Showing a message without closing actual dialog in Android - java

I've to do a pair of fixes to an Android app although I don't really know about Android, but I'm getting problems in something that I don't think should be that difficult, I just want that when an OK button is pressed and some conditions haven't been fulfilled it displays a message and keeps on the same screen until data is correct or the user cancels, but I've tried it for some time and whatever I try it always displays the message and after that a white screen appears, even trying to search for examples on the internet.
This is my code:
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
LinearLayout layout = new LinearLayout(this);
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(parms);
layout.setGravity(Gravity.CLIP_VERTICAL);
layout.setPadding(2, 2, 2, 2);
TextView tv = new TextView(this);
tv.setText("Es necesario rellenar los datos solicitados a continuación para poder realizar su primer canje");
tv.setPadding(40, 40, 40, 40);
tv.setGravity(Gravity.CENTER);
tv.setTextSize(20);
EditText et = new EditText(this);
String etStr = et.getText().toString();
TextView tv1 = new TextView(this);
tv1.setText("Nombre completo");
EditText et2 = new EditText(this);
String etStr2 = et2.getText().toString();
TextView tv2 = new TextView(this);
tv2.setText("Teléfono");
final EditText et3 = new EditText(this);
String etStr3 = et3.getText().toString();
TextView tv3 = new TextView(this);
tv3.setText("Correo electrónico");
LinearLayout.LayoutParams tv1Params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
tv1Params.bottomMargin = 5;
layout.addView(tv1,tv1Params);
layout.addView(et, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
layout.addView(tv2,tv1Params);
layout.addView(et2, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
layout.addView(tv3,tv1Params);
layout.addView(et3, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
alertDialogBuilder.setView(layout);
alertDialogBuilder.setTitle("hola");
// alertDialogBuilder.setMessage("Input Student ID");
alertDialogBuilder.setCustomTitle(tv);
// alertDialogBuilder.setMessage(message);
alertDialogBuilder.setCancelable(true);
// Setting Negative "Cancel" Button
alertDialogBuilder.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
alertDialogBuilder.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
[more code here]
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
matcher = pattern.matcher(et3.getText().toString());
if (matcher.matches())
{
[more code here]
}
else
{
Toast.makeText( contexto, "Por favor, introduzca un e-mail válido", Toast.LENGTH_LONG).show();
}
Hope you can help me with this thing, as I would find pretty annoying to have to learn android from the beginning to make something that I've been able to do in another programming languages in 5 minutes or less without knowing them at all.

Create two instance variables or class varibles like this
private Toast toast;
private boolean stop = false;
Write a method called this
private void showInfiniteToast() {
stop = false;
Thread t = new Thread() {
public void run() {
try {
while (true) {
if (!stop) {
toast.show();
} else {
toast.cancel();
return;
}
sleep(1850);
}
} catch (Exception e) {
Log.e("Infinite Toast", "Error "+ e.getLocalizedMessage());
}
}
};
t.start();
}
Now in the oncreate create the toast and call this method
toast = Toast.makeText(getApplicationContext(), "Test", Toast.LENGTH_LONG);
showInfiniteToast();
Now if you want to change the toast message use this
toast.setText("message");
To stop the toast call any of these
//Call anyone of them
stop = true;
toast.cancel();
To implement your own custom view use this
View mView;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = inflater.inflate(R.layout.mylayout, null);
toast.setView(mView);
Here is the complete file
public class MainActivity extends Activity implements OnClickListener {
Button btnChange, btnStop, btnShow;
private Toast toast;
private boolean stop = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShow = (Button) findViewById(R.id.btnShow);
btnShow.setOnClickListener(this);
btnChange = (Button) findViewById(R.id.btnChange);
btnChange.setOnClickListener(this);
btnStop = (Button) findViewById(R.id.btnStop);
btnStop.setOnClickListener(this);
toast = Toast.makeText(getApplicationContext(), "Test",
Toast.LENGTH_LONG);
showInfiniteToast();
}
private void showInfiniteToast() {
stop = false;
Thread t = new Thread() {
public void run() {
try {
while (true) {
if (!stop) {
toast.show();
} else {
toast.cancel();
return;
}
sleep(1850);
}
} catch (Exception e) {
Log.e("Infinite Toast", "Error "+ e.getLocalizedMessage());
}
}
};
t.start();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnShow:
showInfiniteToast();
break;
case R.id.btnChange:
toast.setText("Added");
break;
case R.id.btnStop:
stop = true;
toast.cancel();
break;
default:
break;
}
}
}

First of all create your layouts using xml and inflate the view like this:
LayoutInflater li = (LayoutInflater) <ACTIVITY_NAME>.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = li.inflate(R.layout.<LAYOUT_NAME>, parent, false);
or
View view = li.inflate(R.layout.<LAYOUT_NAME>, null);
If there is no parent view to attach the inflated view to. Then you can edit objects in your view by doing:
EditText edit = (EditText) findViewById(R.id.edit1);
edit.setText("example");
Doing so just makes your code much more cleaner.
The methods: setPositiveButton, setNeutralButton and setNegativeButton are coded so that when they are pressed, the dialog will close after it has finished executing the code in the listener.
If your Android app is running on the main thread for over 5 seconds then the app will throw an error saying that the app is no longer responding. If you wished to do a long action then you should use an AsyncTask or a Service.
I believe you are wanting to have a progress bar of some kind. I will link you to a
tutorial that will show you how to acheive that side of things. Check here
Hopefully this points you in the right direction.

create a dialogBuilder, and override the negative and positive buttons, and on the click listeners do whatever you want. This will prevent the dialog from closing.
Like this:
Create the builder, intialize it, set it for eg:
builder.setView(view);
builder.setCancelable(false);
override the ondismiss listener, and onshow listener like:
builder.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
if(!errorFlag) {
dialog.dismiss();
}
}
});
builder.setOnShowListener(new OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
Button b = builder.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// write the logic here, and maintain a flag.
// if the flag is true then only dismiss the dialog else show another one
}
Override the negative button also.
show the builder using builder.show()

