Example code on how to open dialog box when click on the list AdapterView - Android

Today I want to show how to open list items in the dialog box.

For this tutorial, you need to have:-

  1. Dialog design view_item.xml
  2. MyDialogFragment.java class
  3. OnClick Event to call dialog.
  4. Announcement.java Class
  5. AnnouncementHelper Class
  6. OnCreateView Method

view_item.xml


  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5dip"
android:id="@+id/Announcement"
android:transitionGroup="false">
<ImageView android:id="@+id/icon" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:layout_alignParentBottom="true" android:layout_marginRight="4dip"
android:src="@drawable/icon" />
<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="vertical">
<TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1" android:gravity="center_vertical" android:textStyle="bold"
android:singleLine="false" android:ellipsize="end" />
<TextView android:id="@+id/datepublish" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_weight="1"
android:gravity="center_vertical" android:singleLine="false" android:ellipsize="end" />
<TextView android:id="@+id/summarycontent" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_weight="1"
android:gravity="center_vertical" android:singleLine="false" android:ellipsize="end" />
<Button android:layout_width="fill_parent" android:layout_height="wrap_content"
android:text="Close Announcement"
android:id="@+id/button"
android:layout_gravity="fill_horizontal"
/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>


MyDialogFragment.java


  public class MyDialogFragment extends DialogFragment {  
int mNum;
int AnnouncementKey;
/**
* Create a new instance of MyDialogFragment, providing "num"
* as an argument.
*/
static MyDialogFragment newInstance(int num,int mAnnouncementKey) {
MyDialogFragment f = new MyDialogFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
args.putInt("announceKey", mAnnouncementKey);
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments().getInt("num");
AnnouncementKey = getArguments().getInt("announceKey");
// Pick a style based on the num.
int style = DialogFragment.STYLE_NORMAL, theme = 0;
switch ((mNum-1)%6) {
case 1: style = DialogFragment.STYLE_NO_TITLE; break;
case 2: style = DialogFragment.STYLE_NO_FRAME; break;
case 3: style = DialogFragment.STYLE_NO_INPUT; break;
case 4: style = DialogFragment.STYLE_NORMAL; break;
case 5: style = DialogFragment.STYLE_NORMAL; break;
case 6: style = DialogFragment.STYLE_NO_TITLE; break;
case 7: style = DialogFragment.STYLE_NO_FRAME; break;
case 8: style = DialogFragment.STYLE_NORMAL; break;
}
switch ((mNum-1)%6) {
case 4: theme = android.R.style.Theme_Holo; break;
case 5: theme = android.R.style.Theme_Holo_Light_Dialog; break;
case 6: theme = android.R.style.Theme_Holo_Light; break;
case 7: theme = android.R.style.Theme_Holo_Light_Panel; break;
case 8: theme = android.R.style.Theme_Holo_Light; break;
}
setStyle(style, theme);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_view_announcemnet, container, false);
//View tv = v.findViewById(R.id.text);
if(AnnouncementKey != 0) {
AnnounceHelper AnnHelper = new AnnounceHelper(v.getContext());
Announcements ann = AnnHelper.GetAnnouncement(AnnouncementKey);
if (!ann.getAnnouncementTitle().equals("")) {
TextView title = (TextView)v.findViewById(R.id.title);
TextView datepublish = (TextView)v.findViewById(R.id.datepublish);
TextView summary = (TextView) v.findViewById(R.id.summarycontent);
ImageView icon = (ImageView)v.findViewById(R.id.icon);
title.setText(ann.getAnnouncementTitle());
datepublish.setText(getDateTime(ann.getAnnouncementPublishDateTime()));
summary.setText(ann.getAnnouncementContent());
Button button = (Button)v.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dismiss();
}
});
}
}
return v;
}
private String getDateTime(Date passedDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:ss", Locale.getDefault());
return dateFormat.format(passedDate);
}
}

OnClick Event to call dialog.


 private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener() {  
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Announcements r = model.get(position);
//Intent inent = new Intent(getActivity(), ViewAnnouncemnet.class);
//inent.putExtra("AnnouncementKey",r.getAnnouncementKey());
//startActivity(inent);
showDialog(r);
}
};
void showDialog(Announcements passedParameter) {
// DialogFragment.show() will take care of adding the fragment
// in a transaction. We also want to remove any currently showing
// dialog, so make our own transaction and take care of that here.
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
DialogFragment newFragment = MyDialogFragment.newInstance(7,passedParameter.getAnnouncementKey());
newFragment.show(ft, "dialog");
}


