I have a addAllToGroup click function and I use the DialogWithRadioButtonM in many different places, is it possible to place DialogWithRadioButtonM() and redioGroup1() functions in a separate file(class)? Here is my code:
i tried to put it in a class but i get error for onclicklistener in it and also i dont know how to use context in a nonActivity java file. sorry, I am new in android and java thanks for help.
public void addAllToGroup(View view) {
csM = new String[6];
//dialogTitle="Add This to Group";
csM[0] = "Add to Group 1";
csM[1] = "Add to Group 2";
csM[2] = "Add to Group 3";
csM[3] = "Add to Group 4";
csM[4] = "Add to Group 5";
csM[5] = "Remove Grouping";
DialogWithRadioButtonM("Add Selected to Group");
}
public void DialogWithRadioButtonM(String str){
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(str);
builder.setSingleChoiceItems(csM, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Log.i("TAG2", "onCreate: "+item);
switch(item)
{
case 0: backFromDialogM=0; break;
case 1: backFromDialogM=1; break;
case 2: backFromDialogM=2; break;
case 3: backFromDialogM=3; break;
case 4: backFromDialogM=4; break;
case 5: backFromDialogM=5; break;
case 6: backFromDialogM=6; break;
case 7: backFromDialogM=7; break;
}
redioGroup1(backFromDialogM);
alertDialogM.dismiss();
}
});
alertDialogM = builder.create();
alertDialogM.show();
}
public void redioGroup1(int group) {
int iCount = myRecycler.getAdapter().getItemCount();
MyDateBase mydbM = new MyDateBase(MainActivity.this);
final SQLiteDatabase databaseM = mydbM.getWritableDatabase();
String strCL = "cl" + "0";
String rawQueryM="";
for (int i = 0; i < iCount; i++) {
if (mAdapter.itemList.get(i).isChecked()) {
mAdapter.itemList.get(i).getuSentId();
rawQueryM ="UPDATE wp_words SET " + strCL + " =" + group + " WHERE wid= " + mAdapter.itemList.get(i).getuSentId();
databaseM.execSQL(rawQueryM);
Log.i("tog", "" + mAdapter.itemList.get(i).getuSentId());
}
}
Log.i("togf", "" + rawQueryM);
}
thanks
Your "DialogWithRadioButtonM" Class depends of the outer class in which it is.
You have to make "DialogWithRadioButtonM" not dependant of other variables/objects outside it, or you cannot move it in a stand alone Class file.
For example: "backFromDialogM" and "alertDialogM" are not declared INSIDE DialogWithRadioButtonM but somewhere else in the same file.
Related
I'm new to Android. I'm trying to develop my first calculator. My calculator output is good, but I'm trying to make some changes to it. Please suggest. My output is 2+2=4.0 How can I get 4 if I put 2+2 and 4.0 when I put 2.8+1.2.
Also, please help me out in trying to figure out how can i keep on adding till i press =.
My code that I'm looking at is below:
private View.OnClickListener buttonClickListerner = new
View.OnClickListener() {
float r;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.clear:
screen.setText("");
operator.setText("");
FirstNum= 0;
showtext.setText("");
break;
case R.id.buttonAdd:
mMath("+");
operator.setText("+");
showtext.setText(String.valueOf(FirstNum));
break;
case R.id.buttonMinus:
mMath("-");
operator.setText("-");
break;
case R.id.buttonMul:
mMath("*");
operator.setText("*");
break;
case R.id.buttonequal:
mResult();
break;
case R.id.buttonDiv:
mMath("/");
operator.setText("/");
break;
case R.id.buttonPercent:
mMath("%");
r = FirstNum / 100;
showtext.setText("[" + String.valueOf(FirstNum) + "%" + "]");
screen.setText(String.valueOf(r));
break;
default:
String num = ((Button) v).getText().toString();
getKeyboard(num);
break;
}
}
};
public void mMath(String str){
FirstNum = Float.parseFloat(screen.getText().toString());
operation = str;
screen.setText("");
}
public void getKeyboard(String str){
String CurrentScreen = screen.getText().toString();
if(CurrentScreen.equals("0"))
CurrentScreen = "";
CurrentScreen = CurrentScreen + str;
screen.setText(CurrentScreen);
String ExScreen = CurrentScreen;
screen.setText(ExScreen);
}
public void mResult(){
float SecondNum = Float.parseFloat(screen.getText().toString());
float ThirdNum = Float.parseFloat(screen.getText().toString());
float result = 0;
//float exresult = result;
if(operation.equals("+")){
result = FirstNum + SecondNum;
// exresult = result + ThirdNum;
}
if(operation.equals("-")){
result = FirstNum - SecondNum;
//exresult = result - ThirdNum;
}
if(operation.equals("*")){
result = FirstNum * SecondNum;
//exresult = result * ThirdNum;
}
if(operation.equals("/")){
result = FirstNum / SecondNum;
//exresult = result / ThirdNum;
}
screen.setText(String.valueOf(result));
//screen.setText(String.valueOf(exresult));
showtext.setText(String.valueOf(FirstNum + operation + SecondNum));
//showtext.setText(String.valueOf(FirstNum + operation + SecondNum +
operation + ThirdNum));
}
}
I guess you should do your calculations as double and then before setting the output to TextView (or whatever you are using), check for the output if int or not and then decide which form of output to set to the TextView.
if ((variable == Math.floor(variable)) && !Double.isInfinite(variable)) {
// integral type
}
See this
Edit:
The idea is to check that fractional part of the number is 0 (i.e.) the number is integer.
You may also Use these conditions [if true then variable is an Integer]
// check if
variable == Math.ceil(variable)
or
// check if
variable == Math.round(variable)
Also Math.round(float f) will return the interger form of the number!
To add multiple item first set up an array with a size of how long the user can input and then loop through each array adding them equivalently... i know this is a vague answer but you can ask me if anything is unclear and also an up vote would be nice. you got the right idea for the cases just try the following code
// array to sum
int[] numbers = new int[]{ 10, 10, 10, 10};
int sum = 0;
for (int i=0; i < numbers.length ; i++) {
sum = sum + numbers[i];
}
System.out.println("Sum value of array elements is : " + sum);
}
I have a listView that I want to display text files in the row folder corresponding to the list item that has been clicked. My code so far:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String displaytxt = "";
int fileLen = 0;
try {
InputStream text = null;
switch(position) {
case 1:
text = getResources().openRawResource(R.raw.books1);
break;
case 2:
text = getResources().openRawResource(R.raw.books2);
break;
case 3:
text = getResources().openRawResource(R.raw.books3);
break;
default:
break;
}
fileLen = text.available();
byte[] fileBuffer = new byte[fileLen];
text.read(fileBuffer);
text.close();
displaytxt = new String (fileBuffer);
}
catch (IOException e) {
}
tv.setText(displaytxt);
}
But when I click the first item on the list I get an error in the emulator
Try to change:
switch(position) {
case 0:
text = getResources().openRawResource(R.raw.books1);
break;
case 1:
text = getResources().openRawResource(R.raw.books2);
break;
case 2:
text = getResources().openRawResource(R.raw.books3);
break;
default:
text = getResources().openRawResource(R.raw.books1); // paste default book
break;
}
I have a fragment, which displays an alert dialog. The alert dialog contains a few buttons with OnClickListeners attached to them.
When clicked, I need to pass some integers into the OnClickListener. I tried the following:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getActivity().getString(R.string.aufgabe_loeschen));
builder.setItems(new CharSequence[]
{getActivity().getString(R.string.nur_diese_wiederholung_löschen),
getActivity().getString(R.string.alle_wiederholungen_löschen)},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(), "selectedAufgabeId: " + String.valueOf(HomeFragment.this.selectedAufgabeId), Toast.LENGTH_SHORT).show();
Toast.makeText(getActivity(), "selectedAufgabeInstanzId: " + String.valueOf(HomeFragment.this.selectedAufgabeInstanzId), Toast.LENGTH_SHORT).show();
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
// nur_diese_wiederholung_löschen
String aufgabeInstanzWhere = AufgabeInstanzContract.Columns._ID + " = ?";
String[] aufgabeInstanzSelectionArgs = {String.valueOf(HomeFragment.this.selectedAufgabeInstanzId)};
int rows = HomeFragment.this.getActivity().getApplicationContext().getContentResolver().delete(AufgabeInstanzContract.CONTENT_URI, aufgabeInstanzWhere, aufgabeInstanzSelectionArgs);
loadAufgabenData();
break;
case 1:
// alle_wiederholungen_löschen
String aufgabeInstanzWhere2 = AufgabeInstanzContract.Columns.AUFGABE_ID + " = ?";
String[] aufgabeInstanzSelectionArgs2 = {String.valueOf(HomeFragment.this.selectedAufgabeId)};
int rows2 = HomeFragment.this.getActivity().getApplicationContext().getContentResolver().delete(AufgabeInstanzContract.CONTENT_URI, aufgabeInstanzWhere2, aufgabeInstanzSelectionArgs2);
loadAufgabenData();
Toast.makeText(getActivity(), "clicked 2", Toast.LENGTH_SHORT).show();
break;
}
}
});
builder.create().show();
selectedAufgabeId and selectedAufgabeInstanzId are public int properties, which change their values with the user interaction. However, both properties remain their initial values (values at the start of the fragment).
How can I access their current values?
I am programming this whole day and now i am stuck with unreachable after return; at
return;
Recipe093.path[1] = localCursor.getString(1);
If i remove return i get unreachable code after continue;
Why do I get unreachable code?
Hope someone can help me and Thanks.
Here is my code:
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
setContentView(R.layout.musiclist);
final Cursor localCursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, (String[])null, null, (String[])null, null);
String[] arrayOfString1 = localCursor.getColumnNames();
int i = arrayOfString1.length;
for (int j = 0; ; j++)
{
if (j >= i)
{
String[] arrayOfString2 = { "title", "artist", "duration" };
int[] arrayOfInt = { 2131099668, 2131099669, 2131099670 };
SimpleCursorAdapter localSimpleCursorAdapter = new SimpleCursorAdapter(getApplicationContext(), 2130903044, localCursor, arrayOfString2, arrayOfInt);
localSimpleCursorAdapter.setViewBinder(new AudioListViewBinder());
ListView localListView = (ListView)findViewById(2131099667);
localListView.setAdapter(localSimpleCursorAdapter);
Log.d("test", "start list()");
localListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> paramAnonymousAdapterView, View paramAnonymousView, int paramAnonymousInt, long paramAnonymousLong)
{
switch (Recipe093.this.getIntent().getIntExtra("case1", 0))
{
default:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
}
while (true)
{
Intent localIntent = new Intent(Recipe093.this.getApplicationContext(), MainActivity.class);
Recipe093.this.startActivity(localIntent);
return;
Recipe093.path[1] = localCursor.getString(1);
SharedPreferences.Editor localEditor10 = Recipe093.this.getSharedPreferences("FileName", 3).edit();
localEditor10.putString("userChoice", Recipe093.path[1]);
localEditor10.commit();
continue;
Recipe093.path[2] = localCursor.getString(1);
SharedPreferences.Editor localEditor9 = Recipe093.this.getSharedPreferences("FileName", 3).edit();
localEditor9.putString("userChoice1", Recipe093.path[2]);
localEditor9.commit();
}
}
});
return;
}
Log.d("Recipe093", arrayOfString1[j]);
}
}
private class AudioListViewBinder
implements SimpleCursorAdapter.ViewBinder
{
private AudioListViewBinder()
{
}
public boolean setViewValue(View paramView, Cursor paramCursor, int paramInt) {
// TODO Auto-generated method stub
int i = paramCursor.getColumnIndex("title");
int j = paramCursor.getColumnIndex("artist");
int k = paramCursor.getColumnIndex("duration");
if ((paramInt == i) || (paramInt == j))
((TextView)paramView).setText(paramCursor.getString(paramInt));
return false;
}
}
}
Basically, return; means "exit this method now". So anything after a return statement is not run.
You can use scope to have multiple returns:
if(x == 1) {
return;
// Nothing will be called here on down in this scope, i.e. before `}`
}
x = 1;
return;
// Nothing will be called here on down
If you can return; the code stops and returns to the first method. It will not run any code after this line. The same story with break;
As Sam said (you should accept his answer), return means exit now.
However, return for a method which returns void is optional, since the closing brace for the method will also return:
These are equivalent:
void someMethod(){
doSomeStuff();
return;
}
void someMethod(){
doSomeStuff();
}
It is considered bad practice to use return in a void method unless you want to return early but, any explicit return must be conditional, i.e. part of a switch or if statement. If they are not conditional, then the compiler knows that the method will always exit at that point and any code after it cannot possibly execute, hence the compiler error you are seeing.
To most Java coders, the first example just looks wrong.
PS. while(true) is horrible but, if you want to get out of that loop early, you should use break which will transfer execution to the statement after the end of the while loop, not return.
What I am trying to do is to handle multitouch buttons. I have 6 buttons and the user may touch from 1 to 6 buttons. The problem is that MotionEvent can handle up to 3 pointers but what I need is up to 6 pointers. Any help please?
This is the code:
public class MultitouchtestActivity extends Activity {
private class TouchListener implements OnTouchListener {
#Override
public boolean onTouch(final View v, final MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
switch (v.getId()) {
case R.id.button1:
sqText = "Square 1 Pressed::Pointer count = "
+ String.valueOf(event.getPointerCount());
break;
case R.id.button2:
sq1Text = "Square 2 Pressed::Pointer count = "
+ String.valueOf(event.getPointerCount());
break;
case R.id.button3:
sq2Text = "Square 3 Pressed::Pointer count = "
+ String.valueOf(event.getPointerCount());
break;
case R.id.button4:
sq3Text = "Square 4 Pressed::Pointer count = "
+ String.valueOf(event.getPointerCount());
break;
case R.id.button5:
sq4Text = "Square 5 Pressed::Pointer count = "
+ String.valueOf(event.getPointerCount());
break;
case R.id.button6:
sq5Text = "Square 6 Pressed::Pointer count = "
+ String.valueOf(event.getPointerCount());
break;
}
} else if (event.getAction() == MotionEvent.ACTION_POINTER_1_DOWN) {
switch (v.getId()) {
case R.id.button1:
sqText = "Square 1 Pointer1Down::Pointer count = "
+ String.valueOf(event.getPointerCount()) + "\n";
break;
case R.id.button2:
sq1Text = "Square 2 Pointer1Down::Pointer count = "
+ String.valueOf(event.getPointerCount()) + "\n";
break;
case R.id.button3:
sq2Text = "Square 3 Pointer1Down::Pointer count = "
+ String.valueOf(event.getPointerCount()) + "\n";
break;
case R.id.button4:
sq3Text = "Square 4 Pointer1Down::Pointer count = "
+ String.valueOf(event.getPointerCount()) + "\n";
break;
}
} else if (event.getAction() == MotionEvent.ACTION_POINTER_2_DOWN) {
switch (v.getId()) {
case R.id.button1:
sqText = "Square 1 Pointer2Down::Pointer count = "
+ String.valueOf(event.getPointerCount()) + "\n";
break;
case R.id.button2:
sq1Text = "Square 2 Pointer2Down::Pointer count = "
+ String.valueOf(event.getPointerCount()) + "\n";
break;
case R.id.button3:
sq2Text = "Square 3 Pointer2Down::Pointer count = "
+ String.valueOf(event.getPointerCount()) + "\n";
break;
case R.id.button4:
sq3Text = "Square 4 Pointer2Down::Pointer count = "
+ String.valueOf(event.getPointerCount()) + "\n";
break;
}
} else if (event.getAction() == MotionEvent.ACTION_POINTER_3_DOWN) {
switch (v.getId()) {
case R.id.button1:
sqText = "Square 1 Pointer3Down::Pointer count = "
+ String.valueOf(event.getPointerCount()) + "\n";
break;
case R.id.button2:
sq1Text = "Square 2 Pointer3Down::Pointer count = "
+ String.valueOf(event.getPointerCount()) + "\n";
break;
case R.id.button3:
sq2Text = "Square 3 Pointer3Down::Pointer count = "
+ String.valueOf(event.getPointerCount()) + "\n";
break;
case R.id.button4:
sq3Text = "Square 4 Pointer3Down::Pointer count = "
+ String.valueOf(event.getPointerCount()) + "\n";
break;
}
}
// TODO Auto-generated method stub
return true;
}
}
protected Button sq1;
protected Button sq2;
protected Button sq3;
protected Button sq4;
protected Button sq5;
protected Button sq6;
protected String sqText = new String();
protected String sq1Text = new String();
protected String sq2Text = new String();
protected String sq3Text = new String();
protected String sq4Text = new String();
protected String sq5Text = new String();
private final Handler handler = new Handler();
private final Runnable mUpdateUITimerTask = new Runnable() {
#Override
public void run() {
// do whatever you want to change here, like:
updateTextField();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setViews();
handler.postDelayed(mUpdateUITimerTask, 5000);
}
private void setViews() {
sq1 = (Button) findViewById(R.id.button1);
sq2 = (Button) findViewById(R.id.button2);
sq3 = (Button) findViewById(R.id.button3);
sq4 = (Button) findViewById(R.id.button4);
sq5 = (Button) findViewById(R.id.button5);
sq6 = (Button) findViewById(R.id.button6);
sq1.setOnTouchListener(new TouchListener());
sq2.setOnTouchListener(new TouchListener());
sq3.setOnTouchListener(new TouchListener());
sq4.setOnTouchListener(new TouchListener());
sq5.setOnTouchListener(new TouchListener());
sq6.setOnTouchListener(new TouchListener());
}
private void updateTextField() {
final TextView view1 = (TextView) findViewById(R.id.logView);
final TextView view2 = (TextView) findViewById(R.id.logView1);
final TextView view3 = (TextView) findViewById(R.id.logView2);
final TextView view4 = (TextView) findViewById(R.id.logView3);
final TextView view5 = (TextView) findViewById(R.id.logView4);
final TextView view6 = (TextView) findViewById(R.id.logView5);
// view1.append(sqText + "\n");
view1.setText(sqText);
view2.setText(sq1Text);
view3.setText(sq2Text);
view4.setText(sq3Text);
view5.setText(sq4Text);
view6.setText(sq5Text);
handler.post(mUpdateUITimerTask);
}
}
The number of pointers that you can detect with android depends on the device. Some older ones can only detect one whereas more modern ones may be able to detect more.
Please make sure that your app also works on devices with less pointers if you want to publish it on the market.