Related

Using setOnLongClickListener to setText on multiples of buttons

I am trying to change the text on a button after setOnLongClickListener amd there are six buttons to choose from. Currently, regardless of which button I click, the list button is updated with the new text.
I think I have tried everything on this thread:
setonlongclicklistener for several buttons at once
Eventually i hope to save these new button values to shared preferences so they are there when the app is next started.
public class MainActivity extends AppCompatActivity {
private Button btn;
Context context;
final String[] task = new String[1];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
Resources r = getResources();
String pName = getPackageName();
String PREFERENCES_FILE_KEY = "com.example.buttondemo";
String SECURE_PREFS_FILE_KEY = "com.example.buttonnames";
// Declare shared preferences
SharedPreferences sharedPreferences = this.getSharedPreferences(PREFERENCES_FILE_KEY, Context.MODE_PRIVATE);
// get shared preferences for each button and apply the stored name to each button
//String buttonText = sharedPreferences.getString("Value01", "Button_01");
for (int i=1;i<=6;i++) {
String buttonId = "button" + i;
btn = (Button) findViewById(r.getIdentifier(buttonId, "id", pName));
btn.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
task[0] = showAddItemDialog(MainActivity.this, btn);
//sharedPreferences.edit().putString(buttonId, task[0]).apply();
return true;
}
});
}
}
private String showAddItemDialog(Context context, Button btnNew) {
final EditText taskEditText = new EditText(context);
taskEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
final String[] task = new String[1];
AlertDialog dialog = new AlertDialog.Builder(context)
.setTitle("Enter New button value")
.setMessage("Enter New button value:")
.setView(taskEditText)
.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
task[0] = String.valueOf(taskEditText.getText());
btnNew.setText(String.valueOf(taskEditText.getText()));
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
return task[0];
}
}
Thanks.
What's happening is the btn variable is getting reassigned each iteration of your loop. Therefore once the long click listener fires, you are calling showAddItemDialog(this, btn) where btn is holding a reference to whatever it was set to in the last loop iteration (when i = 6).
So the behaviour you're experiencing makes sense. Hopefully this is enough to point you in the right direction.
As a side note, finding views based on dynamic ids that come from r.getIdentifier() might be a bit of a bad design choice and could open up bugs in the future. I would recommend simplifying it to just use R.id.button1, R.id.button2 etc. if possible.

