how to pass a ListView to my Contextmenu item? - android

on my deleteLogItem i need to pass teh listView so i can find the item in position(id) to delete him.
how can i pass it to him.
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
public class LogActivity extends ListActivity {
private static final int DELETE_ID = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Parse.initialize(this, "sjfsjdfhjshfjhsjdfhsjhfjshdf4",
"sdfgsdfgsdfg76sdfg76s7dfgsd");
final ProgressDialog dialog = ProgressDialog.show(LogActivity.this, "",
"Loading. Please wait...", true);
ParseQuery query = new ParseQuery("Devices");
query.whereEqualTo("Device", "ffffffff-e0d7-1802-8031-65e37f7a7ed3");
query.findInBackground(new FindCallback() {
public void done(List<ParseObject> scoreList, ParseException e) {
if (e == null) {
initListView(scoreList);
dialog.dismiss();
} else {
objectRetrievalFailed();
}
}
});
}
protected void objectRetrievalFailed() {
// TODO Auto-generated method stub
}
private void initListView(List<ParseObject> objects) {
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(
2);
HashMap<String, String> map;
for (ParseObject hashMap : objects) {
map = new HashMap<String, String>();
map.put("line0", hashMap.getObjectId());
map.put("line1", hashMap.getString("Model"));
map.put("line2", hashMap.getString("Device"));
map.put("line3", (String) hashMap.getCreatedAt().toString());
list.add(map);
}
// the from array specifies which keys from the map
// we want to view in our ListView
String[] from = { "line1", "line2", "line3" };
// the to array specifies the TextViews from the xml layout
// on which we want to display the values defined in the from array
int[] to = { R.id.item_title, R.id.item_subtitle, R.id.item_subtitle2 };
// create the adapter and assign it to the listview
SimpleAdapter adapter = new SimpleAdapter(this, list,
R.layout.first_list, from, to);
setListAdapter(adapter);
registerForContextMenu(getListView());
}
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, "Delete");
}
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
switch (item.getItemId()) {
case DELETE_ID:
deleteLogItem(info.id);
return true;
default:
return super.onContextItemSelected(item);
}
}
private void deleteLogItem(long id) {
// TODO Auto-generated method stub
HashMap<String, String> o = (HashMap<String, String>) l
.getItemAtPosition((int)id);
// String selection = l.getItemAtPosition(position).toString();
String selection = o.get("line0");
Toast.makeText(this, selection, Toast.LENGTH_LONG).show();
}
}
EDIT: i just add the line ListView l = getListView();

Related

Android - update ListView from a fragment to another

