0

Another question about using Global variable class, and extending Application. Hopefully it varies enough not to be considered a duplicate. I have read these great questions and answers.

Asynchronous programming best practices

How to use global class variables in android

Although I understand how these relate to my current problem, being that Im a total novice I have 2 main issues.

1- Im not quite sure how to apply these solutions, but I will try to figure it out on my own.

2- The second and biggest issue is, what part of my code should I actually even try to migrate over to a Global Class, or a helper class.

So I have 3 classes, Section1.java, Section2.java, Section3.java, which essentially do the same thing, in the same way, using the same methods, they even use almost exact xml layouts(only the xml's name and the drawable's with in each xml changes). The only difference is what they accept as a correct result.

My questions regarding my second point of concern, are under the pasted code.

Here is the code from from Section1.java (rough, looong spagetthi code)

Section1.java

public class Section1  extends Activity implements OnClickListener, OnInitListener{

 private TextToSpeech myTTS;
  ListView lv;
  private ProgressDialog dialog;
  static final int check = 111;
  static final int checka = 222;
  static final int checkb = 333;
      TextView speak;
  private int MY_DATA_CHECK_CODE = 0;
  int counter_score;
  RatingBar rb_cooking;
  MediaPlayer ourSong;
     ImageView display,image1,image2,image3;
     int  gotLetterA, gotLetterB,gotLetterC
     int counter_score_a;
 int counter_score_b;
 int counter_score_c;

    @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
      setContentView(R.layout.section1);
            Intent checkTTSIntent = new Intent();
        checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
        TextView speak = (TextView) findViewById(R.id.text_to_speech);
        ////////////////////////////////////

    counter_score=0;
    counter_score_this=0;
    counter_score_b=0;
    counter_score_c=0;
      image1 = (ImageView) findViewById(R.id.IVimage_1);
    image2 = (ImageView) findViewById(R.id.IVimage_2);
    image3 = (ImageView) findViewById(R.id.IVimage_3);

    initialize();


private void initialize() {
// TODO Auto-generated method stub
lv = (ListView)findViewById(R.id.lvVoiceReturn);
speak = (TextView) findViewById(R.id.text_to_speech);
Button play1 = (Button) findViewById(R.id.play_01);
Button play2 = (Button) findViewById(R.id.play_2);
Button play3 = (Button) findViewById(R.id.play_3);

 image1.setOnClickListener(this);
image2.setOnClickListener(this);
image3.setOnClickListener(this);

 play1.setOnClickListener(this);
play2.setOnClickListener(this);
play3.setOnClickListener(this);



public void speakClicked(View v) {
speak.setText("testing text");
speak(false);
}

public void speakJbClicked(View v) {
speak(true);
}
private void speak(boolean b) {
// get the text entered
TextView speak = (TextView) findViewById(R.id.texto_correcto);
speak.setText("test, spoken text");
String words = speak.getText().toString();
speakWords(words, b);
}

private void speakWords(String speech, boolean b) {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put(TextToSpeech.Engine.KEY_FEATURE_NETWORK_SYNTHESIS, "true");
myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, b ? hashMap : null);

}