"onRadioButtonClicked" method not working for radio button implemented by "onCreate" method

I tried to populate RadioGroup's RadioButtons on "onCreateMethod" rather than using XML because my purpose is to get it from some sort of database or other business objects model that works with randomicity. RadioButtons are fine, but nothing happens when I click them otherwise when I created in XML activity file, not a log message neither a test toast. By the way, as I said, I need to create the buttons by code, thanks, is my first steps in Android.
My Activity XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/quiz"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
My Code:
public class ListaAlunosActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_alunos);
LinearLayout questoesQuiz = (LinearLayout) findViewById(R.id.quiz);
// Log.d(TAG,"Populate List View; Displaying Data in the List View");
ArrayList<String> dataList = new ArrayList<>(Arrays.asList("sup1", "sup2", "sup3"));
RadioGroup listaDeQuestoes = new RadioGroup(this);
listaDeQuestoes.setOrientation(RadioGroup.VERTICAL);
RadioGroup.LayoutParams lp;
for (int i = 0; i < dataList.size(); i++) {
RadioButton botao = new RadioButton(this);
botao.setText(dataList.get(i));
lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.MATCH_PARENT);
listaDeQuestoes.addView(botao, lp);
}
questoesQuiz.addView(listaDeQuestoes);
}
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
final String TAG = "MyActivity";
Log.v("On clicked working", "clicado");
int id = view.getId();
Toast toast2 = Toast.makeText(this, "toast working", Toast.LENGTH_LONG);
toast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
toast2.show();
}
}
Buttons are okay!
using onClick for finding selected radio button is not the best solution but because you want to use onClick i will show you how to do it with minimum changes to your code. make these three changes to your code:
public class ListaAlunosActivity extends AppCompatActivity
implements View.OnClickListener {// <------ 1. implement OnClickListener
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_alunos);
LinearLayout questoesQuiz = (LinearLayout) findViewById(R.id.quiz);
// Log.d(TAG,"Populate List View; Displaying Data in the List View");
ArrayList<String> dataList = new ArrayList<>(Arrays.asList("sup1", "sup2", "sup3"));
RadioGroup listaDeQuestoes = new RadioGroup(this);
listaDeQuestoes.setOrientation(RadioGroup.VERTICAL);
RadioGroup.LayoutParams lp;
for (int i = 0; i < dataList.size(); i++) {
RadioButton botao = new RadioButton(this);
botao.setOnClickListener(this);// <---------- 2.add this line
botao.setText(dataList.get(i));
lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.MATCH_PARENT);
listaDeQuestoes.addView(botao, lp);
}
questoesQuiz.addView(listaDeQuestoes);
}
#Override
public abstract void onClick (View v){ //<-------- 3. override onClick
boolean checked = ((RadioButton) v).isChecked();
final String TAG = "MyActivity";
Log.v("On clicked working", "clicado");
int id = v.getId();// your radio buttons have no id thus use title instead of id:
String title = ((RadioButton) v).getText();
Toast toast2 = Toast.makeText(this, "toast working", Toast.LENGTH_LONG);
toast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
toast2.show();
}
If you look keenly, your onRadioButtonClicked is just a method that is never called. Now what you have to do is make the Activity implement RadioGroup.OnCheckedChangeListener. And in onCheckedChanged method, do the Toast and it will work. Here is the code.
public class ListaAlunosActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_alnus);
LinearLayout questoesQuiz = (LinearLayout) findViewById(R.id.quiz);
// Log.d(TAG,"Populate List View; Displaying Data in the List View");
ArrayList<String> dataList = new ArrayList<>(Arrays.asList("sup1", "sup2", "sup3"));
RadioGroup listaDeQuestoes = new RadioGroup(this);
listaDeQuestoes.setOrientation(RadioGroup.VERTICAL);
RadioGroup.LayoutParams lp;
for (int i = 0; i < dataList.size(); i++) {
RadioButton botao = new RadioButton(this);
botao.setId(i);
botao.setText(dataList.get(i));
lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.MATCH_PARENT);
listaDeQuestoes.addView(botao, lp);
}
questoesQuiz.addView(listaDeQuestoes);
listaDeQuestoes.setOnCheckedChangeListener(this);
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Toast toast2 = Toast.makeText(this, "toast working for id "+ checkedId, Toast.LENGTH_LONG);
toast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
toast2.show();
}
}
I did this and it works perfectly
Not completely sure what your code is meant to do, but I would use a setOnCheckedChangeListener rather than onClick.
Something like this
listaDeQuestoes.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
final String TAG = "MyActivity"; // not used?
Log.v("On clicked working", "clicado");
// Note checkedId is +1 when accessing the arraylist so needs to be decremented to get a list item
Toast toast2 = Toast.makeText(ListaAlunosActivity.this, "toast working clicked (" + checkedId + ") [" + dataList.get(checkedId - 1) + "]", Toast.LENGTH_LONG);
toast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
toast2.show();
}
});
The Toast is working and I showed how you can determine which button was clicked and how to access your data array with it, if desired.
The main reason for this, as BAHMAN points out, is that you haven't set any listener. HOWEVER. Setting a listener on the buttons themselves is not a very good idea. It is better to set it on the radio group. And it's better to have your layout elements in your layout file. This makes them easier to modify and understand.
Another thing that is personal preference: I prefer implementing the listener as an anonymous class where it is set. The solutions where the class implements the listener make it harder to read for large classes where it can be annoying to go looking for listeners. I might make an exception if the listener is very complex or if it something that might be used more than once.
I also cleaned up the code a bit. Comments added where I did
Anyway, here's how I would write this code:
Main Activity Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/quiz"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RadioGroup
android:id="#+id/radio_button_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Main Activity Code:
public class ListaAlunosActivity extends AppCompatActivity {
// I put your tag at the top of the class so it's more useful
public static final String TAG = "ListaAlunosActivity";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_alunos);
// You didn't really need an arraylist here for this static content.
// I just made it an array
String[] dataList = {"sup1", "sup2", "sup3"};
// Get this from your layout instead of adding it manually.
// It's a cleaner way to set up the layout that makes the
// code more maintainable
RadioGroup listaDeQuestoes = findViewById(R.id.radio_button_list);
// I changed this to a for each loop because it's a little cleaner
for (String name : dataList){
RadioButton botao = new RadioButton(this);
botao.setText(name);
listaDeQuestoes.addView(botao);
}
// This is the code that will react to the new radio button being selected
listaDeQuestoes.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// Either way we do it, we need to grab the view to get the name
RadioButton buttonView = group.findViewById(checkedId);
// You can use this code to get the index if you need it
int checkedIndex = group.indexOfChild(buttonView);
// And you can use either of these methods to get the name:
String buttonNameFromView = buttonView.getText().toString();
String buttonNameFromDataSource = dataList[checkedIndex];
String output = "Button with Id: " + checkedId + " and Name: " + buttonNameFromView + " was clicked";
Log.v(TAG, output);
Toast toast = Toast.makeText(ListaAlunosActivity.this, output, Toast.LENGTH_LONG);
// I set gravity to just center here. This is the same as center_vertical | center_horizontal. Personally, I wouldn't set it at all.
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
}
}