I am trying to update listView from another fragment class after i delete an item from listView from current class. For example, i delete a consumer that has an expense, then the expense of that consumer will also be deleted. But consumer and expense is different page that using tab control, which is fragment, when i delete consumer, the expense list is not updated, until i go to previous page, then enter the page again. What can i do to update the expense list when consumer from consumer list is deleted? i heard of using broadcast receiver is able to do that, but how can i implement it in my code? I am new in android, please guide me.Thanks
Here is the code for consumer/participant list :
public class Participant extends ListFragment implements OnClickListener{
Intent intent;
TextView friendId;
Button addparticipant;
String eventId;
ListView lv;
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
ArrayList<HashMap<String, String>> friendList = controller
.getAllFriends(queryValues);
if (friendList.size() != 0) {
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
friendId = (TextView) view.findViewById(R.id.friendId);
String valFriendId = friendId.getText().toString();
Intent objIndent = new Intent(getActivity(),
EventPage.class);
objIndent.putExtra("friendId", valFriendId);
startActivity(objIndent);
}
});
lv.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
friendId = (TextView) arg1.findViewById(R.id.friendId);
registerForContextMenu(getListView());
return false;
}
});
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
friendList, R.layout.view_friend_entry, new String[] {
"friendId", "friendName", "friendSpending" },
new int[] { R.id.friendId, R.id.friendName,
R.id.friendSpending });
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.participant, container, false);
addparticipant = (Button) rootView.findViewById(R.id.addpart);
addparticipant.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent objIntent = new Intent(getActivity(),
AddParticipant.class);
objIntent.putExtra("eventId", eventId);
startActivity(objIntent);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
String[] menuItems = getResources().getStringArray(R.array.menu);
for (int i = 0; i < menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
int menuItemIndex = item.getItemId();
EventController controller = new EventController(getActivity());
switch (menuItemIndex) {
case 0:
String valFriendId = friendId.getText().toString();
Intent objIndent = new Intent(getActivity(),
EditParticipant.class);
objIndent.putExtra("friendId", valFriendId);
startActivity(objIndent);
break;
case 1:
String valFriendId2 = friendId.getText().toString();
controller.deleteFriend(valFriendId2);
onResume();
}
return true;
}
#Override
public void onResume() {
super.onResume();
if (getListView() != null) {
updateData();
}
}
private void updateData() {
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
controller.getAllFriends(queryValues),
R.layout.view_friend_entry, new String[] { "friendId",
"friendName", "friendSpending" }, new int[] {
R.id.friendId, R.id.friendName, R.id.friendSpending });
setListAdapter(adapter);
}
}
Here is the code for expense list:
public class Expense extends ListFragment implements OnClickListener {
Button addexp;
TextView expenseId;
ListView lv;
String eventId, friendId;
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
ArrayList<HashMap<String, String>> expenseList = controller
.getAllExpenses(queryValues);
if (expenseList.size() != 0) {
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
expenseId = (TextView) view.findViewById(R.id.expenseId);
String valExpenseId = expenseId.getText().toString();
Intent objIndent = new Intent(getActivity(),
EditExpense.class);
objIndent.putExtra("expenseId", valExpenseId);
startActivity(objIndent);
}
});
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
expenseList, R.layout.view_expense_entry, new String[] {
"expenseId", "expenseName","expenseQuantity" }, new int[] {
R.id.expenseId, R.id.expenseName, R.id.expenseQuantity });
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.expense, container, false);
addexp = (Button) rootView.findViewById(R.id.addexp);
addexp.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent objIntent = new Intent(getActivity(), AddExpense.class);
objIntent.putExtra("eventId", eventId);
startActivity(objIntent);
}
#Override
public void onResume() {
super.onResume();
if (getListView() != null) {
updateData();
}
}
private void updateData() {
EventController controller = new EventController(getActivity());
HashMap<String, String> queryValues = new HashMap<String, String>();
Intent objIntent = getActivity().getIntent();
eventId = objIntent.getStringExtra("eventId");
queryValues.put("eventId", eventId);
SimpleAdapter adapter = new SimpleAdapter(getActivity(),
controller.getAllExpenses(queryValues),
R.layout.view_expense_entry, new String[] { "expenseId",
"expenseName", "expenseQuantity" }, new int[] { R.id.expenseId,
R.id.expenseName, R.id.expenseQuantity });
setListAdapter(adapter);
}
}
Same scenario with me, if you used FragmentPagerAdapter, Try like this in FirstFragment
private void updateSecondFragment(){
//Way to get TagName which generated by FragmentPagerAdapter
String tagName = "android:switcher:" + R.id.pager + ":" + 1; // Your pager name & tab no of Second Fragment
//Get SecondFragment object from FirstFragment
SecondFragment f2 = (SecondFragment)getActivity().getSupportFragmentManager().findFragmentByTag(tagName);
//Then call your wish method from SecondFragment to update appropriate list
f2.updateList();
}
I got that idea by reading this. Then edit a little !
One way could be creating the methods in the activity that contains the two fragments, and access to the fragments methods from the activity. You can update the database and reload the list in the same method.
For example, In the activity
public void updateFragment2(){ ... }
In fragment 1 you should call:
((ActivityClass)getActivity()).updateFragment2();
In the section "Communicating with the Activity" you can see the explanation of this example:
http://developer.android.com/guide/components/fragments.html

