I have added the checkBoxView to my ListView
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<TextView
android:id="#+id/textViewWord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/fstRow"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textViewTranslate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textViewWord"
android:layout_below="#+id/textViewWord"
android:textColor="#ff1009"
android:text="#string/scndRow"
android:textAppearance="?android:attr/textAppearanceMedium" />
<CheckBox
android:id="#+id/starCheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:button="#android:drawable/btn_star"
android:focusable="false"
/>
</RelativeLayout>
here is my code
package com.wts.ui;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
public final static int REQUEST_CODE = 1;
private WordsDBAdapter dbAdapter;
private SimpleCursorAdapter dataAdapter;
private Button button;
private EditText editWord;
private EditText editTranslate;
private ListView listView;
private String selectedWord;
private Cursor cursor;
//context menu
private final static int IDM_EDIT = 101;
private final static int IDM_DELETE = 102;
//options menu
private static final int IDM_ABOUT = 201;
private static final int IDM_EXIT = 202;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbAdapter = new WordsDBAdapter(this);
dbAdapter.open();
button = (Button)findViewById(R.id.buttonAddWord);
listView = (ListView)findViewById(R.id.listWords);
displayListView();
registerForContextMenu(listView);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Add some words, please",
Toast.LENGTH_LONG).show();
}
});
//================ListView onLongClick========================
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
cursor = (Cursor)listView.getItemAtPosition(arg2);
selectedWord = cursor.getString(0);
return false;
}
});
//================Button onClick========================
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
editWord = (EditText)findViewById(R.id.editWord);
editTranslate = (EditText)findViewById(R.id.editTranslate);
String word = editWord.getText().toString();
String translate = editTranslate.getText().toString();
if(word.length() > 0 && translate.length() > 0){
dbAdapter.insertWord(word,translate , "noDscrpt");
displayListView();
editWord.setText("");
editTranslate.setText("");
}
}
});
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId() == R.id.listWords) {
String[] menuItems = getResources().getStringArray(
R.array.contextMenuItems);
menu.add(Menu.NONE, IDM_EDIT, Menu.NONE, menuItems[0]);
menu.add(Menu.NONE, IDM_DELETE, Menu.NONE, menuItems[1]);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case IDM_EDIT:
Intent intent = new Intent(this, EditActivity.class);
intent.putExtra(getResources().getString(R.string.fstRow),
cursor.getString(1));
intent.putExtra(getResources().getString(R.string.scndRow),
cursor.getString(2));
intent.putExtra(getResources().getString(R.string.thrdRow),
cursor.getString(3));
startActivityForResult(intent, REQUEST_CODE);
break;
case IDM_DELETE:
dbAdapter.deleteWord(selectedWord);
displayListView();
break;
}
return true;
}
#SuppressWarnings("deprecation")
private void displayListView() {
Cursor cursor = dbAdapter.fetchAllWords();
String[] columns = new String[] {
WordsDBAdapter.KEY_WORD,
WordsDBAdapter.KEY_TRANSLATION,
};
int[] to = new int[] {
R.id.textViewWord,
R.id.textViewTranslate,
};
dataAdapter = new SimpleCursorAdapter(this, R.layout.word_info, cursor,
columns, to);
listView.setAdapter(dataAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
String[] menuItems = getResources().getStringArray(R.array.options_menu_items);
menu.add(Menu.NONE,IDM_ABOUT,Menu.NONE,menuItems[1]);
menu.add(Menu.NONE,IDM_EXIT,Menu.NONE,menuItems[2]);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item)
{
switch(item.getItemId())
{
case IDM_ABOUT:
{
Intent intent = new Intent(MainActivity.this,AboutActivity.class);
startActivity(intent);
break;
}
case IDM_EXIT:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
break;
}
return true;
}
#Override
protected void onActivityResult(int requestCode,int resultCode,Intent intent)
{
if(resultCode == RESULT_OK && requestCode == REQUEST_CODE)
{
if(intent.hasExtra(getResources().getString(R.string.fstRow)))
{
dbAdapter.changeValue(
selectedWord,
intent.getExtras().getString(getResources().getString(R.string.fstRow)),
intent.getExtras().getString(getResources().getString(R.string.scndRow)),
intent.getExtras().getString(getResources().getString(R.string.thrdRow))
);
displayListView();
}
}
}
}
How to get listViewItem that holds CheckBox that I have been clicked ?
Do i Need to set OnClickListener on CheckBox? but what next ?
Please help
thnx!
You should create your custom adapter , and you can catch your checkbox its getView method
public class CustomListAdapter extends ArrayAdapter<String> {
private Activity context;
private ListItemRow itemRow;
private String[] list;
private LayoutInflater layoutInflater;
public CustomListAdapter(Activity context, String[] list) {
super(context, R.layout.main, list);
this.context = context;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
itemRow = new ListItemRow();
layoutInflater = context.getLayoutInflater();
rowView = layoutInflater.inflate(R.layout.word_info, null, true);
itemRow.starCheck= (ChechBox) rowView.findViewById(R.id.starCheck);
itemRow.textViewTranslate= (TextView) rowView.findViewById(R.id.textViewTranslate);
} else {
itemRow = (ListItemRow) rowView.getTag();
}
itemRow.starCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
itemRow.textViewTranslate.setText("starCheck clicked");
}
});
return rowView;
}
private class ListItemRow {
private ChechBox starCheck;
private TextView textViewTranslate;
}
}
Related
I am developer a Apps which contain Various Name & Country List. I want to pass Employee Name & Country name to another activity on click on Child Item of Expandable ListView.
How to set On Click Listener Method on my Activity?
package nasir.main.activity;
import java.util.ArrayList;
import nasir.adapter.EntryItem;
import nasir.adapter.MyListAdapter;
import nasir.adapter.SectionItem;
import nasir.bd.poem.R;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.SearchView;
public class Employee_List extends Activity implements SearchView.OnQueryTextListener, SearchView.OnCloseListener {
Button Collapse;
Button Expand;
private SearchView search;
private MyListAdapter listAdapter;
private ExpandableListView myList;
private ArrayList<SectionItem> section = new ArrayList<SectionItem>();
ArrayList<EntryItem> items = new ArrayList<EntryItem>();
ExpandableListView expandableList = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.poem_list);
expandableList = (ExpandableListView) findViewById(R.id.expandableList);
Expand = (Button) findViewById(R.id.Expand);
Collapse = (Button) findViewById(R.id.Collapse);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
search = (SearchView) findViewById(R.id.search);
search.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
Collapse.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
myList.collapseGroup(i);
}
Collapse.setVisibility(View.GONE);
Expand.setVisibility(View.VISIBLE);
}
});
Expand.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
myList.expandGroup(i);
}
Expand.setVisibility(View.GONE);
Collapse.setVisibility(View.VISIBLE);
}
});
// display the list
displayList();
// expand all Groups
// expandAll();
collapseAll();
}
// method to expand all groups
private void expandAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++) {
myList.expandGroup(i);
}
}
//method to Collapse all groups
private void collapseAll() {
int count = listAdapter.getGroupCount();
for (int i = 0; i < count; i++){
myList.collapseGroup(i);
}
}
// method to expand all groups
private void displayList() {
// display the list
load_Part_1_Data();
// get reference to the ExpandableListView
myList = (ExpandableListView) findViewById(R.id.expandableList);
// create the adapter by passing your ArrayList data
listAdapter = new MyListAdapter(Poem_List.this, section);
// attach the adapter to the list
myList.setAdapter(listAdapter);
myList.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView arg0, View arg1, int arg2,
int arg3, long arg4) {
// TODO Auto-generated method stub
Intent intent = new Intent(Poem_List.this, Details_Information.class);
startActivity(intent);
return false;
}
});
}
private void load_Part_1_Data() {
items = new ArrayList<EntryItem>();
section.add(new SectionItem(R.drawable.ic_launcher, "", items));
items.add(new EntryItem(R.drawable.ic_launcher, "Margerate Milan", "Computer Operator", getString(R.string.app_name)));
items.add(new EntryItem(R.drawable.ic_launcher, "Abraham Jhon", "Salse Man", getString(R.string.app_name)));
items = new ArrayList<EntryItem>();
section.add(new SectionItem(R.drawable.blank_image, "", items));
items.add(new EntryItem(R.drawable.ic_launcher, "England", "Europe", getString(R.string.app_name)));
items.add(new EntryItem(R.drawable.ic_launcher, "Japan", "Asia", getString(R.string.app_name)));
}
#Override
public boolean onClose() {
listAdapter.filterData("");
expandAll();
return true;
}
#Override
public boolean onQueryTextChange(String query) {
listAdapter.filterData(query);
expandAll();
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
listAdapter.filterData(query);
expandAll();
return false;
}
}
MyListAdapter.Class
package nasir.adapter;
import java.util.ArrayList;
import nasir.bd.poem.R;
import nasir.main.activity.Details_Information;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyListAdapter extends BaseExpandableListAdapter {
private Context context;
private ArrayList<SectionItem> continentList;
private ArrayList<SectionItem> originalList;
public MyListAdapter(Context context, ArrayList<SectionItem> continentList) {
this.context = context;
this.continentList = new ArrayList<SectionItem>();
this.continentList.addAll(continentList);
this.originalList = new ArrayList<SectionItem>();
this.originalList.addAll(continentList);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<EntryItem> countryList = continentList.get(groupPosition).getSectionList();
return countryList.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View view, ViewGroup parent) {
final EntryItem country = (EntryItem) getChild(groupPosition, childPosition);
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.child_row, null);
}
ImageView Rank = (ImageView) view.findViewById(R.id.Rank);
TextView Poem = (TextView) view.findViewById(R.id.Poem);
TextView Poetry = (TextView) view.findViewById(R.id.Poetry);
Rank.setImageResource(country.getRank());
Poem.setText(country.getPoem().trim());
Poetry.setText(country.getPoetry().trim());
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, Details_Information.class);
Bundle bundle=new Bundle();
intent.putExtras(bundle);
intent.putExtra("header", country.getDetails_Doc());
context.startActivity(intent);
}
});
return view;
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<EntryItem> countryList = continentList.get(groupPosition).getSectionList();
return countryList.size();
}
#Override
public Object getGroup(int groupPosition) {
return continentList.get(groupPosition);
}
#Override
public int getGroupCount() {
return continentList.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isLastChild, View view, ViewGroup parent) {
SectionItem continent = (SectionItem) getGroup(groupPosition);
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.group_row, null);
}
TextView heading = (TextView) view.findViewById(R.id.heading);
heading.setText(continent.getName().trim());
ImageView Group_icon = (ImageView) view.findViewById(R.id.Group_Icon);
Group_icon.setImageResource(continent.getIcon());
return view;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void filterData(String query) {
query = query.toLowerCase();
Log.v("MyListAdapter", String.valueOf(continentList.size()));
continentList.clear();
if (query.isEmpty()) {
continentList.addAll(originalList);
} else {
for (SectionItem continent : originalList) {
ArrayList<EntryItem> countryList = continent.getSectionList();
ArrayList<EntryItem> newList = new ArrayList<EntryItem>();
for (EntryItem country : countryList) {
if (country.getPoem().toLowerCase().contains(query) || country.getPoetry().toLowerCase().contains(query) ) {
newList.add(country);
}
}
if (newList.size() > 0) {
SectionItem nContinent = new SectionItem(continent.getIcon(), continent.getName(), newList);
continentList.add(nContinent);
}
}
}
Log.v("MyListAdapter", String.valueOf(continentList.size()));
notifyDataSetChanged();
}
}
In the Employee_List activity , you can access the data through index of child and group obtaining from ChildClickListener
myList.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView arg0, View arg1, int arg2,
int arg3, long arg4) {
// TODO Auto-generated method stub
//Here You can access the child data by
final EntryItem country = (EntryItem) listAdapter .getChild(arg2, arg3);
//From here you can pass the data through Intent
...
return false;
}
});
here I have a String array of rootCategoryID and a String categoryID.
On my custom ListView I want to pass different IDs for each of the rows.
But I can't make it work! Here's my code:
package ir.zabardast.onlinemarket;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class Main extends ListActivity {
String[] rootCategoryName = new String[6];
String[] rootCategoryImage = new String[6];
String[] rootCategoryID = new String[6];
int categoryCount;
String categoryID = "0";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(true){
setContentView(R.layout.activity_main);
HandleXML hxml = new HandleXML();
String url = "http://karakaal.com/market/category.xml";
String object = "category";
hxml.fetchXML(url, object);
while(hxml.parsingComplete);
categoryCount = hxml.getCategories().size();
for (int i = 0; i < categoryCount; i++) {
if(hxml.getCategories().get(i).getParentId() == 0){
rootCategoryName[i] = hxml.getCategories().get(i).getName();
}
}
for (int i = 0; i < categoryCount; i++) {
if(hxml.getCategories().get(i).getParentId() == 0){
rootCategoryImage[i] = hxml.getCategories().get(i).getImage();
}
}
for (int i = 0; i < categoryCount; i++) {
if(hxml.getCategories().get(i).getParentId() == 0){
rootCategoryImage[i] = hxml.getCategories().get(i).getId();
}
}
setListAdapter(new MyAdapter(this,
android.R.layout.simple_list_item_1,
R.id.listName,
rootCategoryName));
ListView listView = getListView();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View view, int i, long l) {
Intent intent = new Intent(Main.this, CategoryList.class);
intent.putExtra("categoryID", categoryID);
startActivity(intent);
}
});
} else if (!checkWifi()) {
setContentView(R.layout.wifi_check);
}
}
private class MyAdapter extends ArrayAdapter<String>{
public MyAdapter(Context context, int resource, int textViewResourceId,
String[] rootCategoryName) {
super(context, resource, textViewResourceId, rootCategoryName);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list, parent, false);
String[] products = rootCategoryName;
ImageView iv = (ImageView) row.findViewById(R.id.listImage);
TextView tv = (TextView) row.findViewById(R.id.listName);
tv.setText(products[position]);
int loader = R.drawable.ic_launcher;
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
String baseURL = "http://karakaal.com/market/";
imgLoader.DisplayImage(baseURL + rootCategoryImage[position], loader, iv);
categoryID = rootCategoryID[position];
return row;
}
}
#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;
}
public boolean checkWifi()
{
ConnectivityManager conman = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean wifi = conman.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
if (wifi)
return true;
else
return false;
}
}
As you can see I use a variable to set categoryID in my private class
I want to pass rootCategoryID of each row by an Intent to the next activity when each row is clicked
you can get categoryID by position of ListView clicked
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View view, int i, long l) {
Intent intent = new Intent(Main.this, CategoryList.class);
intent.putExtra("categoryID", rootCategoryID[i]);//here CategoryId
startActivity(intent);
}
});
I managed to get Dialog to show up on the long click by implementing this code:
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(view.getContext()).show();
return true;
}
});
Unfortunately, when the dialog opens and prompts for new text input, when clicked ok, no changes are made to the list.
Here is the Dialog file:
package com.example.classorganizer;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
class EditListItemDialog extends Dialog implements View.OnClickListener {
private View editText;
public EditListItemDialog(Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
}
#Override
public void onClick(View v) {
((TextView) editText).getText().toString();//here is your updated(or not updated) text
dismiss();
}
}
Here is the file containing list:
package com.example.classorganizer;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.cookbook.data.Constants;
import com.cookbook.data.MyDB;
public class Monday extends ListActivity {
private static final int MyMenu = 0;
MyDB dba;
DiaryAdapter myAdapter;
private class MyDiary{
public MyDiary(String t, String c){
title=t;
content=c;
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(view.getContext()).show();
return true;
}
});
}
public String title;
public String content;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
dba = new MyDB(this);
dba.open();
setContentView(R.layout.fragment_monday);
super.onCreate(savedInstanceState);
myAdapter = new DiaryAdapter(this);
this.setListAdapter(myAdapter);
}
private class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
/** Called when the user clicks the Edit button */
public void visitDiary(View view) {
Intent intent = new Intent(this, Diary.class);
startActivity(intent);
}
/** Called when the user clicks the back button */
public void visitSchedule(View view) {
Intent intent = new Intent(this, DisplayScheduleScreen.class);
startActivity(intent);
}
}
Here is an xml file for dialog:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/relativeLayout4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" >
<EditText
android:id="#+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK" />
</RelativeLayout>
</LinearLayout>
I don't understand why the rows are not being updated with data entered through Dialog file...
#Override
public void onClick(View v) {
((TextView) editText).getText().toString();//here is your updated(or not updated) text
dismiss();
}
You are getting the value from TextView of the dialog ,have u added the data to the list.
Update the data to the list
fragment_monday.add(((TextView) editText).getText().toString());
Is it possible to have such functionality in android? When user longclicks row in a list popup window opens with option to edit content?
Yes it is. First of all you need to create your own Dialog with appropriate xml:
private static class EditListItemDialog extends Dialog implements View.OnClickListener {
private EditText editText;
public EditListItemDialog(Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
Button btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
}
#Override
public void onClick(View v) {
editText.getText().toString();//here is your updated(or not updated) text
dismiss();
}
}
Then add listener at setOnLongClickListener:
ListView listView = new ListView(this);
listView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
new EditListItemDialog(v.getContext()).show();
return true;
}
});
Finally you need to update data in your ListView. The right way is to update Adapter of your list view which finally will update ListView.
Ok, I managed to make Dialog file as in your example:
package com.example.classorganizer;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
class EditListItemDialog extends Dialog implements View.OnClickListener {
private View editText;
public EditListItemDialog(Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
}
#Override
public void onClick(View v) {
((TextView) editText).getText().toString();//here is your updated(or not updated) text
dismiss();
}
}
I created an xml file for Dialog file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK" />
</LinearLayout>
Then I updated my Display List file with this code:
ListView listView = new ListView(Monday.this);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(view.getContext()).show();
return true;
}
});
And here is full file that displays list of rows to be edited upon Long Click:
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.cookbook.data.Constants;
import com.cookbook.data.MyDB;
public class Monday extends ListActivity {
private static final int MyMenu = 0;
MyDB dba;
DiaryAdapter myAdapter;
private class MyDiary{
public MyDiary(String t, String c){
title=t;
content=c;
}
public String title;
public String content;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
dba = new MyDB(this);
dba.open();
setContentView(R.layout.fragment_monday);
super.onCreate(savedInstanceState);
myAdapter = new DiaryAdapter(this);
this.setListAdapter(myAdapter);
}
private class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
//new code below
ListView listView = new ListView(Monday.this);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(view.getContext()).show();
return true;
}
}); //end of new code
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
/** Called when the user clicks the Edit button */
public void visitDiary(View view) {
Intent intent = new Intent(this, Diary.class);
startActivity(intent);
}
/** Called when the user clicks the back button */
public void visitSchedule(View view) {
Intent intent = new Intent(this, DisplayScheduleScreen.class);
startActivity(intent);
}
}
There you can see where I put the new code. Unfortunately, upon long click row is not being updated. I mean, the dialog file seems that is not being launched. Is it because I put the code in the wrong place or am I missing something else?
I am doing an contact list android application but i have a small problem with my screens.
Here is my search.xml code:
<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<EditText android:id="#+id/searchText"
android:hint="#string/searchDefault"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
<Button android:id="#+id/searchButton"
android:text="Search"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
enter code here
Here is my detalii.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
My problem is that my screen appears like image from below but i want detalii to appear on entire screen.I dont know what am i doing wrong.Could anybody give me a solution?
This is my search.java:
package org.example.dbcontactconsole;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import static android.provider.BaseColumns._ID;
public class Search extends ListActivity {
private static int[] TO = {R.id.rowid,R.id.name, R.id.mobilephone, R.id.email };
private static String[] FROM = {_ID,DbConstants.NAME, DbConstants.PHONE, DbConstants.EMAIL, };
private Button sButton;
private ListView lv1;
private static SQLiteDatabase db;
private DbCreate contacts;
private Cursor cursor;
private EditText searchText;
protected SimpleCursorAdapter adapter;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
searchText=(EditText)findViewById(R.id.searchText);
sButton=(Button)findViewById(R.id.searchButton);
sButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
showDatabaseContent();
lv1 = getListView();
lv1.setTextFilterEnabled(true);
}
});
}
private Cursor getContacts() {
db = contacts.getReadableDatabase();
cursor = db.rawQuery("SELECT _id,name, phone, email FROM contactTest1 WHERE name LIKE ?",
new String[]{searchText.getText().toString()+"%"});
startManagingCursor(cursor);
return cursor;
}
public void showDatabaseContent(){
contacts = new DbCreate(this);
try {
cursor = getContacts();
showContacts(cursor);
} finally {
contacts.close();
db.close();
}
}
private void showContacts(Cursor cursor) {
//set up data binding
adapter = new SimpleCursorAdapter(this, R.layout.item, cursor, FROM, TO);
setListAdapter(adapter);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
Intent abaintent = new Intent(this,Detalii.class);
Cursor cursor = (Cursor) adapter.getItem(position);
abaintent.putExtra("Contact_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(abaintent);
}
}
Here is my Detalii.java:
package org.example.dbcontactconsole;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Detalii extends ListActivity
{
protected TextView contactName;
protected TextView contactPhone;
protected TextView email;
protected int contactId;
protected List<Actiune> actiune;
protected ActiuneAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detalii);
contactId = getIntent().getIntExtra("Contact_ID",0);
SQLiteDatabase db = (new DbCreate(this)).getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT name,phone,email FROM contactTest1 WHERE _id=?",new String[]{""+contactId});
if (cursor.getCount() == 1)
{
cursor.moveToFirst();
contactName = (TextView) findViewById(R.id.name);
contactName.setText(cursor.getString(cursor.getColumnIndex("name")));
actiune= new ArrayList<Actiune>();
String phoneString=cursor.getString(cursor.getColumnIndex("phone"));
if (phoneString!=null)
{
actiune.add(new Actiune("Suna la numar",phoneString,Actiune.ACTION_CALL));
}
String stringemail = cursor.getString(cursor.getColumnIndex("email"));
if (stringemail != null) {
actiune.add(new Actiune("Email", stringemail,Actiune.ACTION_EMAIL));
}
adapter = new ActiuneAdapter();
setListAdapter(adapter);
}
}
public void onListItemClick(ListView parent, View view, int position, long id) {
Actiune action = actiune.get(position);
Intent intent;
switch (action.getType()) {
case Actiune.ACTION_CALL:
Uri callUri = Uri.parse("tel:" + action.getData());
intent = new Intent(Intent.ACTION_CALL, callUri);
startActivity(intent);
break;
case Actiune.ACTION_EMAIL:
intent = new Intent(Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{action.getData()});
startActivity(intent);
break;
}
}
class ActiuneAdapter extends ArrayAdapter<Actiune> {
ActiuneAdapter() {
super(Detalii.this, R.layout.actiune_detalii, actiune);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Actiune action = actiune.get(position);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.actiune_detalii, parent, false);
TextView label = (TextView) view.findViewById(R.id.label);
label.setText(action.getLabel());
TextView data = (TextView) view.findViewById(R.id.data);
data.setText(action.getData());
return view;
}
}
}
Here is my DBconsole.java:
package org.example.dbcontactconsole;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.view.View;
import android.app.ListActivity;
import static android.provider.BaseColumns._ID;
public class DbContactConsole extends ListActivity {
private static String[] FROM = {_ID,DbConstants.NAME };
private DbCreate contacts;
private static SQLiteDatabase db;
private static int[] TO = {R.id.rowid,R.id.name,};
private ListView lv1;
private static String itemId;
private Cursor cursor;
static final int CONTACT_CANCELED = 0;
static final int CONTACT_ADDED = 1;
static final int CONTACT_MODIFIED = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showDatabaseContent();
lv1 = getListView();
lv1.setTextFilterEnabled(true);
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
cursor = (Cursor) a.getItemAtPosition(position);
itemId = cursor.getString(0);
openOptionsMenu();
}
});
lv1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id){
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
//selected item index from ListView
public void showDialogItemId(long itemId){
Toast.makeText(this, "Menu item selected index is" + Long.toString(itemId), Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.modifyitem:
if(null != itemId){
Bundle contactToModify = new Bundle();
contactToModify.putString("cFirstName", cursor.getString(1));
contactToModify.putString("cMobilePhone", cursor.getString(2));
contactToModify.putString("cEmail", cursor.getString(3));
contactToModify.putString("mod_type", "modifyPerson");
Intent intent = new Intent(this, ContactDetails.class);
intent.setClass(this, ContactDetails.class);
intent.putExtras(contactToModify);
startActivityForResult(intent, CONTACT_MODIFIED);
}else{
Toast.makeText(this, "Select Contact to modify", Toast.LENGTH_LONG).show();
}
break;
case R.id.additem:
Intent i = new Intent(this, ContactDetails.class);
Bundle bun = new Bundle();
bun.putString("mod_type", "addPerson");
i.setClass(this, ContactDetails.class);
i.putExtras(bun);
startActivityForResult(i, CONTACT_ADDED);
break;
case R.id.removeitem:
if(null != itemId){
removeContact(itemId);
showDatabaseContent();
}
else{
Toast.makeText(this, "Select Contact to delete", Toast.LENGTH_LONG).show();
}
break;
case R.id.search:
Intent j =new Intent(this,Search.class);
j.setClass(this, Search.class);
startActivity(j);
break;
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
// See which child activity is calling us back.
switch (resultCode) {
case CONTACT_ADDED:
// This is the standard resultCode that is sent back if the
// activity crashed or didn't doesn't supply an explicit result.
if (resultCode == RESULT_FIRST_USER){
Bundle bundle = new Bundle();
bundle = intent.getBundleExtra("contactData");
addContact(bundle);
showDatabaseContent();
}
else{
Toast.makeText(this, "CANCEL CONTACT BUTTON PRESSED", Toast.LENGTH_LONG).show();
}
break;
case CONTACT_MODIFIED:
if (resultCode == 2){
Bundle bundle = new Bundle();
bundle = intent.getBundleExtra("contactData");
modifyContact(bundle);
showDatabaseContent();
}
else{
Toast.makeText(this, "MODIFY CONTACT FAILED", Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
//method removes item from database
private void removeContact(String itemId){
db = contacts.getWritableDatabase();
db.delete(DbConstants.TABLE_NAME, "_ID=" + itemId, null);
}
private void addContact(Bundle bundle) {
// Insert a new record into the Events data source.
// You would do something similar for delete and update.
db = contacts.getWritableDatabase();
ContentValues vals = new ContentValues();
vals.put(DbConstants.NAME, bundle.getString("contactFirstName"));
vals.put(DbConstants.PHONE, bundle.getString("contactMobilePhone"));
vals.put(DbConstants.EMAIL, bundle.getString("contactEmail"));
db.insertOrThrow(DbConstants.TABLE_NAME, null, vals);
}
//method should modify existing Contact
private void modifyContact(Bundle bundle){
db = contacts.getWritableDatabase();
ContentValues vals = new ContentValues();
vals.put(DbConstants.NAME, bundle.getString("contactFirstName"));
vals.put(DbConstants.PHONE, bundle.getString("contactMobilePhone"));
vals.put(DbConstants.EMAIL, bundle.getString("contactEmail"));
db.update(DbConstants.TABLE_NAME, vals, _ID+"="+itemId, null);
}
private Cursor getContacts() {
db = contacts.getReadableDatabase();
cursor = db.query(DbConstants.TABLE_NAME, FROM, null, null, null,
null,DbConstants.NAME);
startManagingCursor(cursor);
return cursor;
}
public void showDatabaseContent(){
contacts = new DbCreate(this);
try {
cursor = getContacts();
showContacts(cursor);
} finally {
contacts.close();
db.close();
}
}
private void showContacts(Cursor cursor) {
//set up data binding
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item, cursor, FROM, TO);
setListAdapter(adapter);
}
}
Do you have to have the orientation as vertical? Could you change that for detalii.xml to be horizontal so it fills the parent horizontally instead of vertically?
android:orientation="vertical"