How to get data from many EditTexts when Its added in layout programmatically in android

I'm adding EditText in linear layout and it gives a view like that in image.
I'm getting this view by using this code.
public class SearchRecipe extends AppCompatActivity {
LinearLayout parentLayout;
ImageButton searchRecipe;
private int EDITTEXT_ID = 1;
private List<EditText> editTextList;
EditText editTextItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_recipe);
setActionBar();
init();
searchRecipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editTextItem = (EditText) parentLayout.findViewById(EDITTEXT_ID);
for (int i = 0; i < editTextList.size(); i++) {
Log.e("All Values=", editTextList.get(i).getText().toString());
Toast.makeText(SearchRecipe.this, editTextItem.getText().toString() + " ", Toast.LENGTH_SHORT).show();
}
}
});
}
public void init() {
parentLayout = (LinearLayout) findViewById(R.id.parent_layout); //make sure you have set vertical orientation attribute on your xml
searchRecipe = (ImageButton) findViewById(R.id.search_button);
editTextList = new ArrayList<EditText>();
TextView addMoreText = new TextView(this);
addMoreText.setText("Add More Ingredients");
addMoreText.setGravity(Gravity.CENTER);
addMoreText.setPadding(20, 20, 20, 20);
addMoreText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.add, 0);
addMoreText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editTextItem = new EditText(SearchRecipe.this);
editTextItem.setId(EDITTEXT_ID);
editTextList.add(editTextItem);
EDITTEXT_ID++;
editTextItem.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.cross, 0);
editTextItem.setPadding(20, 20, 20, 20);
editTextItem.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
parentLayout.removeView(editTextItem);
return true;
}
});
parentLayout.addView(editTextItem, 0);
}
});
parentLayout.addView(addMoreText);
}
Now the only problem I'm facing is that. I'm not getting the text from edittext properly. Let me Explain what I want to do.
Click on Add More TextView will add one more edit text.
After adding all edittexts I will click on Search button.
By clicking search button will get the data from edittexs and save in arraylist. I tried a lot but can't do this properly. will you please help me to do this thing ? I'm stuck in from many days.
if you are createing edit text run time only for this purpose then there is no need of below tow lines
editTextItem.setId(EDITTEXT_ID);
EDITTEXT_ID++;
To retrive data from each edit box follow below things
for (EditText editText : editTextList) {
/* now you can get the value from Edit-text and save in the ArrayList
or you can append it in same string*/
yourArraList.add(editText.getText().toString()));
}
Get the editext from your list editTextList
String data = editTextList.get(index).getText().toString();
Add check for editTextList should not be null or empty.
You can iterate over list using for-each loop
for (EditText editText : editTextList) {
// now you can get the value from Edit-text and save in the ArrayList
yourArraList.add(editText.getText().toString()));
}
you can do like below if view inside fragment.
public static String getText(final Activity activity) {
final StringBuilder stringBuilder=new StringBuilder();
LinearLayout scrollViewlinerLayout = (LinearLayout) activity.findViewById(R.id.linearLayoutForm);
ArrayList<String> msg = new ArrayList<String>();
for (int i = 0; i < scrollViewlinerLayout.getChildCount(); i++)
{
LinearLayout innerLayout = (LinearLayout) scrollViewlinerLayout.getChildAt(i);
EditText editText = (EditText) innerLayout.findViewById(R.id.meeting_dialog_et);
msg.add(editText.getText().toString());
}
for (int j=0;j<msg.size();j++)
{
stringBuilder.append(msg.get(j)).append(";");
}
Toast t = Toast.makeText(activity.getApplicationContext(), stringBuilder.toString(), Toast.LENGTH_SHORT);
t.show();
return stringBuilder.toString();
}
there is another way is make arraylist Edittexes and add each edittext when it added to layout. then you can get like below:
for (int i = 0; i < Edittexes.size(); i++) {
if (Edittexes.get(i) == view)
{
String text=Edittexes.get(i).getText();
}
}