Implement OnClickListener to make Show Context Menu With Short Click not Long Click

I have code like this :
public class ListConActivity extends Activity {
private String[] Distro = { "Ubuntu", "Arch Linux", "Mandriva",
"Open Suse", "IGOS Nusantara", "Linux Mint", "Debian", "Fedora",
"CrunchBang", "Backtrack", "Puppy Linux", "OpenBSD", "Slackware",
"BlankOn", "CentOS" };
private String[] pilihan_menu = { "Tambah Data", "Edit Data", "Hapus Data",
"Kirim Data" };
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Arrays.sort(Distro);
ListView list = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, Distro);
list.setAdapter(adapter);
registerForContextMenu(list);
}
public void onCreateContextMenu(ContextMenu menu, View tampil,
ContextMenuInfo menuInfo) {
if (tampil.getId() == R.id.list) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
menu.setHeaderTitle(Distro[info.position]);
for (int i = 0; i < pilihan_menu.length; i++) {
menu.add(Menu.NONE, i, i, pilihan_menu[i]);
}
}
}
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
.getMenuInfo();
String aksi = pilihan_menu[item.getItemId()];
String nama_pilihan = Distro[info.position];
String isi = String.format("Anda melakukan operasi %s pada pilihan %s",
aksi, nama_pilihan);
Toast.makeText(this, isi, Toast.LENGTH_LONG).show();
return true;
}
}
Its work perfectly showing contextmenu for long click. I changed the code to implement the onclick to be able to open a context menu with a short click.
public class ListConActivity extends Activity implements OnClickListener {
private String[] Distro = { "Ubuntu", "Arch Linux", "Mandriva",
"Open Suse", "IGOS Nusantara", "Linux Mint", "Debian", "Fedora",
"CrunchBang", "Backtrack", "Puppy Linux", "OpenBSD", "Slackware",
"BlankOn", "CentOS" };
private String[] pilihan_menu = { "Tambah Data", "Edit Data", "Hapus Data",
"Kirim Data" };
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Arrays.sort(Distro);
ListView list = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, Distro);
list.setAdapter(adapter);
registerForContextMenu(list);
list.setOnClickListener(this);
}
public void onCreateContextMenu(ContextMenu menu, View tampil,
ContextMenuInfo menuInfo) {
if (tampil.getId() == R.id.list) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
menu.setHeaderTitle(Distro[info.position]);
for (int i = 0; i < pilihan_menu.length; i++) {
menu.add(Menu.NONE, i, i, pilihan_menu[i]);
}
}
}
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
.getMenuInfo();
String aksi = pilihan_menu[item.getItemId()];
String nama_pilihan = Distro[info.position];
String isi = String.format("Anda melakukan operasi %s pada pilihan %s",
aksi, nama_pilihan);
Toast.makeText(this, isi, Toast.LENGTH_LONG).show();
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
openContextMenu(v);
}
}
Compile success.. But i get force close. Can u help me? thanks dude!
You have set click listener for ListView, not list items. Use setOnItemClickListener and AdapterView.OnItemClickListener
yeaH: do a setOnItemClickListener for listView & in that click method call openContextMenu(view) from Activity class

How to navigate in Tab Application in Android? with my sources classes

