Cannot resolve private void method - java

Android studio does not recognize a method within my code.
I implemented a method to handle the call.
private void saveDeal(){
String title = textTitle.getText().toString();
String description = textDescription.getText().toString();
String price = textPrice.getText().toString();
TravelDeal deal = new TravelDeal(title, description, price, "");
mDatabaseReference.push().setValue(deal);
}
private void clean(){
textTitle.setText("");
textDescription.setText("");
textPrice.setText("");
textTitle.requestFocus();
}
But in the method call,
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_save:
saveDeal();
Toast.makeText(this, "Deal saved", Toast.LENGTH_LONG);
clean();
return true;
default:
return super.onOptionsItemSelected(item);
}
saveDeal() and clean() are still showing in red in the switch block.

Found a solution. I missed a closing curly bracket in the switch statement in the onOptionsItemsSelectedMenu() method.

From Android Studio Menu, Try File->Invalidate Caches/Restart->Invalidate and Restart

Related

Global value becomes null in method

I have created a private member of the whole class called Member curMbr;
The activity (rather the fragment, since this is in a frament class) has a listview
with some contributions from members.
I also have a context menu on that list. When clicking on a contribution, I want a (customized) dialog box to show details about the member. (Member ID is part of the contribution objet. )
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
Log.d("FRGCOTIZ02", "create ctxt menu");
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
String[] menuItems = getResources().getStringArray(R.array.ar_menu_ctxt_participant);
// Get selected member
Contribution curCotis = (Contribution) (((ListView)v).getItemAtPosition(info.position));
Participant p = new Participant(helper.getDBItem(DBHelper.TABLE_PARTICIPANT,
DBHelper.COL_ID, curCotis.getParticipant()));
curMbr = new Member(helper.getDBItem(DBHelper.TABLE_MEMBER, DBHelper.COL_ID, p.getMember()));
for (int i = 0; i < menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
Log.d("FRGCOTIZ01", curMbr.getId_());
}
#Override
public boolean onContextItemSelected(MenuItem item) {
return ( applyContextMenuSelection(item) || super.onContextItemSelected(item) );
}
private boolean applyContextMenuSelection(MenuItem item) {
switch (item.getItemId()) {
case 0: // Summary
final Dialog dlg = new Dialog(this.getContext());
final String sessID;
try {
sessID = KUtil.DATE_FORMAT.format(curSess.getDate());
dlg.setContentView(R.layout.alert_show_charges);
Button btnOK = dlg.findViewById(R.id.btn_alertOK);
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setupAlertDialogCharges(dlg, sessID, curMbr.getId_());
}
});
Button btnCancel = dlg.findViewById(R.id.btn_alertCancel);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dlg.dismiss();
}
});
dlg.show();
} catch (Exception e){
Log.d("FRAGMENT Contribution", e.getMessage());
}
break;
case 1: // Collect
break;
case 2: // Cancel
break;
default:
break;
}
return true;
}
In method onCreateContextMenu, I can get the member and display his ID.
But in method applyContextMenuSelection, there is an exception, saying the meber is null!
Funny enough there is another variable that I am using in that method, and it works fine. Difference is, that variable has been set at creation of the fragment.
How do I solve this?
I have been studying the code for a while and the only thing I could figure was that the issue is somehow linked to the use of contextmenu. It seems to me that variables are set back to their original when the menu action is supposed to be executed. Again, I am not too sure about that.
So, the only solution I found so far was to keep that vale in a "higher" context:
When I can still read the value,
getActivity().getIntent().putExtra(HomeActivity.ID_ENTRY, curMbr.getId_());
When I want to use it,
final String mbrID = getActivity().getIntent().getStringExtra(HomeActivity.ID_ENTRY);

How to reference to a variable from onLoadFinished in onOptionsItemSelected?

