My question is how to set on click for the item in my list because in list fragment it need to have a specific id which is android:list so i don't how can i use this.
I have this layout :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fab="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#id/android:list"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true" />
<TextView
android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="30sp"
android:text="" />
<com.getbase.floatingactionbutton.AddFloatingActionButton
android:id="#+id/semi_transparent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fab:fab_plusIconColor="#color/primaryColorDark"
fab:fab_colorNormal="#color/primaryColor"
fab:fab_colorPressed="#color/AccentColor"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
and this list fragment :
public class F1_fr extends ListFragment {
View rootview;
TextView textView1;
ArrayAdapter<String> aa;
ArrayList<String> arrayList = new ArrayList<String>();
SQLiteDatabase db;
ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootview=inflater.inflate(R.layout.f1_lay,container,false);
textView1=(TextView)rootview.findViewById(R.id.textView1);
db = getActivity().openOrCreateDatabase("testDB2", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS test2(mac VARCHAR,mdp VARCHAR,obj VARCHAR);");
aa = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, arrayList);
setListAdapter(aa);
Cursor cursor = db.rawQuery("SELECT * FROM test2", null);
// Toast.makeText(myContext, ""+cursor.getCount(), Toast.LENGTH_LONG).show();
if (cursor.moveToFirst())
{
do
{
arrayList.add(cursor.getString(2));
} while (cursor.moveToNext());
}
rootview.findViewById(R.id.semi_transparent).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(getActivity(),ajout.class);
startActivityForResult(intent, 2);
}
});
return rootview;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 2)
{
//String message=data.getStringExtra("MESSAGE");
Intent intent=new Intent(getActivity(),qr.class);
startActivity(intent);
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
Something like this should do the trick (at least I think this is what you are trying to do)
In onCreateView()
((ListView) rootView.findViewById(android.R.id.list)).
setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
//Do what you want when you click on an item
}
}
Would have posted as a comment since I don't really have time to explain it, but looked sloppy so figured an answer would do better.
Related
I am a newbie programmer in android.I am trying to develop a simple paternity blood test.The logic is like this.I have three spinners and blood group A,B,AB and O will be listed into the spinner.The user have to chose blood type from A,B,AB or O for child,mother and father and then click submit button.The button will do some matching and produce a string result.I have tried several methods whichI found on internet. But still unable to use button click function.
Here is my code.Plz correct my mistake .Thanks.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/btn_paternity"
android:layout_centerHorizontal="true"
android:gravity="center_horizontal"
android:layout_marginTop="52dp"
android:id="#+id/paternity_ans" />
<TextView
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:id="#+id/textView6"
android:text="Father"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:layout_width="100dp"
android:layout_above="#+id/childblds"
android:layout_centerHorizontal="true" />
<TextView
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_marginTop="53dp"
android:id="#+id/textView5"
android:text="Child "
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:layout_width="100dp"
android:layout_marginRight="15dp"
android:layout_marginEnd="15dp"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/btn_paternity"
android:layout_toStartOf="#+id/btn_paternity" />
<Spinner
android:layout_width="100dp"
android:layout_height="wrap_content"
android:spinnerMode="dialog"
android:id="#+id/dadblds"
android:dropDownWidth="match_parent"
android:layout_toLeftOf="#+id/textView4"
android:layout_toStartOf="#+id/textView4"
android:layout_alignBottom="#+id/childblds"
android:layout_alignTop="#+id/childblds" />
<Spinner
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/childblds"
android:spinnerMode="dialog"
android:dropDownWidth="match_parent"
android:layout_marginTop="13dp"
android:layout_below="#+id/textView5"
android:layout_alignLeft="#+id/textView5"
android:layout_alignStart="#+id/textView5" />
<Spinner
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/momblds"
android:spinnerMode="dialog"
android:entries="#array/paternitybldtype"
android:dropDownWidth="match_parent"
android:layout_alignTop="#+id/dadblds"
android:layout_alignLeft="#+id/textView4"
android:layout_alignStart="#+id/textView4" />
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_paternity"
android:layout_below="#+id/dadblds"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp" />
<TextView
android:layout_height="wrap_content"
android:id="#+id/textView4"
android:gravity="center_horizontal"
android:text="Mother"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:layout_width="100dp"
android:layout_marginLeft="9dp"
android:layout_marginStart="9dp"
android:layout_above="#+id/childblds"
android:layout_toRightOf="#+id/textView6"
android:layout_toEndOf="#+id/textView6" />
</RelativeLayout>
</LinearLayout>
Fragments code:
public class Paternitytest extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.paternitytestlo, container, false);
final Button setItem = (Button) view.findViewById(R.id.btn_paternity);
final TextView txt1 = (TextView) view.findViewById(R.id.paternity_ans);
setItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Some if else statement will be applied here by using String c, f and m
}
});
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Spinner childspinner = (Spinner) view.findViewById(R.id.childblds);
Spinner dadspinner = (Spinner) view.findViewById(R.id.dadblds);
Spinner momspinner = (Spinner) view.findViewById(R.id.momblds);
// Spinner Drop down elements
String[] categories = {"A", "B", "O", "AB",};
// Creating adapter for spinner
ArrayAdapter adapter = new ArrayAdapter(
getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, categories);
// Drop down layout style - list view with radio button
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
childspinner.setAdapter(adapter);
dadspinner.setAdapter(adapter);
momspinner.setAdapter(adapter);
// Spinner click listener
childspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String c = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
dadspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String f = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
momspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String m = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
I have made some changes in your code so try this.
public class Paternitytest extends Fragment {
private String childSpinnerString, momSpinnerString, dadspinnerString;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.paternitytestlo,
container, false);
final Button setItem = (Button) view.findViewById(R.id.btn_paternity);
final TextView txt1 = (TextView) view.findViewById(R.id.paternity_ans);
setItem.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
//Some if else statement will be applied here by using String c, f and m
Log.d("Blood groups- ", "Child - " + childSpinnerString + " Mom - " + momSpinnerString + " Dad - " + dadspinnerString);
}
});
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Spinner childspinner = (Spinner) view.findViewById(R.id.childblds);
Spinner dadspinner = (Spinner) view.findViewById(R.id.dadblds);
Spinner momspinner = (Spinner) view.findViewById(R.id.momblds);
// Spinner Drop down elements
String[] categories = {"A", "B", "O", "AB",};
// Creating adapter for spinner
ArrayAdapter adapter = new ArrayAdapter(
getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, categories);
// Drop down layout style - list view with radio button
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
childspinner.setAdapter(adapter);
dadspinner.setAdapter(adapter);
momspinner.setAdapter(adapter);
// Spinner click listener
childspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
childSpinnerString = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
dadspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
dadspinnerString = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
momspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
momSpinnerString = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
Try onClickListener for your button:
btn_paternity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String mom = momblds.getSelectedItem().toString();
}
});
The Listview is displaying some rows instead of all items (sometimes, it's displaying nothing), I couldn't understand why this is happenning. It occurs at first run. After that, it works well, with all items from database filled on the screen. I put vertical orientation in my linear layout xml files and wrap_content height. But the problem is not solved.
This is my main activity :
public class MainActivity extends Activity {
public static final String PREFS_NAME = "MyPrefsFile1";
private TextView mTextView;
private ListView mListView;
ArrayList<WordDefinition> allWordDefinitions=new ArrayList<WordDefinition>();
DictionaryDatabase DictionaryDatabase;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.text);
mListView = (ListView) findViewById(R.id.list);
DictionaryDatabase=new DictionaryDatabase(this);
allWordDefinitions=DictionaryDatabase.getAllWords();
Collections.sort(allWordDefinitions, new CustomComparator());
mListView.setAdapter(new BaseAdapter() {
#Override
public View getView(int position, View view, ViewGroup arg2) {
if (view==null) {
view=getLayoutInflater().inflate(R.layout.list_item, arg2, false);
}
TextView textView=(TextView) view.findViewById(R.id.listItemTextView);
textView.setText(allWordDefinitions.get(position).word);
return view;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return allWordDefinitions.size();
}
});
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
Intent intent =new Intent(MainActivity.this, WordDefinitionDetailActivity.class);
intent.putExtra("word", allWordDefinitions.get(position).word);
intent.putExtra("definition", allWordDefinitions.get(position).definition);
startActivity(intent);
}
});
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Intent wordIntent = new Intent(this, WordActivity.class);
this.finish();
wordIntent.setData(intent.getData());
startActivity(wordIntent);
} else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
showResults(query);
}
}
private void showResults(String query) {
Cursor cursor = managedQuery(DictionaryProvider.CONTENT_URI, null, null,
new String[] {query}, null);
if (cursor == null) {
mTextView.setText(getString(R.string.no_results, new Object[] {query}));
} else {
int count = cursor.getCount();
String countString = getResources().getQuantityString(R.plurals.search_results,
count, new Object[] {count, query});
mTextView.setText(countString);
String[] from = new String[] { DictionaryDatabase.KEY_WORD,
DictionaryDatabase.KEY_DEFINITION };
int[] to = new int[] { R.id.word,
R.id.definition };
SimpleCursorAdapter words = new SimpleCursorAdapter(this,
R.layout.result, cursor, from, to);
mListView.setAdapter(words);
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent wordIntent = new Intent(getApplicationContext(), WordActivity.class);
Uri data = Uri.withAppendedPath(DictionaryProvider.CONTENT_URI,
String.valueOf(id));
wordIntent.setData(data);
startActivity(wordIntent);
}
});
}
}
public class CustomComparator implements Comparator<WordDefinition> {
#Override
public int compare(WordDefinition p1, WordDefinition p2) {
return p1.word.compareTo(p2.word);
}
}
}
WorDefinition (Array List):
public class WordDefinition {
String word,definition;
public WordDefinition(String word,ArrayList<String> alldefinition) {
this.word=word;
StringBuilder stringBuilder=new StringBuilder();
for (String string : alldefinition) {
stringBuilder.append(string);
}
this.word=stringBuilder.toString();
}
public WordDefinition(String word,String alldefinition) {
this.word=word;
this.definition=alldefinition;
}
}
DictionaryDatabase (snippet)
public ArrayList<WordDefinition> getAllWords() {
ArrayList<WordDefinition> arrayList=new ArrayList<WordDefinition>();
SQLiteDatabase database=mDatabaseOpenHelper.getReadableDatabase();
String selectAllQueryString="SELECT * FROM "+FTS_VIRTUAL_TABLE;
Cursor cursor=database.rawQuery(selectAllQueryString, null);
if (cursor.moveToFirst()) {
do {
WordDefinition wordDefinition=new WordDefinition(cursor.getString(cursor.getColumnIndex(KEY_WORD)), cursor.getString(cursor.getColumnIndex(KEY_DEFINITION)));
arrayList.add(wordDefinition);
} while (cursor.moveToNext());
}
return arrayList;
}
Main XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/fundoeua"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
>
<LinearLayout
android:id="#+id/Line1"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/text"
android:textColor="#FFFFFF"
android:gravity="right"
android:textAlignment="gravity"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingRight="15dp"
android:textStyle="bold"
android:textSize="20sp"
android:text="#string/chamada"
android:background="#color/vermelho"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#ff0000"
android:dividerHeight="4px"
/>
</LinearLayout>
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/seletor2"
android:orientation="vertical" >
<TextView
android:id="#+id/listItemTextView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp"
android:textColor="#color/preto"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Sometimes height ListView calculate incorrect.
Android: wrap_content is not working with ListView
You can use one adapter and one ListView instead of Two ListViews. Use types for items in this adapter. In this way you can remove wrap_content and set match_parent for height attribute in ListView
I have the below code :
public class HomeFragment extends Fragment {
private List<RowItem> rowItems;
private static Integer[] images = { R.drawable.red, R.drawable.spidy,
R.drawable.prisoners, R.drawable.red, R.drawable.spidy };
public HomeFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container,
false);
ListView lv = (ListView) rootView.findViewById(R.id.myList);
rowItems = new ArrayList<RowItem>();
String[] titles = { "Movie1", "Movie2", "Movie3", "Movie4", "Movie5" };
String[] descriptions = { "First Movie", "Second movie", "Third Movie",
"Fourth Movie", "Fifth Movie" };
// Populate the List
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i], descriptions[i]);
rowItems.add(item);
}
// Set the adapter on the ListView
LazyAdapter adapter = new LazyAdapter(getActivity()
.getApplicationContext(), R.layout.list_row, rowItems);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(), "test", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(getActivity(), News.class);
getActivity().startActivity(myIntent);
// startActivity(in);
}
});
lv.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
return rootView;
}
}
I have written Toast ans startIntent on item click, but it is not working. Neither toast is display nor new activity is starting. I have also tried onItemSelection method but it is not working. How can i used this in this Fragment class?
list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#drawable/card_greenborder"
android:focusable="false"
android:focusableInTouchMode="false"
android:orientation="vertical"
android:padding="2dp" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:text="Dog Tag"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#040404"
android:textStyle="bold"
android:typeface="sans" />
<ImageView
android:id="#+id/list_image"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_margin="2dp"
android:layout_weight="0.04"
android:scaleType="fitXY"
android:src="#drawable/dhoom" />
<TextView
android:id="#+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:text="Create an NFC Pet Tag"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#android:color/secondary_text_dark"
android:textStyle="bold" />
<Button
android:id="#+id/btnregister"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Register" />
</LinearLayout>
First don't need to be implement OnItemSelectedListener for ListView. Just remove it.
Second make
android:focusable = "false"
android:focusableInTouchMode = "false"
for your UIs in custom inflated views in listview
xml for save database please help me to## i want add delete button in listview's each row when button is pressed delete that data from listview and database ##
here is first xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F3CAE5"
android:orientation="vertical"
android:padding="5dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/frst_txtV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First name"
android:textColor="#000" />
<EditText
android:id="#+id/frst_editTxt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/frst_txtV" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/lst_txtV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Last name"
android:textColor="#000" />
<EditText
android:id="#+id/last_editTxt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/lst_txtV" />
</LinearLayout>
<Button
android:id="#+id/save_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Save"
android:textColor="#000" />
</LinearLayout>
display_activty.xml list view xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#B58897"
android:gravity="center_horizontal" >
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:text="Add" />
<View
android:id="#+id/a"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/btnAdd"
android:background="#8DB3E1" />
<ListView
android:id="#+id/List"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/a"
android:divider="#8DB3E1"
android:dividerHeight="2dp" />
</RelativeLayout>
displayadapter.java here i add button if i press button than record is will delete from database as well from listview
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private SQLiteDatabase dataBase;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(final int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.btn = (Button) child.findViewById(R.id.Button1);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
mHolder.btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
}
});
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
Button btn;
//ImageView img;
}
}
listcell.xml this is to display custom listview xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F3CAE5"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="8dp" >
<TextView
android:id="#+id/txt_id"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#000" />
<TextView
android:id="#+id/txt_fName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<TextView
android:id="#+id/txt_lName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColor="#000" />
<Button android:text="Button"
android:id="#+id/Button1"
android:focusable="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
DisplayActivty.java here is listview adding class
public class DisplayActivity extends Activity {
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();
private ListView userList;
private AlertDialog.Builder build;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_activity);
userList = (ListView) findViewById(R.id.List);
mHelper = new DbHelper(this);
//add new record
findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
AddActivity.class);
i.putExtra("update", false);
startActivity(i);
}
});
//click to update data
userList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent i = new Intent(getApplicationContext(),
AddActivity.class);
i.putExtra("Fname", user_fName.get(arg2));
i.putExtra("Lname", user_lName.get(arg2));
i.putExtra("ID", userId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
}
#Override
protected void onResume() {
displayData();
super.onResume();
}
/**
* displays data from SQLite
*/
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM "
+ DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(DisplayActivity.this,userId, user_fName, user_lName);
userList.setAdapter(disadpt);
mCursor.close();
}
}
Addactivty.java add database class
public class AddActivity extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_first,edit_last;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String id,fname,lname;
private boolean isUpdate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_activity);
btn_save=(Button)findViewById(R.id.save_btn);
edit_first=(EditText)findViewById(R.id.frst_editTxt);
edit_last=(EditText)findViewById(R.id.last_editTxt);
isUpdate=getIntent().getExtras().getBoolean("update");
if(isUpdate)
{
id=getIntent().getExtras().getString("ID");
fname=getIntent().getExtras().getString("Fname");
lname=getIntent().getExtras().getString("Lname");
edit_first.setText(fname);
edit_last.setText(lname);
}
btn_save.setOnClickListener(this);
mHelper=new DbHelper(this);
}
// saveButton click event
public void onClick(View v) {
fname=edit_first.getText().toString().trim();
lname=edit_last.getText().toString().trim();
if(fname.length()>0 && lname.length()>0)
{
saveData();
}
else
{
AlertDialog.Builder alertBuilder=new AlertDialog.Builder(AddActivity.this);
alertBuilder.setTitle("Invalid Data");
alertBuilder.setMessage("Please, Enter valid data");
alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertBuilder.create().show();
}
}
/**
* save data into SQLite
*/
private void saveData(){
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_FNAME,fname);
values.put(DbHelper.KEY_LNAME,lname );
System.out.println("");
if(isUpdate)
{
//update database with new data
dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
}
else
{
//insert data into database
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
//close database
dataBase.close();
finish();
}
}
Create Custom Array Adapter like this
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.inflatelistview, null);
TextView text=(TextView)vi.findViewById(R.id.textView1);
ImageView image=(ImageView)vi.findViewById(R.id.imageView1);
Button btn=(Button)vi.findViewById(R.id.button1);
btn.setTag(position);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer index = (Integer) v.getTag();
//items.remove(index.intValue());
data.remove(position);
notifyDataSetChanged();
}
});
text.setText("item "+position);
imageLoader.DisplayImage(data.get(position), image);
return vi;
}
As you're inserting (Addactivty.java add database class) and fetching (DisplayActivty.java here is listview adding class) data from database similarly you can delete.
For example :
public static boolean Delete(Context context, int id) {
SQLiteDatabase db = new MyDataBase(context).getWritableDatabase();
int res = db.delete(CATEGORY, ID + " = " + id, null);
if (db.isOpen())
db.close();
return (res == 0 ? false : true);
}
You need to delete data from database and listView inside the click listener,like :
mHolder.btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
//1. get the clicked item's *ID*
// (as you did id.get(pos), in your adapter class).
//2. delete data from database using this *ID*.
// (see above function).
//3. remove position from your list.
// list.remove(position);
// (in your case you've multiple lists remove position from all)
//4. notifyDataSetChanged();
}
});
Helping link :
notifyDataSetChanged();
Your choices are:
Use the functions of the ArrayAdapter to modify the underlying List (add(), insert(), remove(), clear(), etc.)
Re-create the ArrayAdapter with the new List data. (Uses a lot of resources and garbage collection.)
Create your own class derived from BaseAdapter and ListAdapter that allows changing of the underlying List data structure.
Use the notifyDataSetChanged() every time the list is updated. To call it on the UI-Thread, use the runOnUiThread() of Activity. Then, notifyDataSetChanged() will work.
i tried to do a simple Toast into my onitemclickmethod but nothing it's happening and no error just nothing happen when i press an item of the list
My listfragment :
public class F1_fr extends ListFragment {
View rootview;
TextView textView1;
ArrayAdapter<String> aa;
ArrayList<String> arrayList = new ArrayList<String>();
SQLiteDatabase db;
ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootview=inflater.inflate(R.layout.f1_lay,container,false);
textView1=(TextView)rootview.findViewById(R.id.textView1);
db = getActivity().openOrCreateDatabase("testDB2", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS test2(mac VARCHAR,mdp VARCHAR,obj VARCHAR);");
aa = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, arrayList);
setListAdapter(aa);
((ListView) rootview.findViewById(android.R.id.list)).setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(),"lol",Toast.LENGTH_LONG).show();
}
});
Cursor cursor = db.rawQuery("SELECT * FROM test2", null);
// Toast.makeText(myContext, ""+cursor.getCount(), Toast.LENGTH_LONG).show();
if(cursor.moveToFirst())
{
do {
arrayList.add(cursor.getString(2));
} while (cursor.moveToNext());
}
rootview.findViewById(R.id.semi_transparent).
setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v){
Intent intent = new Intent(getActivity(), ajout.class);
startActivityForResult(intent, 2);
}
}
);
return rootview;
}
and my layout :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fab="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#id/android:list"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true" />
<TextView
android:id="#android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="30sp"
android:text="" />
<com.getbase.floatingactionbutton.AddFloatingActionButton
android:id="#+id/semi_transparent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fab:fab_plusIconColor="#color/primaryColorDark"
fab:fab_colorNormal="#color/primaryColor"
fab:fab_colorPressed="#color/AccentColor"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
So i'am just asking your help because i have absolutly no error nothing in the logcat just nothing is happening
You've implemented ListFragment so directly #Override onListItemClick(...)
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// do something
Toast.makeText(getActivity(), "Lol", Toast.LENGTH_SHORT).show();
}
Take a look at this
I am not sure but try to put below line in RelativeLayout.
android:descendantFocusability="blocksDescendants"
Hope it will work.!!!
you have to override onListItemClick() of listFragment you dont call listview.setOnItemClick();