// The below Fourth is fourth tab activity in my project so inside it am having few more
other activites like MasjidsearchActivity inside on item .it is displaying as separate activity but i want with remaining tabs
package com.hands.iagd.app;
import java.util.ArrayList;
import java.util.List;
import android.R.layout;
import android.R.string;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class Fourth extends Activity {
static String[] values,Masjeed,Alaram;
String[] adjust_calender;
ListView lv1,lv2,lv3,lv4;
public static List<String> Calculation_method=new ArrayList<String>();
int index,index2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fourth);
lv1=(ListView)findViewById(R.id.lv1);
lv2=(ListView)findViewById(R.id.lv2);
lv3=(ListView)findViewById(R.id.lv3);
lv4=(ListView)findViewById(R.id.lv4);
values = new String[] {"Jafari","Karachi","ISNA","MWL","Makkah","Egypt","Custom","Tehran"};
Masjeed = new String[] {"IAGD Masjid"};
Alaram = new String[] {""};
String hijriString="Hijri Calender "+Adjust_Time.hijriAdjust;
adjust_calender= new String[]{hijriString};
lv1.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice,values));
lv1.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
index=First.index;
lv1.setItemChecked(index, true);
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
index=arg2;
First.index=arg2;
System.out.println("index " +index);
}
});
Masjeed=MasjidsearchActivity.selectedmasjid;
lv2.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,Masjeed));
lv2.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lv2.setItemChecked(index2, true);
lv2.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
index2=arg2;
First.index2=arg2;
System.out.println("index " +index2);
Intent masjid=new Intent(Fourth.this,MasjidsearchActivity.class);
startActivity(masjid);
}
});
lv3.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,adjust_calender));
lv3.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Adjust_Time.sahurORiftar="hijri";
Intent i=new Intent(Fourth.this,Adjust_Time.class);
startActivity(i);
}
});
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
String hijriString="Hijri Calender "+Adjust_Time.hijriAdjust;
adjust_calender= new String[]{hijriString};
lv1.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice,values));
lv1.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
index=First.index;
lv1.setItemChecked(index, true);
lv2.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice,Masjeed));
lv2.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
index2=First.index2;
lv2.setItemChecked(index2, true);
lv3.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,adjust_calender));
super.onResume();
}
}
//here is MasjidsearchActivity class
package com.hands.iagd.app;
/**
* ©2010 by androidblogger.ch
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MasjidsearchActivity extends Activity {
RadioButton rb1 ;
Button b1,btn;
EditText edittext;
ListView mainListView;
static String[] selectedmasjid=new String[] {"IAGD Masjid"};;
List<Hashtable<String,String>> list1 = new ArrayList<Hashtable<String,String>>();
int textlength = 0;
ArrayList<String> text_sort = new ArrayList<String>();
ArrayList<Integer> image_sort = new ArrayList<Integer>();
ArrayList<String> text_sort2 = new ArrayList<String>();
// ArrayList which contains our HashMap's with different objects
private ArrayList<HashMap<String, Object>> myList;
private ArrayList<HashMap<String, Object>> myList1;
private ArrayList<HashMap<String, Object>> filterList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.masjidlist);
b1=(Button)findViewById(R.id.button1);
btn=(Button)findViewById(R.id.btn);
btn.setOnCreateContextMenuListener(this);
//rb1=(RadioButton)findViewById(R.id.radioButton1);
/*rb1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
System.out.println( "inside radio buttons" );
}});*/
mainListView = (ListView) findViewById(R.id.main_listview);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
IAGDAPPActivity.settingCurrentTab=3;
Intent int1 = new Intent(MasjidsearchActivity.this, IAGDAPPActivity.class);
startActivity(int1);
}});
edittext = (EditText) findViewById(R.id.search_mycontact);
// Create Hash Map
myList = new ArrayList<HashMap<String, Object>>();
myList1 = new ArrayList<HashMap<String, Object>>();
filterList = new ArrayList<HashMap<String, Object>>();
edittext.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after)
{
}
public void onTextChanged(CharSequence s, int start,
int before, int count)
{
textlength = edittext.getText().length();
text_sort.clear();
image_sort.clear();
text_sort2.clear();
filterList.clear();
for (int i = 0; i < myList1.size(); i++)
{
HashMap<String,Object> maps=new HashMap<String, Object>();
maps=myList1.get(i);
String masjidName=maps.get("MosquesNames").toString();
String cityName=maps.get("MosqueCity").toString();
List<String> searchStrring = new ArrayList<String>(Arrays.asList(masjidName.split(" ")));
searchStrring.add(masjidName);
searchStrring.add(cityName);
for (String s123 : searchStrring) {
if (textlength <= s123.length())
{
if (edittext.getText().toString().
equalsIgnoreCase((String) s123.subSequence(0, textlength)))
{
filterList.add(maps);
break;
}
}
/* if (edittext.getText().toString().
equalsIgnoreCase((String) masjidName.subSequence(0, textlength)))
{
//text_sort.add(month[i]);
//image_sort.add(image[i]);
// text_sort2.add(desc[i]);
filterList.add(maps);
}*/
}
}
displayList(filterList);
mainListView = (ListView) findViewById(R.id.main_listview);
mainListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
System.out.println("****3");
}
});
// Fill data
// addDataToList();
addDBFROMCSV();
// View
mainListView = (ListView) findViewById(R.id.main_listview);
// Adapter
/* SimpleAdapter aa = new SimpleAdapter(this, myList, R.layout.row,
new String[] {"name", "address", "city", "icon"},
new int[] {R.id.txt_name, R.id.txt_town, R.id.txt_phone, R.id.img_user});
mainListView.setAdapter(aa);*/
/* SimpleAdapter aa = new SimpleAdapter(this, myList1, R.layout.row,
new String[] {"MosquesNames", "MosqueAddress", "MosqueCity","icon"},
new int[] {R.id.txt_name, R.id.txt_town, R.id.txt_phone, R.id.img_user});
mainListView.setAdapter(aa);
*/ displayList(myList1);
// Listener
mainListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mainListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Get the HashMap of the clicked item
HashMap<String, Object> user = myList1.get(position);
// Get Attribute name of the HashMap
String name = (String)user.get("MosquesNames");
selectedmasjid =new String[] {name};
System.out.println("name:"+selectedmasjid.length);
// Create new Dialog
final Dialog dialog = new Dialog(MasjidsearchActivity.this);
dialog.setTitle(" " + name);
TextView txtDescription = new TextView(MasjidsearchActivity.this);
txtDescription.setPadding(10, 0, 0, 10);
txtDescription.setText("Masjid Selected");
dialog.setContentView(txtDescription);
dialog.setCanceledOnTouchOutside(true);
dialog.show();
}
});
}
public void onCreateContextMenu(ContextMenu menu, View view,ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, view, menuInfo);
CreateMenu(menu);
}
#Override
public boolean onContextItemSelected(MenuItem item)
{
return MenuChoice(item);
}
private void CreateMenu(Menu menu)
{
MenuItem mnu1 = menu.add(0, 0, 0, "Register with us");
{
mnu1.setAlphabeticShortcut('a');
//mnu1.setIcon(R.drawable.image1);
}
MenuItem mnu2 = menu.add(0, 1, 1, "Notify about your Masjid ");
{
mnu2.setAlphabeticShortcut('b');
//mnu2.setIcon(R.drawable.image2);
}
MenuItem mnu3 = menu.add(0, 2, 2, "Cancel");
{
mnu3.setAlphabeticShortcut('c');
//mnu3.setIcon(R.drawable.image3);
}
/* MenuItem mnu4 = menu.add(0, 3, 3, "Item 4");
{
mnu4.setAlphabeticShortcut('d');
}
menu.add(0, 4,4, "Item 5");
menu.add(0, 5,5, "Item 6");
menu.add(0, 6,6, "Item 7");*/
}
private boolean MenuChoice(MenuItem item)
{
switch (item.getItemId())
{
case 0:
Intent i=new Intent(MasjidsearchActivity.this,Register.class);
startActivity(i);
//Toast.makeText(this, "You clicked on Notify",Toast.LENGTH_LONG).show();
return true;
case 1:
Intent i1=new Intent(MasjidsearchActivity.this,masjidnotify.class);
startActivity(i1);
//Toast.makeText(this, "You clicked on Register",Toast.LENGTH_LONG).show();
return true;
case 2:
//Toast.makeText(this, "You clicked on Cancel",Toast.LENGTH_LONG).show();
return true;
/*case 3:
Toast.makeText(this, "You clicked on Item 4",Toast.LENGTH_LONG).show();
return true;*/
/* case 4:
Toast.makeText(this, "You clicked on Item 5",Toast.LENGTH_LONG).show();
return true;
case 5:
Toast.makeText(this, "You clicked on Item 6",Toast.LENGTH_LONG).show();
return true;
case 6:
Toast.makeText(this, "You clicked on Item 7",Toast.LENGTH_LONG).show();
return true;*/
}
return false;
}
private void displayList(ArrayList<HashMap<String, Object>> myLists) {
SimpleAdapter aa = new SimpleAdapter(this, myLists, R.layout.row,
new String[] {"MosquesNames", "MosqueAddress", "MosqueCity","icon"},
new int[] {R.id.txt_name, R.id.txt_town, R.id.txt_phone, R.id.img_user});
mainListView.setAdapter(aa);
mainListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
private void addDBFROMCSV()
{
InputStream is = this.getResources().openRawResource
(R.raw.listofmosquesinusa);
BufferedReader reader = new BufferedReader(new InputStreamReader
(is));
try {
ArrayList< String> list=new ArrayList<String>();
String line;
while ((line = reader.readLine()) != null) {
// do something with "line"
// System.out.println("llllll"+line);
list.add(line);
}
// System.out.println("llllll"+list);
ArrayList<List<String>> arrayList=new ArrayList<List<String>>();
for(int i=0;i<list.size();i++)
{
String s1=list.get(i);
List<String> list12 = new ArrayList<String>(Arrays.asList(s1.split("123456COLUMNDEVIDER")));
// System.out.println("List1 is "+list1);
// System.out.println("List size is "+list1.size());
arrayList.add(list12);
}
ArrayList<List<String>> updatedList =new ArrayList<List<String>>();
for(int k=0;k<arrayList.size();k++)
{
List<String> l111=new ArrayList<String>();
List<String> l1=new ArrayList<String>();
l1=arrayList.get(k);
for(int j=0;j<l1.size();j++)
{
String sss1=l1.get(j);
if(sss1.length()<2)
{
l111.add(" ");
// System.out.println("Values in empty"+sss1);
}
else
{
char c1=sss1.charAt(0);
if(c1==',' )
{
sss1=sss1.substring(1);
}
c1=sss1.charAt(sss1.length()-1);
if(c1==',' )
{
sss1=sss1.substring(0,sss1.lastIndexOf(","));
}
l111.add(sss1);
//System.out.println("Values in "+sss1);
}
}
updatedList.add(l111);
}
System.out.println("updated list"+updatedList);
ArrayList<String> tblList=new ArrayList<String>();
for(int i=0;i<updatedList.size();i++)
{
List<String> oneList=updatedList.get(i);
String x1=oneList.get(0);
String x2=oneList.get(1);
String x3=oneList.get(2);
String x4=oneList.get(3);
String x5=oneList.get(4);
String x6=oneList.get(5);
String x7=oneList.get(6);
String x8=oneList.get(7);
String x9=oneList.get(8);
String x10=oneList.get(9);
// String x11=oneList.get(10);
Hashtable<String, String> hm = new Hashtable<String, String>();
hm.put("Sno", x1);
hm.put("MosquesNames", x2);
hm.put("MosqueAddress", x3);
hm.put("MosqueCity", x4);
hm.put("Mosquestate", x5);
hm.put("Mosquezip", x6);
hm.put("Mosquecountry", x7);
hm.put("Mosquephn1", x8);
hm.put("Mosquephn2", x9);
hm.put("Mosquephn3", x10);
//hm.put("Mosquephn3", x10);
// hm.put("icon", R.drawable.images);
HashMap<String, Object> map1 = new HashMap<String, Object>();
map1.put("Sno", x1);
map1.put("MosquesNames", x2);
map1.put("MosqueAddress", x3);
map1.put("MosqueCity", x4);
map1.put("Mosquestate", x5);
map1.put("Mosquezip", x6);
map1.put("Mosquecountry", x7);
map1.put("Mosquephn1", x8);
map1.put("Mosquephn2", x9);
map1.put("Mosquephn3", x10);
map1.put("icon", R.drawable.images);
myList1.add(map1);
// list1.add(hm) ;
// add=hm.get("MosquesNames")+" "+hm.get("MosqueAddress")+" "+hm.get("MosqueCity");
//tblList.add(add);
}
System.out.println("new:"+myList1);
}
catch (IOException ex) {
// handle exception
}
finally {
try {
is.close();
}
catch (IOException e) {
// handle exception
}
}
}
/**
* This method is used, to fill data into our List
*/
private void addDataToList(){
HashMap<String, Object> map1 = new HashMap<String, Object>();
map1.put("icon", R.drawable.images);
map1.put("name", "Al-Masjidul Al-Kaa'Bah");
map1.put("address", "691 Idlewild Circle - Suite H");
map1.put("city", "Birmingham, Alabama");
HashMap<String, Object> map2 = new HashMap<String, Object>();
map2.put("icon",R.drawable.images);
map2.put("name", "Al-Masjidul Al-Kaa'Bah ");
map2.put("address", "691 Idlewild Circle - Suite H");
map2.put("city", "Birmingham, Alabama");
HashMap<String, Object> map3 = new HashMap<String, Object>();
map3.put("icon", R.drawable.images);
map3.put("name", "Birmingham Islamic Society");
map3.put("address", " ");
map3.put("city", "Birmingham, Alabama");
HashMap<String, Object> map4 = new HashMap<String, Object>();
map4.put("icon", R.drawable.images);
map4.put("name", "Birmingham Mosque");
map4.put("address","1534 19th Street");
map4.put("city", "Birmingham, Alabama");
HashMap<String, Object> map5 = new HashMap<String, Object>();
map5.put("icon", R.drawable.images);
map5.put("name", "Masjid Al-Quran");
map5.put("address", " ");
map5.put("city", "Birmingham, Alabama");
myList.add(map1);
myList.add(map2);
myList.add(map3);
myList.add(map4);
myList.add(map5);
}
}

