I am using ListView that get data from Database.
when i call update and delete i refresh the activity by call Intent.
it shows updated list but when i click on it it not shows changes in text view on which i am showing list details.
i am using Custom Adapter.Below is my code,
public class Mainmenu extends Activity{
ListView list;
DBHandler db= new DBHandler(this);
int ID;
String strname,strlastname,strdob,strcell,strcnic,straddress;
String pppath,cfpath,cbpath,fppath;
TextView tvname,tvlastname,tvdob,tvcnic,tvcell,tvaddress;
ImageView pp,cf,cb;
public static ArrayList<String> customers = new ArrayList<String>();
SearchResults sr1;
ArrayList<SearchResults> searchResults= new ArrayList<SearchResults>();
MyCustomBaseAdapter adaptor;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenulist);
list= (ListView) findViewById(R.id.listMM);
tvname=(TextView)findViewById(R.id.textView3);
tvlastname=(TextView)findViewById(R.id.textView4);
tvdob=(TextView)findViewById(R.id.textView5);
tvcnic=(TextView)findViewById(R.id.textView10);
tvcell=(TextView)findViewById(R.id.textView7);
tvaddress=(TextView)findViewById(R.id.textView8);
pp=(ImageView)findViewById(R.id.ImageView02);
cf=(ImageView)findViewById(R.id.imageView2);
cb=(ImageView)findViewById(R.id.ImageView03);
Context c =getApplicationContext();
if(db.getAllcustomers2().toString()==null){
db.getWritableDatabase();
db.init();
}else{
List<Customers_GS> gtEdu = db.getAllcustomers2();
customers.clear();
for (Customers_GS ed : gtEdu) {
sr1 = new SearchResults();
ID=ed.getCID();
sr1.setId(ID);
customers.add(ed.getCustomer_Name());
strname=ed.getCustomer_Name().toString();
sr1.setName(strname);
customers.add(ed.getCustomer_DOB());
strdob=ed.getCustomer_DOB().toString();
sr1.setDOB(strdob);
customers.add(ed.getCustomer_CNIC());
strcnic=ed.getCustomer_CNIC().toString();
sr1.setCNIC(strcnic);
customers.add(ed.getCustomer_Cell());
strcell=ed.getCustomer_Cell().toString();
sr1.setPhone(strcell);
customers.add(straddress);
straddress=ed.getCustomer_Address().toString();
sr1.setAddress(straddress);
customers.add(ed.getCustomer_PP());
pppath=ed.getCustomer_PP().toString();
customers.add(ed.getCustomer_CNICf());
cfpath=ed.getCustomer_CNICf().toString();
customers.add(ed.getCustomer_CNICb());
cbpath=ed.getCustomer_CNICb().toString();
customers.add(ed.getCustomer_Thumb());
sr1.setImageNumber(1);
searchResults.add(sr1);
}
}
adaptor= new MyCustomBaseAdapter(c, searchResults);
list.setAdapter(adaptor);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
int height= 146;
int width=146;
//parent.getItemAtPosition(position);
//
Log.d("PP", ""+pppath);
Log.d("cP", ""+cbpath);
Log.d("fP", ""+cfpath);
// Bitmap ppbitmap = BitmapFactory.decodeFile(pppath );
// Bitmap cbbitmap = BitmapFactory.decodeFile(cbpath );
// Bitmap cfbitmap = BitmapFactory.decodeFile(cfpath );
// ppbitmap=Bitmap.createScaledBitmap(ppbitmap, width,height, true);
// cbbitmap=Bitmap.createScaledBitmap(cbbitmap, width,height, true);
// cfbitmap=Bitmap.createScaledBitmap(cfbitmap, width,height, true);
//
// pp.setImageBitmap(ppbitmap);
// cb.setImageBitmap(cbbitmap);
// cf.setImageBitmap(cfbitmap);
String[] result =strname.split(" ");
strname= result[0];
strlastname=result[1];
tvname.setText(strname);
tvlastname.setText(strlastname);
tvcell.setText(strcell);
tvaddress.setText(straddress);
tvcnic.setText(strcnic);
tvdob.setText(strdob);
adaptor.notifyDataSetChanged();
}
});
list.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
// // TODO Auto-generated method stub
//
//
db.getWritableDatabase();
// db.delete(ID);
// db.update(17);
// // TODO Auto-generated method stub
//
// Intent gonext= new Intent("com.example.ibex.MAINMENU");
// startActivity(gonext);
//
AlertDialog.Builder builder = new AlertDialog.Builder(Mainmenu.this);
builder.setMessage("Chose any one!");
builder.setCancelable(false);
builder.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
db.update(ID);
Intent reload = new Intent(getApplicationContext(), Mainmenu.class);
startActivity(reload);
}
});
builder.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
db.delete(ID);
Intent reload = new Intent(getApplicationContext(), Mainmenu.class);
startActivity(reload);
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
});
}
////### ## ##### ### ### ### ### #### ### ### ### ### ### ## ////
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.optionmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.Addmenu){
Intent openstngs=new Intent("com.example.ibex.REGISTRATION");
startActivity(openstngs);
}else if(item.getItemId()==R.id.Edithmenu){
Bundle contan= new Bundle();
contan.putInt("key", ID );
Intent web =new Intent(Mainmenu.this, Edit.class);
web.putExtras(contan);
startActivity(web);
}else if(item.getItemId()==R.id.Dltmenu){
db.delete(ID);
Intent reload = new Intent(getApplicationContext(), Mainmenu.class);
startActivity(reload);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(Mainmenu.this);
builder.setMessage("Are u sure to want to Logout ?");
builder.setCancelable(false);
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent reload = new Intent(getApplicationContext(), Login.class);
startActivity(reload);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
return super.onOptionsItemSelected(item);
};
}
I'm not clear about your question since you haven't provided the code of your adapter. I think You haven't called notifyDataSetChanged() method on your Adapter instance to get your changes reflected on ListView.
Related
Like the title says. I have coded onClickListener to my AlertDialog but i don't know how to put there onLongClickListener.
This is my code:
private void addRecipeMethod() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");
adapter = new ArrayAdapter<>(getBaseContext(), android.R.layout.simple_list_item_1, getArrayList("ListOfRecipes"));
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
List<String> list = new ArrayList<>(getArrayList("ListOfRecipes"));
getArrayListRecipes(list.get(which));
List<String> listMain = new ArrayList<>(getArrayList("ListMain"));
listMain.addAll(getArrayListRecipes(list.get(which)));
saveList(listMain, "ListMain");
adapter = new ArrayAdapter<>(getBaseContext(), android.R.layout.simple_list_item_1, getArrayList("ListMain"));
listView.setAdapter(adapter);
//Toast.makeText(getApplicationContext(), "you have clicked " + list.get(which) , Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
PS. void addRecipeMethod is called when Menu Item is clicked
Create AlertDialog with custom layout like this
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// ...Irrelevant code for customizing the buttons and title
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);
dialogBuilder.setView(dialogView);
Button button = (Button)dialogBuilder.findViewById(R.id.btnName);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Commond here......
}
});
button.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return false;
}
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
Add Button in alert_label_editor xml and add setOnLongClickListener for that Button
Button button = (Button)dialogBuilder.findViewById(R.id.btnName);
button.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return false;
}
});
I have this error:
The specified child already has a parent. You must call removeView()
on the child's parent first.
When I clicked buildNot.setPosiviteButton.
Help me please, thanks guys!
This is my Java source code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnDersEkle = (Button) findViewById(R.id.btnDersEkle);
list = (ListView) findViewById(R.id.listView1);
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1);
etDers = new EditText(MainActivity.this);
etNot = new EditText(MainActivity.this);
//Dialog
AlertDialog.Builder build = new AlertDialog.Builder(MainActivity.this);
build.setTitle("Ders Ekle");
build.setView(etDers);
//Dialog Not
final AlertDialog.Builder buildNot = new AlertDialog.Builder(MainActivity.this);
buildNot.setTitle("Not Ekle");
buildNot.setView(etNot);
build.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
adapter.add(etDers.getText().toString());
dialog.cancel();
}
});
final AlertDialog alertDers = build.create();
buildNot.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
adapter = (ArrayAdapter ) list.getAdapter();
String item = (String) list.getSelectedItem();
int position = list.getSelectedItemPosition();
item += "YourText";
adapter.insert(item, position);
dialog.cancel();
}
});
final AlertDialog alertNot = buildNot.create();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
alertNot.show();
}
});
list.setAdapter(adapter);
btnDersEkle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
alertDers.show();
}
});
}
That is because nothing is selected.
list.getSelectedItemPosition() will always return -1.
"Click" and "select" are separate things. "Select" in a ListView is done via the pointing device (D-pad, trackball, arrow keys, etc.).
list.getSelectedItemPosition() will always return -1 if you are not using D-pad, trackball or arrow keys.
You should store the position in onItemClick(AdapterView<?> parent, View view, int position, long id) as a class member and access it in buildNot.setPositiveButton onClick.
Coding below, where mPosition is a class member of your class.
buildNot.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
adapter = (ArrayAdapter ) list.getAdapter();
String item = (String) adapter.getItem(mPosition);
item += "YourText";
adapter.insert(item, mPosition);
dialog.cancel();
}
});
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
mPosition = position;
alertNot.show();
}
});
Try change your code like below, maybe help
public class MainActivity extends ListActivity {
int posmy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainlistnew);
Button btnDersEkle = (Button) findViewById(R.id.btnDersEkle);
final ListView list = getListView();
final ArrayAdapter adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1);
final EditText etDers = new EditText(MainActivity.this);
final EditText etNot = new EditText(MainActivity.this);
//Dialog
AlertDialog.Builder build = new AlertDialog.Builder(MainActivity.this);
build.setTitle("Ders Ekle");
build.setView(etDers);
//Dialog Not
final AlertDialog.Builder buildNot = new AlertDialog.Builder(MainActivity.this);
buildNot.setTitle("Not Ekle");
buildNot.setView(etNot);
build.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
adapter.add(etDers.getText().toString());
dialog.cancel();
}
});
final AlertDialog alertDers = build.create();
buildNot.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//adapter = (ArrayAdapter ) list.getAdapter();
//String item = (String) list.getSelectedItem();
//int position = list.getSelectedItemPosition();
int position=posmy;
String item = "YourText" + etNot.getText().toString();
adapter.insert(item, position);
dialog.cancel();
}
});
final AlertDialog alertNot = buildNot.create();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
posmy=position;
alertNot.show();
}
});
list.setAdapter(adapter);
btnDersEkle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
alertDers.show();
}
});
}
}
I have list which need to refresh and I use PullToRefresh. I used to work with Activiti, but now I need to rewrite everything in the fragment. When I used the Activiti everything worked fine, but now I have found a mistake when I copied everything I used the same methods and logic, but an error has occurred nullpointerexception. This is my code of Fragment:
private PullToRefreshListView mPullRefreshListView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_vk, container, false);
Map<String, String> networkDetails = getConnectionDetails();
if (networkDetails.isEmpty()) {
Toast.makeText(getActivity().getApplicationContext(),
"Нет интернет подключения!", Toast.LENGTH_LONG).show();
}
getActivity().getActionBar().setDisplayShowTitleEnabled(false);
/** Create an array adapter to populate dropdownlist */
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getActivity().getBaseContext(),
android.R.layout.simple_spinner_dropdown_item, actions);
/** Enabling dropdown list navigation for the action bar */
getActivity().getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
/** Defining Navigation listener */
ActionBar.OnNavigationListener navigationListener = new OnNavigationListener() {
#Override
public boolean onNavigationItemSelected(int itemPosition,
long itemId) {
switch (itemPosition) {
case 1:
Intent intent1 = new Intent(getActivity().getApplicationContext(),
KfuNews.class);
getActivity().finish();
startActivity(intent1);
break;
}
return false;
}
};
/**
* Setting dropdown items and item navigation listener for the actionbar
*/
getActivity().getActionBar().setListNavigationCallbacks(adapter, navigationListener);
boolean firstrun = getActivity().getSharedPreferences("PREFERENCE", getActivity().MODE_PRIVATE)
.getBoolean("firstrun", true);
// Set a listener to be invoked when the list should be refreshed.
mPullRefreshListView
.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(
PullToRefreshBase<ListView> refreshView) {
String label = DateUtils.formatDateTime(
getActivity().getApplicationContext(),
System.currentTimeMillis(),
DateUtils.FORMAT_SHOW_TIME
| DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_ABBREV_ALL);
// Update the LastUpdatedLabel
refreshView.getLoadingLayoutProxy()
.setLastUpdatedLabel(label);
// Do work to refresh the list here.
new GetDataTask().execute();
}
});
// Add an end-of-list listener
mPullRefreshListView
.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
#Override
public void onLastItemVisible() {
Toast.makeText(getActivity().getApplicationContext(), "End of List!",
Toast.LENGTH_SHORT).show();
}
});
sp11 = getActivity().getSharedPreferences("VK", 0);
editor1 = sp11.edit();
account.restore(getActivity());
if ((firstrun) || (account.access_token == null)) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Авторизация")
.setMessage(
"для просмотра новостей необходимо авторизоваться.")
.setCancelable(false)
.setPositiveButton("Авторизоваться",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
editor1.putInt("isVk", 1).commit();
editor1.apply();
startLoginActivity();
}
})
.setNegativeButton("Отмена",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
editor1.putInt("isVk", 0).commit();
editor1.apply();
Intent intent = new Intent(
getActivity().getApplicationContext(),
KfuNews.class);
getActivity().finish();
startActivity(intent);
}
});
AlertDialog alert = builder.create();
alert.show();
// Save the state
getActivity().getSharedPreferences("PREFERENCE", getActivity().MODE_PRIVATE).edit()
.putBoolean("firstrun", false).commit();
}
if (account.access_token != null) {
api = new Api(account.access_token, Constants.API_ID);
}
Log.d("isChange", isChangedStat + "");
getWall();
return view;
}
And I have problem at this line:
mPullRefreshListView
.setOnRefreshListener(new OnRefreshListener<ListView>() {
There I have nullpointerexception, and I do not have much time to solve the problem, please help with.
You are not initializing your mPullRefreshListView variable thus the nullpointerexception. Based on your code you are missing this line:
mPullRefreshListView = (PullToRefreshListView) view .findViewById(R.id.mPullRefreshListView);
initiate the listview in fragment and add listener to refreshlayout to this listview.
So I have a dialog box, where EditText is enabled, and when someone keys in something, and clicks on the add button, their text gets added into the database. Here are my "mainactivity" which is named IndivItem.java, codes.
public class IndivItem extends Activity {
TextView name, price;
Button descB, revB;
ImageView converse;
ImageButton fav, buy, compare;
TableLayout table_layout;
ReviewController revcon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_indiv_item);
revcon = new ReviewController(this);
price = (TextView) findViewById(R.id.picPrice1);
name = (TextView) findViewById(R.id.text1);
descB = (Button) findViewById(R.id.desc);
revB = (Button) findViewById(R.id.review);
converse = (ImageView) findViewById(R.id.shoee1);
fav = (ImageButton) findViewById(R.id.fv1);
buy = (ImageButton) findViewById(R.id.co1);
compare = (ImageButton) findViewById(R.id.cp1);
table_layout = (TableLayout) findViewById(R.id.tableLayout1);
BuildTable();
revB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
// TODO Auto-generated method stub
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
IndivItem.this);
// Setting Dialog Title
alertDialog.setTitle("Review");
// Setting Dialog Message
alertDialog.setMessage("Add a Review");
final EditText input = new EditText(IndivItem.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alertDialog
.setView(input)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
})
.setCancelable(false)
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
new MyAsync().execute();
// toast saying review added
Toast.makeText(getApplicationContext(),
"Review Added!",
Toast.LENGTH_SHORT).show();
Intent home = new Intent(
getApplicationContext(),
IndivItem.class);
startActivity(home);
}
// close dialog
});
// show alert
alertDialog.show();
}
});
fav.setOnHoverListener(new OnHoverListener() {
#Override
public boolean onHover(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
Toast.makeText(IndivItem.this, "Add to Favorites",
Toast.LENGTH_SHORT).show();
return false;
}
});
compare.setOnHoverListener(new OnHoverListener() {
#Override
public boolean onHover(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
Toast.makeText(IndivItem.this, "Add to Compare List",
Toast.LENGTH_SHORT).show();
return false;
}
});
}
private void BuildTable() {
// TODO Auto-generated method stub
revcon.open();
Cursor c = revcon.readEntry();
int rows = c.getCount();
int cols = c.getColumnCount();
c.moveToFirst();
// outer for loop
for (int i = 0; i < rows; i++) {
TableRow row = new TableRow(IndivItem.this);
row.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
// inner for loop
for (int j = 0; j < cols; j++) {
TextView tv = new TextView(IndivItem.this);
tv.setGravity(Gravity.CENTER);
tv.setTextSize(18);
tv.setPadding(0, 5, 0, 5);
tv.setText(c.getString(j));
row.addView(tv);
}
c.moveToNext();
table_layout.addView(row);
}
revcon.close();
}
private class MyAsync extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
String review = input.getText().toString();
return null;
revcon.open();
revcon.createEntry(review);
// BuildTable();
return null;
}}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
}
And what happens is this line : String review = input.getText().toString();,
Gives me an error, that says error cannot resolved. I have no clue how to link the codes ): or what I'm doing wrong, please enlighten me,thanks!
I want to show a alert dialog box to the user when the back button is pressed..For example :Are you sure want to exit ?.I am not having a problem in creating a alert dialog box..I am having a problem in where to call this dialog box method().
This is my HomeScreen.java
public class HomeScreen extends TabActivity {
ConferenceOpenHelper helper_ob;
Cursor cursorHome;
ProfileEditScreen profileEditScreen;
ConferenceAdapter adapter;
EcMeeting meeting;
final Context context = this;
public static int HOMETEMP = 1;// Constant for Deleting the last created id
// in edit profile screen (Cancel)
public static String HOME = "home";// constant for updating status column
public static String CUSTOM_DIALER = "custom";
public static String TEMPLATE = "template";// constant for updating status // column
public static TabHost tabHost;
public static final int QUICK_START = 1;// Constant for menu options
public static final int TEMPLATE_SCREEN = 2;// Constant for menu options
public static final int USER_GUIDE = 3;// Constant for menu options
public static final int QUICK_CALL = 4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab);
Resources ressources = getResources();
tabHost = getTabHost();
// Android tab
Intent photo = new Intent().setClass(this,EcMeeting.class);
TabSpec tabSpecphoto = tabHost
.newTabSpec("Calendar")
.setIndicator("Calendar", ressources.getDrawable(R.drawable.calendartab))
.setContent(photo);
// Apple tab
Intent intentApple = new Intent().setClass(this,CallListScreen.class);
TabSpec tabSpecApple = tabHost
.newTabSpec("Calls")
.setIndicator("Calls", ressources.getDrawable(R.drawable.ic_action_device_access_call))
.setContent(intentApple);
// Windows tab
Intent intentWindows = new Intent().setClass(this,UserSettingActivity.class);
TabSpec tabSpecWindows = tabHost
.newTabSpec("Settings")
.setIndicator("Settings", ressources.getDrawable(R.drawable.ic_action_setting))
.setContent(intentWindows);
// add all tabs
tabHost.addTab(tabSpecphoto);
tabHost.addTab(tabSpecApple);
tabHost.addTab(tabSpecWindows);
//set Windows tab as default (zero based)
/*tabHost.setCurrentTab(0);*/
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#d3d3d3"));
}
tabHost.getTabWidget().setCurrentTab(0);
/*tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#C35817"));*/
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, QUICK_START, 0, "Quick Start").setIcon(R.drawable.ic_menu_add_icon);
menu.add(0, USER_GUIDE, 0, "User Guide").setIcon(R.drawable.ic_menu_guide_icon);
return true;
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
HomeScreen.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case QUICK_START:
startActivity(new Intent(this, ConfDialerScreen.class));
break;
case USER_GUIDE:
startActivity(new Intent(this, UserGuideScreen.class));
break;
}
return true;
}
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#8A4117"));
}
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#C35817"));
}
}
This is the method() to create alert dialog
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
HomeScreen.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
Now ,I really did not know where to call this method.Could someone give any Idea?
when user press the back button I want to show the alert Dialog.
Try below code:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
dialogOnBackPress();
return true;
}
return super.onKeyDown(keyCode, event);
}
protected void dialogOnBackPress() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
HomeScreen.this.finish();
}
})
.setNegativeButton("No", null)
.show();
}
Use this:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Alert Message:");
builder.setMessage("Do you want to save this image to your file??");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
// do your stuff
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
return super.onKeyDown(keyCode, event);
}
you can this code modify acc. to req.
dialog.setOnKeyListener(new Dialog.OnKeyListener() {
#Override
public boolean onKey(DialogInterface arg0, int keyCode,
KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
dialog.dismiss();
}
return true;
}
});
do not call super.onBackPressed(); in onBackPressed
Else you can simply add onBackPressed() in activity_main.xml(tab.xml) as
android:onClick="onBackPressed"
mention it in your button properties