Speech Recognizer in haddler seems to open the activity again every time

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
returnedText = (TextView) findViewById(R.id.textView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
toggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
progressBar.setVisibility(View.INVISIBLE);
speech = SpeechRecognizer.createSpeechRecognizer(this);
speech.setRecognitionListener(this);
recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE,
"en");
recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
progressBar.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
speech.startListening(recognizerIntent);
} else {
progressBar.setIndeterminate(false);
progressBar.setVisibility(View.INVISIBLE);
speech.stopListening();
}
}
});
ttsManager = new TTSManager();
ttsManager.init(this);
Pause = (Button) findViewById(R.id.pause);
Stop = (Button) findViewById(R.id.stop);
Resume = (Button) findViewById(R.id.resume);
Pause.setVisibility(View.INVISIBLE);
Resume.setVisibility(View.INVISIBLE);
Stop.setVisibility(View.INVISIBLE);
// -------------------------------------
//----------------------------------------
handler = new android.os.Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
Log.e("TAG", sbprint);
if(sbprint.contains("ello")){
progressBar.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
speech.startListening(recognizerIntent);
toggleButton.setChecked(true);
}
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
};
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
//--------------------------------------
}
I am trying to activate speech like I am pressing the toogleButton, and i copyed the code from the toogleButton to the handler.
Everything is ok, i mean if i click the toogleButton it works, but when i recive the message that cointains "ello" in the handler, the speechRecognizer starts but closes very quickly, this happens every time i send that message.
Also it seems like a new activity i created when i trigger the handler with that message, but the same functions in the toogleButton work.
Any ideea how can i make this work ? I want functionality in the toogleButton, but in the handler too, so i can trigger speechRecognition with a message or something inside handler.
I think the problem is that you're changing the toggleButton's state inside the Handler
toggleButton.setChecked(true);
And this will trigger the OnCheckedChangeListener. But this should start the speech recognition again (because you set it to true), not stop it.
Try to call only toggleButton.setChecked(true); in your Handler, see if that resolves the problem, for example:
if(sbprint.contains("ello")){
toggleButton.setChecked(true);
}