    @Override
public void onClick(View v) {
    if (v.getId() == R.id.IVimage_1){
    Intent a = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    a.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,     RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    a.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
    a.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech rec prompt.");
    startActivityForResult(a, checka);
}else if(v.getId() == R.id.IVimage_2){
    Intent b = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    b.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    b.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
    b.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech rec prompt.");
    startActivityForResult(b, checkb);
}else if(v.getId() == R.id.IVimage_3){
    Intent c = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    c.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    c.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
    c.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech rec prompt.");
    startActivityForResult(c, checkc);
 }else if(v.getId() == R.id.play_01){
myTTS.setLanguage(Locale.US);
myTTS.setPitch((float) .9);
myTTS.setSpeechRate((float) 0.75);
myTTS.speak("a",TextToSpeech.QUEUE_FLUSH, null);
 }else if(v.getId() == R.id.play_2){
myTTS.setLanguage(Locale.US);
myTTS.setPitch((float) .9);
myTTS.setSpeechRate((float) 0.75);
myTTS.speak("b",TextToSpeech.QUEUE_FLUSH, null);
 }else if(v.getId() == R.id.play_3){
myTTS.setLanguage(Locale.US);
myTTS.setPitch((float) .9);/
myTTS.setSpeechRate((float) 0.75);
myTTS.speak("c",TextToSpeech.QUEUE_FLUSH, null);

     @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
        if (requestCode == MY_DATA_CHECK_CODE) {
        // if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
        // the user has the necessary data - create the TTS
        myTTS = new TextToSpeech(this, this);
        myTTS.setPitch((float) .9);/////delete
        myTTS.setSpeechRate((float) 0.75);///delete maybe
        // }
        // else {
        // //no data - install it now
        // Intent installTTSIntent = new Intent();
        // installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
        // startActivity(installTTSIntent);
        // }
      }
    if (requestCode == checka && resultCode == RESULT_OK){
        ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
        lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
        if(results.contains("hey") || results.contains("a") || results.contains("ay") || results.contains("add")|| results.contains("day")||results.contains("A")){
            counter_score ++;
            image1.setVisibility(View.INVISIBLE);
            ourSong = MediaPlayer.create(Section1.this, R.raw.rightsound2);
            ourSong.start();
            AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
            dialogBuilder.setTitle("Great");
            dialogBuilder.setMessage("some msg");
            dialogBuilder.setIcon(R.drawable.ic_mark);
            dialogBuilder.setButton("Continue", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            dialogBuilder.show();
            Thread timer = new Thread(){
                public void run(){
                    try{
                     sleep(2500);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    } finally {
                        if(counter_score == 3){

                            Bundle basket = new Bundle();
                            basket.putInt("key", counter_score);
                            Intent nextAct = new Intent(Section1.this, Result_Section1.class);
                            nextAct.putExtras(basket);
                            startActivity(nextAct);
                            finish();
                        }
                    }
                }
            };
            timer.start();

        }else{

            lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
            counter_score +=0;
            ourSong = MediaPlayer.create(Section1.this, R.raw.wrongsound);
            ourSong.start();
            AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
            dialogBuilder.setTitle("Oops");
            dialogBuilder.setMessage("Wrong msg");
            dialogBuilder.setIcon(R.drawable.ic_wrong);
            dialogBuilder.setButton("Try again", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            dialogBuilder.show();
            Thread timer = new Thread(){
                public void run(){
                    try{
                     sleep(4000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    } finally {



                    }
                }
            };
            timer.start();
        }



    }

if (requestCode == checkb && resultCode == RESULT_OK){
        ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
        lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
        if(results.contains("b") || results.contains("be") || results.contains("boob")|| results.contains("dude")|| results.contains("B")){

            counter_score ++;
            image2.setVisibility(View.INVISIBLE);
            ourSong = MediaPlayer.create(Section1.this, R.raw.rightsound2);
            ourSong.start();
            AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
            dialogBuilder.setTitle("Great");
            dialogBuilder.setMessage("some msg");
            dialogBuilder.setIcon(R.drawable.ic_mark);
            dialogBuilder.setButton("Continue", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            dialogBuilder.show();
            Thread timer = new Thread(){
                public void run(){
                    try{
                     sleep(2500);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    } finally {
                        if(counter_score == 3){

                            Bundle basket = new Bundle();
                            basket.putInt("key", counter_score);
                            Intent nextAct = new Intent(Section1.this, Result_Section1.class);
                            nextAct.putExtras(basket);
                            startActivity(nextAct);
                            finish();
                        }
                    }
                }
            };
            timer.start();

        }else{

            lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
            counter_score +=0;
            ourSong = MediaPlayer.create(Section1.this, R.raw.wrongsound);
            ourSong.start();
            AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
            dialogBuilder.setTitle("Oops");
            dialogBuilder.setMessage("Wrong msg");
            dialogBuilder.setIcon(R.drawable.ic_wrong);
            dialogBuilder.setButton("Try again", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            dialogBuilder.show();
            Thread timer = new Thread(){
                public void run(){
                    try{
                     sleep(4000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    } finally {



                    }
                }
            };
            timer.start();
        }



    }
if (requestCode == checkc && resultCode == RESULT_OK){
        ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
        lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
        if(results.contains("c") || results.contains("see") || results.contains("sea")|| results.contains("C")){
            counter_score ++;
            image3.setVisibility(View.INVISIBLE);
            ourSong = MediaPlayer.create(Section1.this, R.raw.rightsound2);
            ourSong.start();
            AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
            dialogBuilder.setTitle("Great");
            dialogBuilder.setMessage("some msg");
            dialogBuilder.setIcon(R.drawable.ic_mark);
            dialogBuilder.setButton("Continue", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            dialogBuilder.show();
            Thread timer = new Thread(){
                public void run(){
                    try{
                     sleep(2500);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    } finally {
                        if(counter_score == 3){

                            Bundle basket = new Bundle();
                            basket.putInt("key", counter_score);
                            Intent nextAct = new Intent(Section1.this, Result_Section1.class);
                            nextAct.putExtras(basket);
                            startActivity(nextAct);
                            finish();
                        }
                    }
                }
            };
            timer.start();

        }else{

            lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
            counter_score +=0;
            ourSong = MediaPlayer.create(Section1.this, R.raw.wrongsound);
            ourSong.start();
            AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
            dialogBuilder.setTitle("Oops");
            dialogBuilder.setMessage("Wrong msg");
            dialogBuilder.setIcon(R.drawable.ic_wrong);
            dialogBuilder.setButton("Try again", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            dialogBuilder.show();
            Thread timer = new Thread(){
                public void run(){
                    try{
                     sleep(4000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    } finally {



                    }
                }
            };
            timer.start();
        }



    }

super.onActivityResult(requestCode, resultCode, data);



}
    @Override
public void onInit(int status) {
    // check for successful instantiation
    // if (initStatus == TextToSpeech.SUCCESS) {
    // if(myTTS.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE)
    ///myTTS.setLanguage(Locale.US);

    // }
    // else if (initStatus == TextToSpeech.ERROR) {
    // Toast.makeText(this, "Sorry! Text To Speech failed...",
    // Toast.LENGTH_LONG).show();
    // }
}


@Override
protected void onDestroy() {
// TODO Auto-generated method stub
if (myTTS !=null){
    myTTS.stop();
    myTTS.shutdown();


}
super.onDestroy();
}



public void onBackPressed() {
finish();
}

}

I would post Section2.java, Section3.java, but there are only 4 things in the code that change.

1-The xml layout, which is itself an exact copy.

setContentView(R.layout.section1);//changes to setContentView(R.layout.section2),setContentView(R.layout.section2) accordingly

2-The accepted result as right answer of what is spoken.

if(results.contains("hey") || results.contains("a") || results.contains("ay") || results.contains("add")|| results.contains("day")||results.contains("A")){//to whatever the correct answer is for that class

3-The amount questions that need to be right to move to the next activity

if(counter_score == 3){

4-The activity where my bundle is being sent

Intent nextAct = new Intent(Section1.this, Result_Section1.class);

Im aware I can build a Global class for variables.

So finally my questions.

As I read here, I can not build a Global Class for say the AlertDialog's, because if I understand correctly dialogs require a Context and thats part of the View class.

Q1.Could I build a public class MyAlertDialogs extends View { to hold my dialogs?

As I read here, Im aware I can build a Global class to handle OnclickListener.

Q2.Can I have the the SpeechRecognizer Intent or the TextToSpeech Intent on that global class?

Community
  • 1
  • 1

1 Answers1

0

Answer for Q1. Pass the context of your view class to the dialog class when you create it's object. Use the constructor like

public DialogClass {
     final Context mContext;

     DialogClass(Context context) {
         mContext = context;
     }
}

and create it's object while passing the context from the view class.

WarrenFaith
  • 57,492
  • 25
  • 134
  • 150
Vaibhav Ajay Gupta
  • 463
  • 2
  • 4
  • 18
  • thanks for the taking the time, I'll give that a try – user3246849 Mar 12 '14 at 04:47
  • 1
    Could you please provide code that at least matches the common java code styles? Class names and constructors should begin with uppercase! (I edited your code for you, next time do it yourself, please) – WarrenFaith Mar 13 '14 at 15:27
  • I was not able to implement your solution, Im sure its correct, Im just to limited in my understanding to implement it.I ended up using this https://github.com/sherifelkhatib/Super-Dialogs, and although this sample gave me abetter idea, when I came back to try to implement your solution I kept running into issues with the AlertDialog - `The constructor AlertDialog.Builder(DialogClass) is undefined` Im probably better off starting with trying to display a view from another class to get a better understanding of how this works, then come back to this…Anywho, thnx again! – user3246849 Mar 13 '14 at 21:08