android OptionsMenu click times - android

Can I get OptionsMenu click times,
I want to get value to use in onReceive, like this
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
SubMenu fileMenu = menu.addSubMenu(0, 7, Menu.NONE, "歌曲");
fileMenu.add(0, 1, Menu.NONE, "A");
fileMenu.add(0, 2, Menu.NONE, "B");
fileMenu.add(0, 3, Menu.NONE, "C");
fileMenu.add(0, 4, Menu.NONE, "D");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
Toast.makeText(this, "A", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(this, "B", Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(this, "C", Toast.LENGTH_SHORT).show();
break;
case 4:
Toast.makeText(this, "D", Toast.LENGTH_SHORT).show();
break;
default:
return true;
}
return super.onOptionsItemSelected(item);
}
IntentFilter intent = new IntentFilter();
intent.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(searchDevices, intent);
private BroadcastReceiver searchDevices = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if(OptionsMenu click times == 2)
{
}
}
Because I just have the process only this part,
please help me understand how to solve provide advice thank

Bali gave a good solution for what you asked. But there is a much simpler way to get this done without using a receiver.
Make a new class that has a static container for your click number.
ie:
public class ParamValues{
private static int clickNums= 0;
/**
* #return the clickNumber
*/
public static int getClickNums() {
return clickNums;
}
/**
* Sets the clickNumber
*/
public static int setClickNum(int clickNum) {
clickNums = clickNum;
}
}
Then create an onClickHandler for your OptionsMenu, and inside the click handler add in somecode like.
int count = ParamValues.getClickNum();
count++;
ParamValues.setClickNum(count);
Now you could get this click count anywhere in your code. If you want to make sure it's synchronized you could just add a function to process what you want in the same onClick.
ie:
if(ParamValues.getClickNum() == 2)
{
// Do whatever
}
Then in you can reset the count value in here or wherever you would want to reset it by using the convenient setter in the ParamValues class.
Using the receiver you can't guarantee exactly when the code will execute.

From the detail you have given:
You could create a datamember in your Activity, which will store the number of times, the menukey was pressed, and increase it every time its pressed:
private int menuPressedCount = 0;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_MENU)
menuPressedCount++;
}
And you can pass this to your receiver, puting it in the Intent, which the receiver will get:
Intent intent = ...;
intent.putExtra("menu_pressed_count", menuPressedCount);
And in the onReceive():
int pressedCount = intent.getIntExtra("menu_pressed_count", 0);
Tell me if this isn't what you are looking for!

Related

Refreshing list on RecyclerView

I am fairly new in android programming.
I am having two cases where I am unable to get the list updated.
FIRST
Here is my Activity (QuestionList Activity).
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ques_list);
....
quesList=quesDB.getQues(); //getting arraylist from database
qAdapter = new QuesList_Adaptor(quesList, this, this);
rv_qlist.setAdapter(qAdapter);
qAdapter.notifyDataSetChanged();
}
On other activity, taking user input which updates the database (thus also updates quesList above).
public void save (View view)
{
String ques = et_ques.getText().toString();
String optionA = et_optA.getText().toString();
String optionB = et_optB.getText().toString();
String optionC = et_optC.getText().toString();
String optionD = et_optD.getText().toString();
String ans = et_ans.getText().toString();
QuesDB qd = new QuesDB(this);
boolean b = qd.addQues(ques, optionA, optionB, optionC, optionD, ans);
if (b)
{
Toast.makeText(this, "Question Saved", Toast.LENGTH_SHORT).show();
}
*//so... I have to notify adapter here right? than, what's the way here to reference adaptor and use notifyDataSetChanged*
finish();
SECOND CASE
Setting up Multi-delete on recyclerview. Data is getting deleted but trouble in refreshing the list.
Please take a look into the code, I mentioned there using comments.
On Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
..
StoreNotesDB sdb = new StoreNotesDB(this);
noteslist= sdb.getStoreNotes(); //storing from database to array
mAdapter = new AdaptorNotes(this,noteslist, this);
rv.setAdapter(mAdapter);
}
#Override
public void OnLongClick() {
fab.setVisibility(View.GONE);
inActionMode = true;
actionMode = this.startActionMode(new ContextualCallback());
mAdapter.notifyDataSetChanged();
}
#Override
public void OnClick(AdaptorNotes.MyViewHolder holder, int pos) {
if (holder.chk_notes.isChecked())
{
selected_list.add(noteslist.get(pos));
//counter = counter + 1;
}
else
{
selected_list.remove(noteslist.get(pos));
//counter = counter - 1;
}
}
class ContextualCallback implements ActionMode.Callback {
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
actionMode.getMenuInflater().inflate(R.menu.notescontextual_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
//Toast.makeText(MainActivity.this,"delete",Toast.LENGTH_SHORT).show();
if (selected_list.isEmpty()) {
Toast.makeText(NotesListViewActivity.this, "No item is selected", Toast.LENGTH_SHORT).show();
}
else{
//loop for deleting item from database of the selected list
for (MyStoreNotes myStoreNotes: selected_list)
{
String x = String.valueOf(myStoreNotes.getSl());
int y = storeNotesDB.deleteRow(x);
}
mAdapter.notifyDataSetChanged(); // it doesn't work
inActionMode = false;
selected_list.clear();
Toast.makeText(NotesListViewActivity.this, "Selected List Deleted", Toast.LENGTH_SHORT).show();
actionMode.finish();
}
}
return false;
}......
.....
I'm not sure if you're trying to refresh the data on each load of the activity, or if you are using a different method to refresh your data.
If you want to reload the data each time the recyclerview activity is shown, then you need to call...
quesList.clear();
after declaring the list, and before getting the data. That ensures that you are populating your recyclerview with the latest data from your database.
If this is not what you're asking, please explain what your app is currently doing vs what you want it to do.

