How to Modularize Long Code - java

I have over 900 lines in my MainActivity because I can't figure out how to make other classes work.
It works but it makes it hard to read and tedious to update.
I will give an example of what I would want to separate to another class.
I would like to call this from the main activity.
MainActivity:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.apm:
apm();
return true;
}
}
public void apm() {
AlertDialog levelDialog;
final CharSequence[] items = {" Reboot ", " Reboot Recovery ", " Hot Reboot "};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("What do you want to do?");
builder.setCancelable(true);
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
rooted();
reboot();
break;
case 1:
rooted();
recovery();
break;
case 2:
rooted();
softreboot();
break;
//case 3:
//shutdown();
//break;
}
}
});
levelDialog = builder.create();
levelDialog.show();
}

Create a new class called Util (for example) in a new file, Util.java.
In this class put:
public static void apm(MainActivity activity){
//Put the code from your old apm method here.
//Whenever you need to call a method that is part of MainActivity
//just prepend activity. in front of the method call.
}
Then in MainActivity, call Util.apm(this);.
EDIT:
Here's more detail. Put the following in Util.java and call Util.apm(this); in your MainActivity.
public static void apm(MainActivity activity) {
AlertDialog levelDialog;
final CharSequence[] items = {" Reboot ", " Reboot Recovery ", " Hot Reboot "};
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("What do you want to do?");
builder.setCancelable(true);
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
activity.rooted();
activity.reboot();
break;
case 1:
activity.rooted();
activity.recovery();
break;
case 2:
activity.rooted();
activity.softreboot();
break;
//case 3:
//activity.shutdown();
//break;
}
}
});
levelDialog = builder.create();
levelDialog.show();
}

you can write your apm method in another class. From your mainActivity, you can instanciate that class and pass the context of the activity to the constructor of the class.
then from mainActivity, just call the methods of that class using the class instance.
I hope you understand what I try to say. In your new class, you can access mainActivity components using the context you received in constructor.

Related

AlertDialog does not show text

I am using alertDialog with switch case, I want the text to change depending on the case value.
here is the code that I tried :
private void transacechouée(int i) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity())
.setTitle("Information")
.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new Thread(new Runnable() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void run() {
Intent intent = new Intent(getActivity(), CashActivity1.class);
startActivity(intent);
}
}).start();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
ReadCardFragment.alertDialogBuilder=alertDialogBuilder;
}
});
switch (i){
case 1 :
alertDialogBuilder.setMessage("Transaction non aboutie");
break;
case 2:
alertDialogBuilder.setMessage("Connexion impossible");
break;
case 3:
alertDialogBuilder.setMessage("Problème de récéption");
break;
case 4:
alertDialogBuilder.setMessage("Erreur de traitement");
break;
case 5:
alertDialogBuilder.setMessage("Erreur de transmission");
break;
case 6:
alertDialogBuilder.setMessage("Timout");
break;
case 7:
alertDialogBuilder.setMessage("Transaction invalide");
break;
case 90:
alertDialogBuilder.setMessage("Piste non valide");
break;
case 91:
alertDialogBuilder.setMessage("Transaction non valide");
break;
}
}
I expect the alertDialog to set the message depending on the case, but it doesn't display any text.
You need to calls to setMessage to occur before the dialog is actually shown. Remember that the AlertDialog.Builder just builds the AlertDialog, using all the details that you've given it. Calling the methods of AlertDialog.Builder after the AlertDialog has already been created is too late.
Move the whole switch/case structure that you've got upwards, to just before the line AlertDialog alertDialog = alertDialogBuilder.create();.

How to fix automatic view another activity on spinner onItemSelected methods

I'm working on simple android project that require spinner widget in android studio. what i want to do is, when a user select choices from the spinner it will open another activity. while i'm in the middle of the coding. I decided to use switch case condition with Intent. The problem is whenever i run the application it will automatically go to the specific activity location that i declare. Even though I didn't select any choice on spinner.
Note: log cat doesn't show any error
Your help is very much appreciated to beginner like me.
public class CustomOnItemSelectedListener extends Activity implements
OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
// **************************** below here is where I start the new activity
switch (pos) {
case 0 :
Intent i = new Intent(app.this, home.class);
app.this.startActivity(i);
break;
case 1 :
//Intent intent = new Intent(app.this, about.class);
//app.this.startActivity(intent);
break;
case 2 :
//Intent intent1 = new Intent(app.this, home.class);
//app.this.startActivity(intent1);
break;
}
// **************************** above here is where I start the new activity
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Try this
Declare an int in your class, e.g. before onCreate(), then in your onCreate() you assign it to 0. Use this variable to check if its bigger than 0 when selecting something with your spinner, example below.
public class ExampleActivity extends AppCompatActivity {
private int spinnerCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSpinnerCheck = 0;
mMySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int itemId = (int) id;
// For some reason this method is called during initialization, so increment counter once to prevent it from auto selecting first item when loading view
spinnerCheck += 1;
if (spinnerCheck > 1) {
switch (pos) {
case 0:
Intent i = new Intent(app.this, home.class);
app.this.startActivity(i);
break;
case 1:
//Intent intent = new Intent(app.this, about.class);
//app.this.startActivity(intent);
break;
case 2:
//Intent intent1 = new Intent(app.this, home.class);
//app.this.startActivity(intent1);
break;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
For some reason it selects the first item once created, not sure why, but this should work.
When the application is created by default the first option is selected in your spinner and your listener is called. To avoid this you can use the solution of #Simon
or you can use a button to confirm your selection and change your activity when this button is pressed and not when an item is selected in your spinner.
UPDATE
You can also populate the first entry of your spinner with a useless text which can be a title like "Select activity" and start your switch in the listener to 1 and not 0

Button long click does not work

I'm working on a soundboard and I want to implement a long click to share the sound.
I am working with a switch Case for each button
public void MainMMP(View view){
switch (view.getId()) {
case R.id.button1:
MainMMP.release();
MainMMP = MediaPlayer.create(this, R.raw.xxx1);
MainMMP.start();
break;
case R.id.button2:
MainMMP.release();
MainMMP = MediaPlayer.create(this, R.raw.xxx2);
MainMMP.start();
break;
case R.id.button3:
MainMMP.release();
MainMMP = MediaPlayer.create(this, R.raw.xxx3);
MainMMP.start();
break;
And now I want to implement the long click. I tried a lot of different code here but it is not working for me.
I do not know where to put the onLongClick statement and how.
Can somebody show me a working method and in case of long click it should just send me a Toast that I know the method works?
You could add the OnLongClickListener where you want, in the onCreate method for example.
Try to use the following code:
Button button = (Button)findViewById(R.id.button);
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//Your code
return false; // True if you want to execute simple click code too
}
});
You can use this
private View.OnLongClickListener listener = new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
switch (view.getId())
case R.id.button1:
// Do something...
break;
case R.id.button2:
// Do something else...
break;
// If you still want to get normal click callbacks return true,
// if you do not then return false.
return true;
}
}
Somewhere in your code
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
button1.setOnLongClickListener(listener);
button2.setOnLongClickListener(listener);
Or better this
One common recommended way to get onClick/onLongClick/whatever callbacks is to make the Activity implement the callback interfaces.
class YourActivity extend Activity implements View.OnLongClickListener {
#Override
public boolean onCreate(/* ... */) {
// ...
button1.setOnLongClickListener(this);
button2.setOnLongClickListener(this);
}
#Override
public boolean onLongClick(View view) {
// Same code as the one above
}
}