how to get position in on context item selected in android?

setListAdapter(new ArrayAdapter<String>(this,R.layout.custom_list_item, r));
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
fname=r.get(position);
the above code I got position and name also from array adapter
Like, I need get these all are the values in context menu how can I get it
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Playlist Option");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
public boolean onContextItemSelected(MenuItem item) {
// here I select the particular list value, that the value position I need that is only I delete that position from server. what are the data i fetch here? and its possible to get position from array list?
}
You can use AdapterContextMenuInfo
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.delete:
String itemName = r.get[(int) info.id]; // This item you will delete
// from list
return true;
}
}
public class DataDemo extends Activity {
public ArrayList<HashMap<String, String>> ContactList = new ArrayList<HashMap<String, String>>();
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_PHNO = "phNo";
private static int itemIndex;
private ListView lst;
private List<Contact> contacts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database_demo);
lst = (ListView) findViewById(R.id.lstContact);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId() == R.id.lstContact) {
menu.setHeaderIcon(R.drawable.message);
menu.setHeaderTitle("Contacts");
menu.add(0, 1, Menu.NONE, "Edit Contact");
menu.add(0, 2, Menu.NONE, "Delete Contact");
menu.add(0, 3, Menu.NONE, "Cancel");
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterView.AdapterContextMenuInfo menuInfo;//you can select on context item selected
menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
itemIndex = menuInfo.position;//you will get position of selected item
final Contact con = contacts.get(itemIndex);
switch (item.getItemId()) {
case 1:
Intent editIntent = new Intent(DataDemo.this, UpdateContact.class);
editIntent.putExtra(TAG_ID, con.getID());
editIntent.putExtra(TAG_NAME, con.getName());
editIntent.putExtra(TAG_PHNO, con.getPhNo());
startActivity(editIntent);
break;
case 2:
new AlertDialog.Builder(this)
.setIcon(R.drawable.document_delete)
.setTitle("Confirm Delete")
.setMessage("Are you sure?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
DatabaseHandler db = new DatabaseHandler(
DataDemo.this);
db.DeleteContact(con);
Toast.makeText(DataDemo.this, con.getName() + " Deleted",
Toast.LENGTH_SHORT).show();
fillList();
}
}).setNegativeButton("No", null).show();
break;
default:
break;
}
return super.onContextItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem addNew = menu.add(0, 1, 0, "Create Contact");
addNew.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// TODO Auto-generated method stub
Intent iCreate = new Intent(DataDemo.this, CreateContact.class);
startActivity(iCreate);
return true;
}
});
return true;
}
protected void fillList() {
DatabaseHandler db = new DatabaseHandler(this);
ListAdapter adap;
ContactList.clear();
contacts = db.ReadAllContact();
for (Contact cn : contacts) {
HashMap<String, String> hmap = new HashMap<String, String>();
hmap.put(TAG_NAME, cn.getName());
hmap.put(TAG_PHNO, cn.getPhNo());
ContactList.add(hmap);
adap = new SimpleAdapter(this, ContactList,
R.layout.list_item_view,
new String[] { TAG_NAME, TAG_PHNO }, new int[] {
R.id.lstName, R.id.lstPhNo });
lst.setAdapter(adap);
registerForContextMenu(lst);
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
fillList();
}
}