Alert Dialog weird trouble on Contextual Action Mode

I have a very strange situation. I am using Contextual Action Mode for selecting multiple items of the ListView. The flow goes as follows:
User selects the list items using long press on them --> Uses the action item "Operations" to choose what he wants to do --> This action item creates a AlertDialog with 4 list items (call it dialog1) where the 3rd item calls another AlertDialog (call it dialog2) which includes an EditText for some data input and later calls a method to perform it.
Later the user hits Back button or Home button to exit the Action Mode.
The problem is that dialog2 shows up alternatively like first time user selects the list items, Chooses "Operations" action item and chooses the 3rd item which calls dialog2. Now dialog2 will appear as it is supposed to. Later the user hits the Back button to quit the Action Mode.
The SECOND TIME user performs the same steps dialog2 doesn't appear.
The logcat shows this error in both the cases:
09-04 10:53:12.096 6299-6299/com.project.pcmanager
W/InputEventReceiver: Attempted to finish an input event but the input
event receiver has already been disposed.
Some code:
public void sendAction(final Context context, final EventModel model, int position) {
JSONObject object = new JSONObject();
String[] operations = getResources().getStringArray(R.array.operations);
// null set before is modified here
model.setEventTitle(operations[position]);
final String ip = model.getEventIP();
switch (position) {
case 0:
try {
object.put("command", "power_off");
notifyUser();
LogUtils.addEntry(model.toString());
execCommand(ip,object);
} catch (JSONException e) {
e.printStackTrace();
}
break;
case 1:
try {
object.put("command", "reboot");
notifyUser();
LogUtils.addEntry(model.toString());
execCommand(ip,object);
} catch (JSONException e) {
e.printStackTrace();
}
break;
case 2:
//Show AlertDialog with EditText on it for command input
final EditText txtCommand = new EditText(context);
// Set some properties to EditText
txtCommand.setPadding(16, 16, 16, 16);
txtCommand.setMinHeight(150);
txtCommand.setHint("Ex: ping google.com");
txtCommand.setSingleLine();
new AlertDialog.Builder(context)
.setTitle("Run a task")
.setView(txtCommand)
.setCancelable(false)
.setPositiveButton("Run",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String command = txtCommand.getText().toString();
if (command.length() > 0) {
JSONObject object = new JSONObject();
try {
object.put("run", command);
object.put("ip", ip);
notifyUser();
LogUtils.addEntry(model.toString());
performRemoteExec(object);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, "Please provide a command first!", Toast.LENGTH_SHORT).show();
}
}
}).setNeutralButton("Cancel", null).show();
break;
case 3:
notifyUser();
LogUtils.addEntry(model.toString());
getScreenshot(ip);
break;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
listView.setAdapter(adapter);
listView.setEmptyView(emptyView);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
//Change the title bar with the items selected
mode.setTitle(listView.getCheckedItemCount() + " selected");
//select the clicked item
adapter.toggleSelection(position);
}
/**
* Called when action mode is first created.
* The menu supplied will be used to generate action buttons for the action mode.
* #param mode ActionMode being created
* #param menu Menu used to populate action buttons
* #return true if the action mode should be created,
* false if entering this mode should be aborted.
*/
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
onContextMode = true;
mode.getMenuInflater().inflate(R.menu.menu_client_select_main, menu);
return true;
}
/**
* Called to refresh an action mode's action menu whenever it is invalidated.
* #return true if the menu or action mode was updated, false otherwise.
*/
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
/**
* Called to report a user click on an action button.
* #return true if this callback handled the event,
* false if the standard MenuItem invocation should continue.
*/
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_operations) {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setItems(R.array.operations, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SparseBooleanArray selectedIds = adapter.getSelectedIds();
// traverse the array to find chosen clients
for (int i = 0; i < selectedIds.size(); i++) {
if (selectedIds.get(i)) {
ClientModel item = adapter.getItem(i);
String ip = item.getClientIP();
String os = item.getOSType();
// null will be treated soon
EventModel model = new EventModel(ip, null, os);
sendAction(builder.getContext(),model, which);
}
}
}
});
builder.show();
}
return true;
}
/**
* Called when an action mode is about to be exited and destroyed.
*/
#Override
public void onDestroyActionMode(ActionMode mode) {
onContextMode = false;
}
});
}
Ok so I figured the problem myself. It turns out the culprit was me using SparseBooleanArray to get selected clients and I was wrong.
In my code it was:
SparseBooleanArray selectedIds = adapter.getSelectedIds();
So, I removed this SparseBooleanArray with a new implementation technique. I used ArrayList<ClientMode> selectedItems to store all the selected models in my Adapter class.
Also, I created a simple method called clearSelections that calls selectedItems.clear() method in it. I call this method at on onDestroyActionMode as per my app requirement.
HOW I FOUND THIS?
I simply placed a bunch of System.out.println statements all around onCreate and sendAction to find out the culprit.