Announcement.java Class


  public class Announcements {  
private Integer AnnouncementKey;
private String AnnouncementTitle;
private String AnnouncementContent;
private Date AnnouncementPublishDateTime;
private String AnnounceError;
public Announcements() {
AnnounceError = "";
AnnouncementKey = 0;
AnnouncementTitle = "";
AnnouncementContent = "";
setAnnouncementPublishDateTime(new Date());
}
public String getContentSummary(){
if(getAnnouncementContent().length() > 50) {
return getAnnouncementContent().substring(0, 50);
}else{
return getAnnouncementContent();
}
}
public String toString(){
return "Title : " + getAnnouncementTitle() + ", Content : " + getAnnouncementContent() + ", Publish DateTime : " +
getAnnouncementPublishDateTime().toString();
}
public String getAnnouncementTitle() {
return AnnouncementTitle;
}
public void setAnnouncementTitle(String announcementTitle) {
AnnouncementTitle = announcementTitle;
}
public String getAnnouncementContent() {
return AnnouncementContent;
}
public void setAnnouncementContent(String announcementContent) {
AnnouncementContent = announcementContent;
}
public Date getAnnouncementPublishDateTime() {
return AnnouncementPublishDateTime;
}
public void setAnnouncementPublishDateTime(Date announcementPublishDateTime) {
AnnouncementPublishDateTime = announcementPublishDateTime;
}
public String getAnnounceError() {
return AnnounceError;
}
public void setAnnounceError(String announceError) {
AnnounceError = announceError;
}
public Integer getAnnouncementKey() {
return AnnouncementKey;
}
public void setAnnouncementKey(Integer announcementKey) {
AnnouncementKey = announcementKey;
}
}


AnnouncementHelper.java class


 public class AnnounceHelper extends SQLiteOpenHelper {  
// UserDetails table name
private static final String TABLE_ANNOUNCEMENT = "Announcement";
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "ApplyLeave";
private static final String[] COLUMNS = {"AnnouncementKey","AnnouncementTitle","AnnouncementContent","AnnouncementPublishDateTime"};
public AnnounceHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
createTable();
}
private void createTable(){
SQLiteDatabase db = this.getWritableDatabase();
onCreate(db);
}
@Override
public void onCreate(SQLiteDatabase db) {
// SQL statement to create book table
String CREATE_ANNOUNCEMENT_TABLE = " CREATE TABLE IF NOT EXISTS " + TABLE_ANNOUNCEMENT + " ( " +
"AnnouncementKey INTEGER PRIMARY KEY AUTOINCREMENT, " +
"AnnouncementTitle TEXT, " +
"AnnouncementContent TEXT," +
"AnnouncementPublishDateTime DATETIME DEFAULT CURRENT_TIMESTAMP )";
// create books table
db.execSQL(CREATE_ANNOUNCEMENT_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older UsersDetails table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ANNOUNCEMENT);
// create fresh UsersDetails table
this.onCreate(db);
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion){
// Drop older UsersDetails table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ANNOUNCEMENT);
// create fresh UsersDetails table
this.onCreate(db);
}
public Announcements SetDummyAnnouncement(){
Announcements DummyAnnouncement = new Announcements();
DummyAnnouncement.setAnnouncementTitle("Welcome To Announcement");
DummyAnnouncement.setAnnouncementContent("This is Announcement v1.0 application.\n\nDeveloper Name : \nSw Engineering Code Developer");
DummyAnnouncement.setAnnouncementPublishDateTime(new Date());
CreateAnnouncement(DummyAnnouncement);
Announcements testAnno = new Announcements();
testAnno.setAnnouncementTitle("This is second announcement");
testAnno.setAnnouncementContent("This is the second Content summary");
testAnno.setAnnouncementPublishDateTime(new Date());
CreateAnnouncement(testAnno);
return DummyAnnouncement;
}
public List<Announcements> GetAllAnnouncement() throws SQLiteException{
List<Announcements> AllAnnouncement = new LinkedList<>();
try {
String query = "SELECT * FROM " + TABLE_ANNOUNCEMENT;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
Announcements detail = null;
if (cursor.moveToFirst()) {
do {
detail = new Announcements();
detail.setAnnouncementKey(Integer.parseInt(cursor.getString(0)));
detail.setAnnouncementTitle(cursor.getString(1));
detail.setAnnouncementContent(cursor.getString(2));
detail.setAnnouncementPublishDateTime(getDateTime(cursor.getString(3)));
AllAnnouncement.add(detail);
} while (cursor.moveToNext());
}
} catch (Exception ex){
Announcements detail = new Announcements();
detail.setAnnounceError(ex.getMessage());
AllAnnouncement.add(detail);
}
return AllAnnouncement;
}
public Boolean DeleteAllAnnouncement(){
Boolean isSuccessful = false;
Announcements ann = new Announcements();
try {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ANNOUNCEMENT,"",null);
db.close();
isSuccessful = true;
} catch (Exception ex){
ann.setAnnounceError(ex.getMessage());
}
return isSuccessful;
}
public Announcements GetAnnouncement(int key){
Announcements NewAnnouncement = new Announcements();
SQLiteDatabase db = this.getReadableDatabase();
// 2. build query
Cursor cursor =
db.query(TABLE_ANNOUNCEMENT,COLUMNS," AnnouncementKey = ?", new String[] { String.valueOf(key) },
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
if (cursor != null && cursor.getCount() > 0){
cursor.moveToFirst();
NewAnnouncement.setAnnouncementKey(Integer.parseInt(cursor.getString(0)));
NewAnnouncement.setAnnouncementTitle(cursor.getString(1));
NewAnnouncement.setAnnouncementContent(cursor.getString(2));
NewAnnouncement.setAnnouncementPublishDateTime(getDateTime(cursor.getString(3)));
}
return NewAnnouncement;
}
public Boolean CreateAnnouncement(Announcements Announcement) throws SQLiteException {
Boolean successful = false;
try {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("AnnouncementTitle", Announcement.getAnnouncementTitle());
values.put("AnnouncementContent", Announcement.getAnnouncementContent());
values.put("AnnouncementPublishDateTime",getDateTime(Announcement.getAnnouncementPublishDateTime()));
long rowEfected = db.insert(TABLE_ANNOUNCEMENT, null,values);
db.close();
if(rowEfected > 0){
successful = true;
}else{
successful = false;
}
}
catch(Exception ex){
Announcement.setAnnounceError(ex.getMessage());
return false;
}
return successful;
}
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:ss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
private String getDateTime(Date passedDate) {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:ss", Locale.getDefault());
return dateFormat.format(passedDate);
}
private Date getDateTime(String passedDateString) {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:ss", Locale.getDefault());
Date date = new Date();
try {
date = dateFormat.parse(passedDateString);
}catch (Exception ex){
//do nothing
}
return date;
}
}