AlertDialog box Repeats four times

OK my question is a lot bigger than the Title. But can't describe everything in a Title. So here we go.
I am writing an App that when a NFC cards get detected by Phone, it will be able to WRITE and READ a NDEF message on / from it.
I use two buttons READ and WRITE to trigger these events. Everything works fine, just the thing that EVERYTHING REPEATS ITSELF FOUR (4x) TIMES!
Only the TAG "UltraLightCard Detected" and "Connected" pops once.
Everything else that you see in code in "ShowMessage" will pop out 4x times also the AlertDialog box gets triggered 4x times and you have to write the text 4 times.
If you wrote it only once and then clicked "Save" 3x times just to close it, it wont store the string.
Here's my code:
protected void ultralightCardLogic() {
final Button b_write = (Button)findViewById(R.id.b_write);
final Button b_read = (Button)findViewById(R.id.b_read);
b_write.setId(1);
b_read.setId(2);
//showImageSnap(R.drawable.ultralight);
ShowMessage("UltraLight Card Detected :" + mifareUL.getTagName(), 'a');
try {
mifareUL.connect();
mifareUL.formatT2T();
ShowMessage("Connected!" , 'd');
b_write.setOnTouchListener(new MyTouchListener());
b_read.setOnTouchListener(new MyTouchListener());
} catch (IOException e) {
e.printStackTrace();
}
}
Here is MyTouchListener:
public class MyTouchListener implements OnTouchListener{
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stu
int id = v.getId();
switch(id){
case 1:
onCreateDialog();
break;
case 2:
readNDEFmsg();
break;
case 3:
break;
}
return false;
}
}
Here is the OnCreateDialog:
final View v = getLayoutInflater().inflate(R.layout.dia_box,null);
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setView(v)
.setPositiveButton("SAVE", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
final EditText mEdit=(EditText)v.findViewById(R.id.et_dia);
String str = mEdit.getText().toString();
writeNDEFmsg(str);
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
If you guys need some more of the code, I can add it then. Don't want to write too much code, because my experience tells me that then noone will try to help me out.
Please, help me out
Thanks to your help I figured out my issue.
I used onTouchListener, which triggers more than once, since it has more MotionEvents available.
After I changed on to OnClickListener everything works smoothly!
Just be sure to implement View.OnClickListener
if you are doing it like I do in my public class MyClickListener.
Then Eclipse will auto-generate your necessary code. Extract the id of your buttons and do the switch statement (again, if you`re doing it this way):
public class MyClickListener implements android.view.View.OnClickListener{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id = v.getId();
switch(id){
case 1:
onCreateDialog();
break;
case 2:
readNDEFmsg();
break;
case 3:
break;
}
}
Thanks again for the help! Hope it will help someone else too.

android : what's the procedure to write functions for alertdialog item?

I'm going to write some function in AlertDialog's item : - Code is : -
final CharSequence[] items = {"Now", "Later", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("When you need to Take BackUp?");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item)
{
// Toast.makeText(getApplicationContext(),items[item],Toast.LENGTH_SHORT).show();
items[0].notify();
items[1].charAt(2);
}
});
builder.show();
This item will enable some function, how can i declare and define that.
The item that is selected will be passed into the onClick method, the int item in the method's signature.
public void onClick(DialogInterface dialog, int item) {
switch(item) {
case 0: // the first item in the CharSequence[]
callUserClickedNow();
break;
case 1: // the second item in the CharSequence[]
callUserClickedLater();
break;
case 2: // the thirditem in the CharSequence[]
callUserClickedCancel();
break;
}
dialog.dismiss();
}
Then outside of the method where you create the AlertDialog:
private void callUserClickedNow() {
// do stuff
}
etc...

Categories

Resources