how can i refresh a listview after a new item is added to the list?

i know this question has been asked a couple of times before and i tried all of the suggestions there and i still cant refresh my list view after i add a new item to the list
can anyone please try to explain how can i do it?
thnaks
this is the code of the adding:
public class MainActivity extends ListActivity {
private DBHandler dataBase;
private ArrayList<Movies> list;
private ArrayAdapter<Movies> adapter;
private ListView lv;
private ImageButton addMovie;
private Intent intent;
final static int FLAG_FOR_ADDING=1;
final static int FLAG_FOR_EDITING=2;
final static int FLAG_FROM_MENU=3;
private int selected_movie;
private String the_movie;
private String movie_title;
private String movie_description;
private String movie_url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
dataBase = new DBHandler(MainActivity.this);
// by pressing this button the user will get instructions about how to use this application
Button start = (Button)findViewById(R.id.how_to_start);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(MainActivity.this, "Press the plus button for adding a movie or the menu button for the menu", Toast.LENGTH_LONG).show();
}
});
// by pressing this button, the menu of this application will open
ImageButton menu = (ImageButton)findViewById(R.id.menu_context);
menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openOptionsMenu();
}
});
addMovie = (ImageButton)findViewById(R.id.add_movie);
addMovie.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerForContextMenu(addMovie);
openContextMenu(addMovie);
}
});
// the array list is getting the movies from the database
list = dataBase.getAllMovies();
// here i am setting the adapter that will handle the list
adapter = new ArrayAdapter<Movies>(MainActivity.this, R.layout.row,list);
// i am getting a default xml
lv=getListView();
// i am connecting between the list and the adapter
lv.setAdapter(adapter);
// by short pressing an item on the list the user will move to the edit_a_movie page
// in order to edit the movie
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
intent = new Intent(MainActivity.this,Edit_A_Movie.class);
// i am sending the information of the item that been pressed to the edit_a_movie page
// the id, title,description and the url_photo
intent.putExtra("item_id", list.get(position).getId());
intent.putExtra("item_title", list.get(position).getTitle().toString());
intent.putExtra("item_description", list.get(position).getDescription().toString());
intent.putExtra("item_url", list.get(position).getPhoto_url().toString());
startActivityForResult(intent, FLAG_FOR_EDITING);
}
});
// a long press on a movie in the list will open a context menu for deleting or editing the item
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
// i am getting the information of the movie that was pressed
selected_movie = list.get(position).getId();
the_movie = String.valueOf(selected_movie);
movie_title = list.get(position).getTitle().toString();
movie_description = list.get(position).getDescription().toString();
movie_url = list.get(position).getPhoto_url().toString();
// i register to a context menu
registerForContextMenu(lv);
openContextMenu(lv);
return true;
}
});
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
// by pressing the exit option, the user will exit the application
case R.id.menu_exit:
finish();
android.os.Process.killProcess(android.os.Process.myPid());
super.onDestroy();
break;
// this option will delete all the movies from the list
case R.id.menu_delete:
dataBase.deleteAllMovies();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// if the user will press the menu button he will get the menu and if he will press
// the plus button he will get 2 options: 1. move to the edit a movie page
// 2. move to the search a movie from the Internet page
// if the user will press a long press on a movie he will get 2 options:
//1. update the movie
//2. delete the movie
if(v.getId() == R.id.menu_context){
getMenuInflater().inflate(R.menu.main, menu);
}
else if (v.getId() == R.id.add_movie){
getMenuInflater().inflate(R.menu.aad_menu, menu);
}
else {
getMenuInflater().inflate(R.menu.edit_or_delete, menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()){
// selecting this option will exit the application
case R.id.menu_exit:
finish();
android.os.Process.killProcess(android.os.Process.myPid());
super.onDestroy();
break;
// this option will delete all the movies from the list
case R.id.menu_delete:
dataBase.deleteAllMovies();
break;
// this option will move the user to the edit a movie page
case R.id.move_to_edit:
intent = new Intent(MainActivity.this,Edit_A_Movie.class);
startActivityForResult(intent, FLAG_FOR_ADDING);
break;
// this option will get the user move to the add a movie from the Internet page
case R.id.move_to_search:
break;
// if the user will press on a movie he will be able to update the movie or delete it
//this option will delete the movie
case R.id.delete_menu_movie:
dataBase.deleteMovie(the_movie);
break;
// this option will move the user to the edit_a_movie page
case R.id.edit_menu_movie:
intent = new Intent(MainActivity.this,Edit_A_Movie.class);
// i am sending the information of the pressed movie
intent.putExtra("item_id",selected_movie);
intent.putExtra("item_title", movie_title);
intent.putExtra("item_description", movie_description);
intent.putExtra("item_url", movie_url);
startActivityForResult(intent, FLAG_FROM_MENU);
break;
default:
break;
}
return super.onContextItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
// this is the info i am getting from the edit_a_movie page in order to put it in the database
// i am using it to add a new movie to the list
if(requestCode==FLAG_FOR_ADDING && resultCode==RESULT_OK){
// this is the info i received
String title_from_adding = data.getStringExtra("user_title");
String description_from_adding = data.getStringExtra("user_desciption");
String url_from_adding = data.getStringExtra("user_url");
// here i am putting the info in the database
dataBase.addMovie(title_from_adding, description_from_adding, url_from_adding);
// in case that the user pressed the cancel button he will get a massage
} else if
(requestCode==FLAG_FOR_ADDING && resultCode==RESULT_CANCELED){
Toast.makeText(MainActivity.this, "No movie has been added", Toast.LENGTH_LONG).show();
}
// i am using the info from the edit_a_movie page in order to update a movie
else if
(requestCode==FLAG_FOR_EDITING && resultCode==RESULT_OK ){
String position_from_editing = data.getStringExtra("position");
String title_from_editing = data.getStringExtra("user_title");
String description_from_editing = data.getStringExtra("user_desciption");
String url_from_editing = data.getStringExtra("user_url");
// the database is being updating
dataBase.updateMovie(position_from_editing, title_from_editing, description_from_editing, url_from_editing);
}
// this case is for editing the movie that was long pressed
else if
(requestCode==FLAG_FROM_MENU && resultCode==RESULT_OK){
// i am receiving the updated information from the edit_a_movie page
String position_from_menu = data.getStringExtra("position");
String title_from_menu = data.getStringExtra("user_title");
String description_from_menu = data.getStringExtra("user_desciption");
String url_from_menu = data.getStringExtra("user_url");
//the database is being updating with the new information
dataBase.updateMovie(position_from_menu, title_from_menu, description_from_menu, url_from_menu);
}
}
}
You should call notifyDataSetChanged on the adapter.
After dataBase.addMovie(..)
adapter.notifyDataSetChanged();