OnCreateView Method


 @Override  
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Boolean setDummy = false;
AnnounceHelper AnnSQLHelper = new AnnounceHelper(getActivity());
model.clear();
List<Announcements> AllAnnouncement = AnnSQLHelper.GetAllAnnouncement();
if(AllAnnouncement.size() > 0){
//check if first announcement get error
Announcements firstElement = AllAnnouncement.get(0);
if(CheckError(firstElement,true)) {
firstElement = AnnSQLHelper.SetDummyAnnouncement();
setDummy = true;
}else{
try {
ListView list = (ListView)getView().findViewById(R.id.listView);
if(list != null) {
list.setAdapter(null);
adapter = null;
adapter = new AnnouncementAdapter();
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
list.setOnItemClickListener(onListClick);
for (int i = 0; i < AllAnnouncement.size(); i++) {
Announcements ann = AllAnnouncement.get(i);
adapter.add(ann);
}
}else{
ShowMessage("List is null","Info");
}
}catch (Exception ex){
ShowMessage(ex.getMessage(),"Error");
}
}
}else {
Announcements firstElement = AnnSQLHelper.SetDummyAnnouncement();
CheckError(firstElement,true);
setDummy = true;
}
if(setDummy){
AllAnnouncement = AnnSQLHelper.GetAllAnnouncement();
if(AllAnnouncement.size() > 0){
try {
ListView list = (ListView)getView().findViewById(R.id.listView);
if(list != null) {
list.setAdapter(null);
adapter = null;
adapter = new AnnouncementAdapter();
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
list.setOnItemClickListener(onListClick);
for (int i = 0; i < AllAnnouncement.size(); i++) {
Announcements ann = AllAnnouncement.get(i);
adapter.add(ann);
}
}else{
ShowMessage("List is null","Info");
}
}catch (Exception ex){
ShowMessage(ex.getMessage(),"Error");
}
}
}
}





Note: To understand this example, you need to have basic Java knowledge. 


Popular posts from this blog

Example to disable save as certain file type in SSRS Report Viewer

Phone book application example - Java

Modal Popup Message Box ASP.NEt C# Example