android delete file using context menu

I've got a Listview showing files currently on the SDcard. When you long press the file, a context menu pops up.
My question is: how do I pass in the selected item to the Context Menu in order to delete the file from the list, and is it possible to also delete it from the SDcard using this? My Code is as follows:
public class PlayListActivity extends ListActivity {
// Songs list
public ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>();
SongsManager plm = new SongsManager();
// get all songs from sdcard
this.songsList = plm.getPlayList();
// looping through playlist
for (int i = 0; i < songsList.size(); i++) {
// creating new HashMap
HashMap<String, String> song = songsList.get(i);
// adding HashList to ArrayList
songsListData.add(song);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, songsListData,
R.layout.playlist_item, new String[] { "songTitle", "songDate" }, new int[] {
R.id.songTitle, R.id.songDate });
setListAdapter(adapter);
// setup ListView item
ListView lv = getListView();
registerForContextMenu(lv);
notifyDataSetChanged();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting listitem index
int songIndex = position;
// Starting new intent
Intent in = new Intent(getApplicationContext(),
Bandboxstage.class);
// Sending songIndex to PlayerActivity
in.putExtra("songIndex", songIndex);
setResult(100, in);
// Closing PlayListView
finish();
}
});
}
private void notifyDataSetChanged() {
// TODO Auto-generated method stub
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.delete:
Toast.makeText(this, "Delete Called.", Toast.LENGTH_SHORT).show();
deleteFile(info.id);
return true;
case R.id.share:
Toast.makeText(this, "Share Called.", Toast.LENGTH_SHORT).show();
default:
return super.onContextItemSelected(item);
}
}
private void deleteFile(long id) {
// TODO Auto-generated method stub
}
}
Well your answer is in your implementation itself. If you notice, in your onContextItemSelected()
, the following statement brings in the info of the item you have selected in your main listview.
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
You can use info.position to find out the position of your item in the list and then get the object from your ArrayList using songsList.get(info.position).
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.delete:
Toast.makeText(this, "Delete Called.", Toast.LENGTH_SHORT).show();
//Make sure songsList is a global variable so that it can be accessed here.
HashMap<String, String> song = songsList.get(info.position);
//Call your delete function to delete the song.
return true;
case R.id.share:
Toast.makeText(this, "Share Called.", Toast.LENGTH_SHORT).show();
default:
return super.onContextItemSelected(item);
}
}
Refer this LINK it passes varialble on long click.
below is the deletefile function
file.delete() will delete the file.

Categories

Resources