Combination of Service, ProgressBar, Gridview (and his notifydatasetchanged) an QuickAction-Implementation goes wrong

(Sorry for my mistakes in spelling)
I have a problem in the combination of some things:
I use a GridView to download show content from a database. onClick a file is downloaded which can be viewed later. Its about 20MB. This download is done by a service.
Every item in the gridView contains a progressbar in the layout. this progressbar is just shown if the item is donwloading in the background via the service.
The Service sends a broadcast about the download Progress, the Intent contains the ID of the item to find it in data of the Adapter for the gridview.
A BroadcastReceiver ist registered in my Activity to get the Progress Update (remember, simultaneous downloads are possible) which calls a function "setProgress" in the gridview-adapter
public void setProgress(long id, int progress)
{
for (int i = 0;i < list.size();i++)
{
if (list.get(i).getId() == id)
{
list.get(i).setProgress(progress);
notifyDataSetChanged();
}
}
}
To this point everything works fine.
Additionally im using QuickAction implementation from http:// www. londatiga.net/it/how-to-create-quickaction-dialog-in-android/ (Spaces because i cannot post more than two hyperlinks)
Now comes the problem:
Sometimes, i guess when notifydatasetchanged is called and the user taps on an item, the quickaction is shown on a wrong position.
To make this clearer here are two pictures:
The first one is what should happen (in this case a click on the first item of the gridview)
http://dl.dropbox.com/u/9031500/expected.png
The second picture shows what happens sometimes (only when some downloads are running, thats why i guess its because of the "notifydatasetchanged" and the rebuild of the views). This was also a click on the first item, unfortunately the quick-action is shown to the fourth item:
http://dl.dropbox.com/u/9031500/wrong.png
This is my implementation in my activity for the call of the quick-action:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
showQuickAction(view, position);
}
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
showQuickAction(view, position);
return true;
}
private void showQuickAction(View view, int position)
{
RelativeLayout facsimile = (RelativeLayout) view.findViewById(R.id.lib_item_image_layout);
Log.i(LOGTAG, "Position:"+position);
currentPaper = TZReader.paperDao.load(libraryAdapter.getItemId(position));
Log.i(LOGTAG,"Set CurrentPaper:"+currentPaper.getTitelWithDate());
ActionItem downloadItem = new ActionItem(ACTION_ITEM_DOWNLOAD, "Download", getResources().getDrawable(R.drawable.ic_action_download));
ActionItem readItem = new ActionItem(ACTION_ITEM_READ, "Lesen", getResources().getDrawable(R.drawable.ic_action_read));
ActionItem deleteItem = new ActionItem(ACTION_ITEM_DELETE, "Löschen", getResources().getDrawable(R.drawable.ic_action_delete));
ActionItem cancelItem = new ActionItem(ACTION_ITEM_CANCEL, "Abbrechen", getResources().getDrawable(R.drawable.ic_action_cancel));
QuickAction mQuickAction = new QuickAction(this, QuickAction.HORIZONTAL);
switch (currentPaper.getState())
{
case Paper.DOWNLOADED_READABLE:
mQuickAction.addActionItem(readItem);
mQuickAction.addActionItem(deleteItem);
break;
case Paper.DOWNLOADED_BUT_UPDATE:
mQuickAction.addActionItem(downloadItem);
mQuickAction.addActionItem(deleteItem);
break;
case Paper.IS_DOWNLOADING:
mQuickAction.addActionItem(cancelItem);
break;
case Paper.NOT_DOWNLOADED:
mQuickAction.addActionItem(downloadItem);
break;
}
//Set listener for action item clicked
mQuickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
#Override
public void onItemClick(QuickAction source, int pos, int actionId) {
//here we can filter which action item was clicked with pos or actionId parameter
switch(actionId)
{
case ACTION_ITEM_DOWNLOAD:
Intent downloadIntent = new Intent(getApplicationContext(), DownloadService.class);
downloadIntent.putExtra(DownloadService.PARAMETER_PAPER_DB_ID_LONG, currentPaper.getId());
startService(downloadIntent);
break;
case ACTION_ITEM_READ:
break;
case ACTION_ITEM_DELETE:
DeleteAlertDialogFragment newFragment = DeleteAlertDialogFragment.newInstance(currentPaper.getId());
newFragment.setStyle(SherlockDialogFragment.STYLE_NO_TITLE,0);
newFragment.show(getSupportFragmentManager(), "dialog");
break;
case ACTION_ITEM_CANCEL:
break;
}
}
});
mQuickAction.show(facsimile);
}
Maybe someone has any idea or hints for me how i can handle this problem!
Thanks a million in advance!
I found a solution for my problem.
The solution is that i implement my own ProgressBar, which contains now a BroadcastListerner and set the progress on each item. So i can change the value without need to call "notifydatasetchanged". perfect for my needs. Im still not sur if this is a good solution, but it works well.
Here is the code for the Progressbar:
public class ListeningProgressBar extends ProgressBar {
public ListeningProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
final IntentFilter intentDownloadProgressFilter = new IntentFilter(DownloadService.DOWNLOAD_PROGRESS_BROADCAST);
private long paperId = 0;
private boolean isReceiverRegistered = false;
#Override
protected void onAttachedToWindow() {
getContext().getApplicationContext().registerReceiver(downloadProgressBroadcastReceiver,intentDownloadProgressFilter);
isReceiverRegistered = true;
super.onAttachedToWindow();
}
#Override
protected void onDetachedFromWindow() {
if (isReceiverRegistered)
{
getContext().getApplicationContext().unregisterReceiver(downloadProgressBroadcastReceiver);
isReceiverRegistered = false;
}
super.onDetachedFromWindow();
}
private BroadcastReceiver downloadProgressBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
long id = intent.getLongExtra(DownloadService.PARAMETER_PAPER_DB_ID_LONG, -1);
int progressValue = intent.getIntExtra(DownloadService.PARAMETER_PAPER_PROGRESS_INT, 0);
if (paperId == id)
{
setProgress(progressValue);
}
}
};
public long getPaperId() {
return paperId;
}
public void setPaperId(long paperId) {
this.paperId = paperId;
}
}
I just use it as a normal custom view in my XML Layout.
In the Adapter i set the id of my content to give the receiver the data just to setprogress if its the right content.
At the end, my problem is solved, the progress is updated without the need to call notifydatasetchanged. Yeah!