Android activity unresponsive until back button is pressed

Below is the oncreate to my activity. My issue is that when the activity is started it is completely unresponsive until I press the back button. Once I press the back button it works perfectly.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_packs);
count = 0;
Bundle extras = getIntent().getExtras();
if(extras != null || !equals("")){
name = extras.getString("name");
}
else{name="PackActivity";}
//getActionBar().setTitle(name);
ActionBar actionBar = getActionBar();
//actionBar.setBackgroundDrawable(R.drawable.navigation_bar_colour_image);
//actionBar.setHomeButtonEnabled(true);
actionBar.setTitle(name);
actionBar.setDisplayHomeAsUpEnabled(false);
//actionBar.hide();
database = new DataObjectDataSource(this.getApplicationContext());
//load all the packs from the DB
packs = loadPacks();
//make the request for GetPacks
sortArrayById();
if(isOnline(this)) {
HTTPRequest.getHTTPRequest(HTTPRequest.getPacksURL, this);
}
else{
dialog("No internet connection available","their is limited functionality available in offline mode",1);
}
gridView = (GridView) findViewById(R.id.packGrid);
adapter = new PackGridAdapter(this, getApplicationContext(), packs);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(this);
System.out.println(" pack_ids ");
}
I have included the dialog function as the unresponsiveness comes after it have been dismissed.
public boolean dialog(String mes,String message,int type){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Add the buttons
if(type==2){
builder.setMessage(message)
.setTitle(mes);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
}
// Create the AlertDialog
final AlertDialog dialog = builder.create();
dialog.show();
if(type==2){
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
dialog.dismiss();
// when the task active then close the dialog
t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report
}
}, 5000);
}
return true;
}
2 Things:
1st confirm that your ActionBar code is working (comment the actionbar part to make sure that is not culprit here) to see if the activity is responsive or not
If the 1st doesn't work, and even after commenting ActionBar activity is unresponsive .. then
2nd comment these lines:
if(isOnline(this)) {
HTTPRequest.getHTTPRequest(HTTPRequest.getPacksURL, this);
}
else{
dialog("No internet connection available","their is limited functionality available in offline mode",1);
}
I suspect you're doing some network operation on your UI Thread, that could be the cause of Activity not Responding or it must have something to do with the dialog method you're using. If you show that method code, it could lead further to diagnose.

Categories