In this onLoadFinished method I get the content of a particular database column and set it on an EditView (mEditView), the id of which has been defined earlier in OnCreate method:
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor)
{
if (cursor.moveToFirst())
{
int textColumnIndex = cursor.getColumnIndex(NoteEntry.COLUMN_TEXT);
String content = cursor.getString(textColumnIndex);
mEditView.setText(content);
}
Now I need to use the variable "content" outside this method. For example, I write a method to make a toast message containing the "content" appear on the screen:
private void displayContent(String content)
{
Toast.makeText(this, content, Toast.LENGTH_SHORT).show();
}
I want this toast to be displayed when an Actionbar menu button is clicked. But here a face a problem - when I include displayContent(String content) in OnOptionsItemSelected, I get an error because the variable "content" is not being recognized.
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case R.id.display_toast:
displayContent(String text);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
Passing "String content" as second input to onOptionsItemSelected also doesn't solve the problem. I'm new to Android programming, and despite of spending a lot of time searching for a solution on the web I couldn't find an answer. So I would be very thankful for any help.
The line displayContent(String text) is basically creating a new variable text and then feeding that to the method, so it is empty. You have to save the variable as a global variable in your Activity, then you can access it in onOptionItemSelected. So it would be like this:
public class MyActivity extends Activity {
private String content;
then later in onLoadFinished you do not create a new variable you use that one
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor)
{
if (cursor.moveToFirst())
{
int textColumnIndex = cursor.getColumnIndex(NoteEntry.COLUMN_TEXT);
content = cursor.getString(textColumnIndex);
mEditView.setText(content);
}
then in onOptionItemSelected you use content as a parameter of your method:
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case R.id.display_toast:
displayContent(content);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
Study up on the difference between local and global variables and this will make sense to you.

Cannot resolve symbol 'setOnClickListener' - AndroidStudio

I'm relatively a rookie/beginner with Java/Android programming. I've been trying to make it so while I press a given button in my application it produces a DTMF tone, but when I try to use setOnTouchListener the Android Studio shows me that error. It also gives me an error for MotionEvent which states Expression expected
Here are the important parts of the code:
boolean pressedCCW = false;
class SendCCWTone extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... arg0){
ToneGenerator toneGen;
toneGen = new ToneGenerator(AudioManager.STREAM_DTMF,100);
while(pressedCCW){
toneGen.startTone(ToneGenerator.TONE_DTMF_1);
}
toneGen.stopTone();
toneGen.release();
createLog("CCW");
return null;
}
}
final Button buttonCCW = (Button) findViewById(R.id.counter_clockwise);
buttonCCW.setOnTouchListener(new View.OnTouchListener(){// Where the error is
#Override
public boolean onTouch(View v, MotionEvent event){// Where the other error is located
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
if(pressedCCW == false){
pressedCCW = true;
new SendCCWTone().execute();
}
break;
case MotionEvent.ACTION_UP:
pressedCCW = false;
}
return true;
}
});
You are creating OnTouchListener inside of setOnClickListener. If you need TouchListener then you should register using setOnTouchListener instead of setOnClickListener
buttonCCW.setOnTouchListener(new View.OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event){
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
if(pressedCCW == false){
pressedCCW = true;
new SendCCWTone().execute();
}
break;
case MotionEvent.ACTION_UP:
pressedCCW = false;
}
return true;
}
});
This problem can be solved if you place setOnTouchListener inside the onCreate() method of your activity.
Rather than use setOnClickListener, you can set onClick in the XML and point to a method (it does the same thing and looks nicer). In this case, you'd have a method like produceSound:
public void produceSound(View view) {
// your onClick method
}
and in the activity's XML, find where that button, counter_clockwise, is and add: android:onClick="produceSound" to the button's XML.
More here if you're curious: How exactly does the android:onClick XML attribute differ from setOnClickListener?
However, if you're using onTouch, then you will have to stick with what everyone else is suggesting. XML does not support an android:onTouch attribute.
Try to add this to your code :
implements View.OnTouchListener
and use setOnTouchListner instead of setOnClickListener.
buttonCCW.setOnListener(new View.OnTouchListener(){// Where the error is
#Override
public boolean onTouch(View v, MotionEvent event){// Where the other error is located
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
if(pressedCCW == false){
pressedCCW = true;
new SendCCWTone().execute();
}
break;
case MotionEvent.ACTION_UP:
pressedCCW = false;
}
return true;
}
});

Java: How to reuse listeners

I would like to reuse an AlertBuilder and therefore put its creation in an own method. Something like this:
private boolean askToDiscardChanges() {
final boolean result = false;
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
result = true;
break;
case DialogInterface.BUTTON_NEGATIVE:
result = false;
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(NewShootingActivity.this);
builder.setMessage(getResources().getString(R.string.msgDiscardChanges)).setPositiveButton(getResources().getString(R.string.lblYes), dialogClickListener)
.setNegativeButton(getResources().getString(R.string.lblNo), dialogClickListener).show();
return result;
}
Unfortunately, this does not work but I hope it helps to understand my issue. Is it possible to return the result of a listener? How?
Thanks
A listener is a callback function. It will be called at some later point in time, possibly far in the future- or even possibly never. So no, it can't return a value, because we don't know what to return yet. If you want to run some code based on a callback being called, you need to put that code in the callback.

How to check is context current running activity

I'm working on my first Android app and I have one issue I cannot sorted. I checked out stack overflow but I cannot find the solution.
I have a menu which show 4 different Activities when menu item is selected.
I also have a class which manage the menu:
public class TabMenuManager {
final Context context;
public TabMenuManager(Context context) {
this.context = context;
}
public boolean handleTabMenuAction(int item) {
Log.d("Toolstrea", "TAB MENU HANDLED: " + item);
switch (item) {
case R.id.action_home:
handleHomeAction();
return true;
case R.id.action_reorder:
handleReOrderAction();
return true;
//.....
}
private void handleReOrderAction() {
if (this.context.getApplicationContext() instanceof ReOrderActivity) {
Log.d("Toolstream", "REORDER CLASSES THE SAME");
Intent reOrderIntent = new Intent(this.context, ReOrderActivity.class);
reOrderIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.context.startActivity(reOrderIntent);
}
else
Log.d("Toolstream", "REORDER CLASSES NOT THE SAME");
}
private void handleHomeAction() {
// Simmilar as one above
}
}
In all activities I show the menu I just call:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
TabMenuManager tmm = new TabMenuManager(getApplicationContext());
boolean success = tmm.handleTabMenuAction(item.getItemId());
if (!success) {
return super.onOptionsItemSelected(item);
}
return success;
}
This class just simple show activity but I want to make sure it won't present the same activity as current one.
In this example I use:
this.context.getApplicationContext() instance of ReOrderActivity
But I also tried
this.context.getClass() == HomeActivity.class
It always log that the activity are different.
It cause the problem that if I'm in HomeActivity I can press Home in my menu and another instance of HomeActivity will be added on the stack and so on.
How can I make sure I present just one instance of the activity?
Is there a better way I doing that?
Many thanks.
In your code, this.context.getApplicationContext() instance of ReOrderActivity can never be true. You should change it to: this.context instance of ReOrderActivity
You also need to change how you create your TabMenuManager in onOptionsItemSelected. Change it to: TabMenuManager tmm = new TabMenuManager(this);

Categories