Check RadioGroup checked or not and get value to static int

GOAL 1: When click the button, if there isn't any radiobutton checked, it will warning user by Toast; if a radiobutton checked, it will take user to new activity (or do smt up on you).
First
public class hanh1_2 extends Activity{
public static int ButID;
#Override
Second, set the button action:
final Button ok2 = (Button) findViewById(R.id.ok2);
ok2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Set int of ButID = checkedradiobuttonID
//If ButID = -1 --> there isn't bt checked
int ButID = tieng.getCheckedRadioButtonId();
if (ButID == -1){
Toast.makeText(hanh1_2.this, "Check a butt pls", Toast.LENGTH_SHORT).show();
}
else {
Intent intent2 = new Intent(hanh1_2.this,hanh1_3.class);
startActivity(intent2);
}
}
});
Meaningless to advanced, but may helpful for some newbie like me :)
Have a look at the Form stuff tutorial on the Android dev site. You can supply an OnClickListener to all RadioButtons and keep track of the one selected (if any).
private OnClickListener radio_listener = new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
RadioButton rb = (RadioButton) v;
Toast.makeText(HelloFormStuff.this, rb.getText(), Toast.LENGTH_SHORT).show();
}
};
Alternatively, you can potentially use the RadioGroup's getCheckedRadioButtonId() method.
As illustrated in one of the other answers: pass the int value as an extra to the Intent you use to launch your second Activity:
// In first activity
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putInt("selected_index", selectedIndex);
startActivity(i);
// In second activity
int selectedIndex = getIntent().getExtras().getInt("selected_index");
Take all your RadioButton and RadioGroup to class level.
initialize them inside onCreate()
now inside onClick() get id of checked RadioButton and compare like this:
public void onClick(View v) {
int checked = tieng.getCheckedRadioButtonId(); // tieng is your RadioGroup
switch(checked)
{
case R.id.tieng1:
Toast.makeText(hanh1_2.this, "First is selected", Toast.LENGTH_SHORT).show();
break;
case R.id.tieng1:
Toast.makeText(hanh1_2.this, "Second is selected", Toast.LENGTH_SHORT).show();
break;
case R.id.tieng1:
Toast.makeText(hanh1_2.this, "Third is selected", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(hanh1_2.this, "pleas check any button", Toast.LENGTH_SHORT).show();
break;
}
}
put extra along with intent :
else {
Intent intent2 = new Intent(hanh1_2.this,hanh1_3.class);
intent2.putInt(Index1, index1);
startActivity(intent2);
}
now inside second activity onCreate() read this extra :
{
int Index1 = getIntent().getExtras().getInt("Index1");
//do stuff here
}

Categories

Resources