The code below is used to convert speech to text on an android app. This code works when the speech button is pressed and whatever you say is transferred into text.
When the speech function closes, the the text is showing.
If you hit the speech button again, the previous text is cleared and the new text shows on the page. What i want to do is everytime i click the speak button, i want to show the word on the page.. then if i click the speak button again, i want the next word to appear under the first word in a list format.
i am looking to use listview but am struggling. here is the original code and the code i am trying to write to make it a listview. can anyone assist?
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/textView1"
android:layout_toLeftOf="#+id/textView1"
android:gravity="center"
android:orientation="vertical" >
<ImageButton
android:id="#+id/btnSpeak"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:contentDescription="#string/speak"
android:src="#android:drawable/ic_btn_speak_now" />
<TextView
android:id="#+id/txtText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Code:
import java.util.ArrayList;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
protected static final int RESULT_SPEECH = 1;
private ImageButton btnSpeak;
private TextView txtText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtText = (TextView) findViewById(R.id.txtText);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"Ops! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtText.setText(text.get(0));
}
break;
}
}
}
}
In your onActivityResult, you are overriding your TextView with the first word only(index 0).
You must iterate through the String array list like so:
String words = "";
for ( String word : text ) {
words += " " + word;
}
txtText.setText(words);
And here's a nice article to help you implement your ListView:
ListView tutorial
So now when you figured that out you add the words value in the listview.
Hope this helps,
Cheers
Related
What I'm facing is that whenever I press the button to save data to check if the fields is filled up and if it is then it will pass data to back4app but nothing happens even. The Android monitor/Run doesnt even show that the button is being pressed nor the Logcat.
I have a log in activity, register activity, and the main activity. After Logging in it will take you to the main activity which is empty for now but you need to use the navigation bar to take you to this activity and even the fields are filled or not the button does not respond at all. I put a toast to make sure that the button works but the toast doesnt show.
The code below I just copied in the registration form which is the same concept, fill the form test if theres something in there, if not then message will appear then it will send data to back4app. But the button in this problem doesnt work.
This is the button command
package com.example.back4app.userregistrationexample.Classes;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.view.View.OnClickListener;
import com.example.back4app.userregistrationexample.R;
import com.parse.Parse;
import com.parse.ParseObject;
import com.parse.ParseUser;
public class Purchases extends AppCompatActivity {
private EditText establishmentView;
private EditText particularsView;
private EditText amountView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.app_bar_purchases);
establishmentView = (EditText) findViewById(R.id.Edt_Establishment);
particularsView = (EditText) findViewById(R.id.Edt_Particular);
amountView = (EditText) findViewById(R.id.Edt_purchasesnumber);
final Button save = (Button) findViewById(R.id.btn_purchasessave);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
boolean validationError = false;
StringBuilder validationErrorMessage = new StringBuilder("Please, insert ");
if (isEmpty(establishmentView)) {
validationError = true;
validationErrorMessage.append("an Establisment");
}
if (isEmpty(particularsView)) {
if (validationError) {
validationErrorMessage.append(" and ");
}
validationError = true;
validationErrorMessage.append("a Particular");
}
if (isEmpty(amountView)) {
if (validationError) {
validationErrorMessage.append(" and ");
}
validationError = true;
validationErrorMessage.append("a Amount");
}
validationErrorMessage.append(".");
if (validationError) {
Toast.makeText(Purchases.this, validationErrorMessage.toString(), Toast.LENGTH_LONG).show();
return;
}
final ProgressDialog dlg = new ProgressDialog(Purchases.this);
dlg.setTitle("Please, wait a moment.");
dlg.setMessage("Signing up...");
dlg.show();
Toast.makeText(getApplicationContext(),"Data Saved",Toast.LENGTH_SHORT).show();
}
});
}
private boolean isEmpty(EditText text) {
if (text.getText().toString().trim().length() > 0) {
return false;
} else {
return true;
}
}
private boolean isMatching(EditText text1, EditText text2){
if(text1.getText().toString().equals(text2.getText().toString())){
return true;
}
else{
return false;
}
}
private void alertDisplayer(String title,String message){
AlertDialog.Builder builder = new AlertDialog.Builder(Purchases.this)
.setTitle(title)
.setMessage(message)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Intent intent = new Intent(Purchases.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
ParseUser.logOut();
}
});
AlertDialog ok = builder.create();
ok.show();
}
}
Edit: This is the app_bar_purchases.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id="#+id/txt_puchasesbal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:text="Balance" />
<EditText
android:id="#+id/Edt_Establishment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:ems="10"
android:hint="Establishment"
android:inputType="textPersonName" />
<EditText
android:id="#+id/Edt_Particular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="130dp"
android:ems="10"
android:hint="Particulars"
android:inputType="textPersonName" />
<EditText
android:id="#+id/Edt_purchasesnumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="197dp"
android:ems="10"
android:hint="Amount"
android:inputType="number" />
<Button
android:id="#+id/btn_purchasessave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="178dp"
android:text="Save" />
</RelativeLayout>
Heres what happen when I try to debug it and put break in boolean same thing happens when I put the break in button save it doesnt show anything on the Debug no errors or anything
EDIT I have pasted the right xml file
EDIT Does having RelativeLayout makes the button not respond?
EDIT I have pasted the whole java class
EDIT I also tried deleting everything else on the onClick except for
Toast.makeText(getApplicationContext(),"Data Saved",Toast.LENGTH_SHORT).show(); just to see if the button itself works but it didn't even show the toast
Please check your button id in xml file it's btn_addbalance
then check your id in java file it's btn_purchasessave
please correct this check below code
your line
final Button save = findViewById(R.id.btn_purchasessave);
replace with
final Button save = findViewById(R.id.btn_addbalance);
it will help to you
I took reference of a SO question,
Try using this :
save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getBaseContext(), "clicked", Toast.LENGTH_LONG).show();
}
});
And import this
import android.view.View.OnClickListener;
EDIT
Casting most of the android views is reduntant now but it can be the problem, Try to caste the button like this :
final Button save = (Button) findViewById(R.id.btn_purchasessave);
and try your code.
EDIT 2
Try using save.setOnClickListener(this) like this,
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText establishmentView;
private EditText particularsView;
private EditText amountView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
establishmentView = (EditText) findViewById(R.id.Edt_Establishment);
particularsView = (EditText) findViewById(R.id.Edt_Particular);
amountView = (EditText) findViewById(R.id.Edt_purchasesnumber);
final Button save = (Button) findViewById(R.id.btn_purchasessave);
save.setOnClickListener(this);
}
#Override
public void onClick(View v) {
//do things here
}
I'm getting four errors all with this message: cannot be resolved or is not a field
The errors are in two different .java files
StartScreen.java.text
tv = (TextView) findViewById(R.id.startscreen); (startscreen underlined in red)
Button startButton = (Button) findViewById(R.id.play_game); (play_game underlined in red)
I creaded a textview called startscreen and a button called startButton inside game.xml
PlayGame.java
tv2 = (TextView) findViewById(R.id.game_text); (game_text underlined in red)
Button startButton = (Button) findViewById(R.id.end_game); (end_game underlined in red)
I creaded a textview called game_text and a button called end_game inside game.xml
StartScreen.java
package com.example.startscreenapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class StartScreen extends Activity {
private static final int PLAY_GAME = 1010;
private TextView tv;
private int meaningOfLife = 42;
private String userName = "Douglas Adams";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.startscreen.text);
//Display initial values
tv.setText(userName + ":" + meaningOfLife);
//Set up button listener
Button startButton = (Button) findViewById(R.id.play_game);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startGame();
}
});
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == PLAY_GAME && resultCode == RESULT_OK) {
meaningOfLife = data.getExtras().getInt("returnInt");
userName = data.getExtras().getString("returnStr");
//Show it has changed
tv.setText(userName + ":" + meaningOfLife);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void startGame() {
Intent launchGame = new Intent(this, PlayGame.class);
//passing information to launched activity
launchGame.putExtra("meaningOfLife", meaningOfLife);
launchGame.putExtra("userName", userName);
startActivityForResult(launchGame, PLAY_GAME);
}
}
PlayGame.java
package com.example.startscreenapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class PlayGame extends Activity {
private TextView tv2;
int answer;
String author;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
tv2 = (TextView) findViewById(R.id.game_text);
//reading information passed to this activity
//Get the intent that started this activity
Intent i = getIntent();
//returns -1 if not initialized by calling activity
answer = i.getIntExtra("meaningOfLife", -1);
//returns [] if not initialized by calling activity
author = i.getStringExtra("userName");
tv2.setText(author + ":" + answer);
//Change values for an example of return
answer = answer - 41;
author = author + " Jr.";
//Set up button listener
Button startButton = (Button) findViewById(R.id.end_game);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Return information to calling activity
Intent i = getIntent();
i.putExtra("returnInt", answer);
i.putExtra("returnStr", author);
setResult(RESULT_OK, i);
finish();
}
});
}}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="#+id/startscreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="115dp"
android:layout_marginTop="164dp"
android:text="TextView" />
<Button
android:id="#+id/play_game"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/startscreen"
android:layout_below="#+id/startscreen"
android:layout_marginTop="64dp"
android:text="Button" />
</RelativeLayout>
game.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/game_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="#+id/end_game"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
Your textview id on your xml is startscreen
Instead of v = (TextView) findViewById(R.id.startscreen.text); just remove the .text part
in startscreen.java you have tv = (TextView) findViewById(R.id.startscreen.text); and in your activity_main.xml you have android:id="#+id/startscreen".
what you should do :
1-is removing the .text from tv = (TextView) findViewById(R.id.startscreen.text);
2- clean and build you project again. (if this didn't work , close and open eclipse again.
i suggest to use ctrl + space in completing you statement, that would help in reducing error and give suggestion.
I was making a form on android. While checking for the text fields, I used isEmpty() method to check if there was any text. The problem is, it is always returning true. I'm unable to figure out where I went wrong. Thanks in advance! :)
If any other file is needed, please comment here, I'll add it ASAP.
AddQuestionActivity.java
import static chipset.quizzy.questionadder.resources.Constants.KEY_QUESTION;
import static chipset.quizzy.questionadder.resources.Constants.KEY_QUESTION_ANSWER;
import static chipset.quizzy.questionadder.resources.Constants.KEY_QUESTION_HINT;
import static chipset.quizzy.questionadder.resources.Constants.KEY_QUESTION_NUMBER;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import chipset.quizzy.questionadder.R;
import chipset.quizzy.questionadder.resources.Functions;
import chipset.quizzy.questionadder.resources.ShowImageActivity;
public class AddQuestionActivity extends Activity {
Functions functions = new Functions();
EditText addQuestionNumber, addQuestion, addQuestionAnswer,
addQuestionHint;
Button addQuestionImage, addQuestionAdd;
ImageView addQuestionImageView;
private static int RESULT_LOAD_IMAGE = 1;
String picturePath, question, questionNumber, questionAnswer, questionHint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_question);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
addQuestionNumber = (EditText) findViewById(R.id.addQuestionNumber);
addQuestion = (EditText) findViewById(R.id.addQuestion);
addQuestionAnswer = (EditText) findViewById(R.id.addQuestionAnswer);
addQuestionHint = (EditText) findViewById(R.id.addQuestionHint);
addQuestionImage = (Button) findViewById(R.id.addQuestionImage);
addQuestionImageView = (ImageView) findViewById(R.id.addQuestionImageView);
addQuestionAdd = (Button) findViewById(R.id.addQuestionAdd);
questionNumber = addQuestionNumber.getText().toString().trim();
question = addQuestion.getText().toString().trim();
questionAnswer = addQuestionAnswer.getText().toString().trim();
questionHint = addQuestionHint.getText().toString().trim();
addQuestionAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
functions.hideKeyboard(getApplicationContext(),
getCurrentFocus());
if (functions.isConnected(getApplicationContext())) {
if (questionNumber.isEmpty() || question.isEmpty()
|| questionAnswer.isEmpty()
|| questionHint.isEmpty()) {
Toast.makeText(getApplicationContext(),
"Enter All Fields", Toast.LENGTH_SHORT).show();
Log.i(KEY_QUESTION, String.valueOf(question.isEmpty()));
Log.i(KEY_QUESTION_ANSWER,
String.valueOf(questionAnswer.isEmpty()));
Log.i(KEY_QUESTION_HINT,
String.valueOf(questionHint.isEmpty()));
Log.i(KEY_QUESTION_NUMBER,
String.valueOf(questionNumber.isEmpty()));
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(
AddQuestionActivity.this);
builder.setTitle("Information");
builder.setMessage(KEY_QUESTION_NUMBER + " : "
+ questionNumber + "\n" + KEY_QUESTION + " : "
+ question + "\n" + KEY_QUESTION_ANSWER + " : "
+ questionAnswer + "\n" + KEY_QUESTION_HINT
+ " : " + questionHint + "\n");
builder.setNeutralButton(android.R.string.ok, null);
builder.create();
builder.show();
}
} else {
Toast.makeText(getApplicationContext(),
"No Internet Connection", Toast.LENGTH_SHORT)
.show();
}
}
});
addQuestionImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent addImage = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(addImage, RESULT_LOAD_IMAGE);
}
});
addQuestionImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent loadBigImage = new Intent(getApplication(),
ShowImageActivity.class);
loadBigImage.putExtra("picturePath", picturePath);
startActivity(loadBigImage);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
addQuestionImageView.setVisibility(View.VISIBLE);
addQuestionImageView.setImageBitmap(BitmapFactory
.decodeFile(picturePath));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_logout) {
functions.logout(getApplication(), getApplicationContext());
} else if (id == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
activity_add_question.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/turquoize" >
<TextView
android:id="#+id/addTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:fontFamily="sans-serif-light"
android:gravity="center_horizontal|center_vertical"
android:text="#string/app_name"
android:textColor="#color/clouds"
android:textSize="30sp" />
<ScrollView
android:id="#+id/boxy"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/addTitle"
android:layout_margin="15dp"
android:background="#color/clouds"
android:orientation="vertical"
android:padding="15dp"
tools:ignore="UselessLeaf" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="#+id/addQuestionNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/qNo"
android:inputType="number" />
<EditText
android:id="#+id/addQuestion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/q"
android:inputType="textMultiLine" />
<EditText
android:id="#+id/addQuestionAnswer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/qAns"
android:inputType="text" />
<EditText
android:id="#+id/addQuestionHint"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/qHint"
android:inputType="text" />
<Button
android:id="#+id/addQuestionImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#drawable/button_click"
android:text="#string/uQImage"
android:textColor="#color/turquoize" />
<ImageView
android:id="#+id/addQuestionImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="15dp"
android:background="#color/black"
android:contentDescription="#string/qImage"
android:visibility="gone" />
</LinearLayout>
</ScrollView>
<Button
android:id="#+id/addQuestionAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_margin="15dp"
android:background="#drawable/button_click"
android:text="#string/addQuestionDo"
android:textColor="#color/turquoize" />
</RelativeLayout>
You need to move this under your Button onClick(...) event
questionNumber = addQuestionNumber.getText().toString().trim();
question = addQuestion.getText().toString().trim();
questionAnswer = addQuestionAnswer.getText().toString().trim();
questionHint = addQuestionHint.getText().toString().trim();
Update
Just like so
addQuestionAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
questionNumber = addQuestionNumber.getText().toString().trim();
question = addQuestion.getText().toString().trim();
questionAnswer = addQuestionAnswer.getText().toString().trim();
questionHint = addQuestionHint.getText().toString().trim();
...........
.............
}
});
It is because, in the onCreate stage itself you are getting the values of the text box and storing it in a variable. Initially the text box would be empty and hence the value would also be empty.
So Modify your onclick Listener code, so that you get the text box value inside the code and then process it. However, also check inside the onclicklistener for empty strings because the user might not have input any value to the textbox. :)
// Edit text instance can be declared in the onCreate
protected void onCreate(Bundle savedInstanceState)
{
....
addQuestionNumber = (EditText) findViewById(R.id.addQuestionNumber);
addQuestion = (EditText) findViewById(R.id.addQuestion);
addQuestionAnswer = (EditText) findViewById(R.id.addQuestionAnswer);
addQuestionHint = (EditText) findViewById(R.id.addQuestionHint);
....
}
// Edit Text value getting should be inside onClick
public void onClick(View v) {
questionNumber = addQuestionNumber.getText().toString().trim();
question = addQuestion.getText().toString().trim();
questionAnswer = addQuestionAnswer.getText().toString().trim();
questionHint = addQuestionHint.getText().toString().trim();
...
}
i am using two activities in my program.In first activity i done coding of voice to text and in second activity i done coding for text to sign langauge i linked it through button.but it doesn't move to another activity.I want this that the textveiw of voice recongnition to be shown on another activity.Please help
fist java code of voice recongnizer
package com.authorwjf.talk2me;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
protected static final int REQUEST_OK = 1;
public static String EXTRA_MESSAGE;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(i, REQUEST_OK);
} catch (Exception e) {
Toast.makeText(this, "Error initializing speech to text engine.", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUEST_OK && resultCode==RESULT_OK) {
ArrayList<String> thingsYouSaid = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
((TextView)findViewById(R.id.text1)).setText(thingsYouSaid.get(0));
}
}
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(MainActivity.this, Second.class);
EditText editText = (EditText) findViewById(R.id.text1);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
this is xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="132dp"
android:text="..." />
<ImageButton
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/text1"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:layout_marginTop="37dp"
android:src="#android:drawable/ic_btn_speak_now" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/text1"
android:layout_alignBottom="#+id/text1"
android:layout_alignLeft="#+id/button1"
android:text="Enter" />
</RelativeLayout>
this is my second activity
package com.authorwjf.talk2me;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
#SuppressLint("NewApi")
public class Second extends Activity {
// View Objects
Button translate;
EditText enterText;
TextView displayText;
ImageView aslImages;
MediaPlayer mP;
Second thisClass;
// Variables for Translation and Display
int phraseIndex = 0; // Keep track of the array indexes
String letters; // Message to be Translated
String display; // Will hold the letters already displayed and show them
String PhraseIndex;
// Array Libraries For Characters and Image References
String letterIndex[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
"x", "y", "z", "hello", "hi", "happy", "sad", "dad", "mom", "school", " " };
int aslPics[] = { R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d,
R.drawable.e, R.drawable.f, R.drawable.g, R.drawable.h,
R.drawable.i, R.drawable.j, R.drawable.k, R.drawable.l,
R.drawable.m, R.drawable.n, R.drawable.o, R.drawable.p,
R.drawable.q, R.drawable.r, R.drawable.s, R.drawable.t,
R.drawable.u, R.drawable.v, R.drawable.w, R.drawable.x,
R.drawable.y, R.drawable.z, R.drawable.hello, R.drawable.happy, R.drawable.sad,
R.drawable.dad, R.drawable.mom, R.drawable.school, R.drawable.space };
#Override
protected void onCreate(Bundle savedInstanceState) {
thisClass = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Show the Up button in the action bar.
setupActionBar();
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
// Attach objects to view objects
translate = (Button) findViewById(R.id.buttonTranslate);
translate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setString(v);
translateLetter();
}
});
enterText = (EditText) findViewById(R.id.textInput);
displayText = (TextView) findViewById(R.id.displayText);
aslImages = (ImageView) findViewById(R.id.aslViewer);
aslImages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
translateLetter();
}
});
// Select all the Text in the enterText Field
enterText.setSelectAllOnFocus(true);
}
// setString Function
// Acts when the Translate Button is pressed
public void setString(View v) {
// Set the text of displayText to'--- '"
displayText.setText(" ----");
// Reset the Phrase Index
phraseIndex = 0;
display = "";
// Get the Input Text
String phrase = enterText.getText().toString();
letters = phrase.toLowerCase();
}
// Displays Image when ImageView Touched.
// Also displays text of letters already translated
public void translateLetter() {
// Checks if letters string is null-displays message
// If the phrase has not been converted to a string
if (letters == null) {
displayText.setText("Press the Translate Button ");
}
// Checks if letters string is null-will not display
// ASL letters until translate Button is pressed
if (letters != null) {
// Fetch the current Character in the phrase
String currentLetter = letters;
// add the letter to the display string
display += currentLetter;
// Search for the corresponding ASL image by Index
for (int i = 0; i < letterIndex.length; i++) {
if (letterIndex[i].contentEquals(currentLetter)) {
// Display the image
aslImages.setImageResource(aslPics[i]);
} // end if
}// end for
// Set the text to display the letters translated
displayText.setText(" " + display);
// Advance to the Next Letter in the Phrase
phraseIndex++;
// Check to see if you reach the end of the phrase
if (phraseIndex > letters.length() - 1) {
// Reset back to the first character
phraseIndex = 0;
display = "";
} // end if
}// end Function translateLetter()
}// end if
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#SuppressLint("NewApi")
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
this is second xml file
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/aslViewer"
android:layout_width="wrap_content"
android:layout_height="300dp"
android:layout_span="2"
android:onClick="translateletter"
android:contentDescription="#string/hand_images"
android:src="#drawable/a" />
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/displayText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="2"
android:text="#string/T_text"/>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="#+id/buttonTranslate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="setString"
android:text="#string/Translate"/>
<EditText
android:id="#+id/textInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/Enter_Text" >
</EditText>
</TableRow>
</TableLayout>
this menifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.authorwjf.talk2me"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.authorwjf.talk2me.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.authorwjf.talk2me.Second"
android:label="#string/title_activity_display_message"
android:parentActivityName="com.authorwjf.talk2me.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.authorwjf.talk2me.MainActivity" />
</activity>
</application>
</manifest>
I think you forgot to call sendMessage(View view) on button click.
add android:onClick="sendMessage" for button2.
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/text1"
android:layout_alignBottom="#+id/text1"
android:layout_alignLeft="#+id/button1"
android:text="Enter"
android:onClick="sendMessage" />
Also, for safty check for button1,
#Override
public void onClick(View v) {
if(v.getId()==R.id.button1){
//Your code
}
}
Inside second activity, I don't think the use of setContentView(textView); is correct. You may get NullPointerException after this line. I think a 'Toast' is enough. Or declare TextView inside xml instead of dynamic creation.
In my app there is two layout first.xml and activity_main.xml. In first Layout there is a button and ListView (Code):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/but"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<ListView
android:id="#+id/listView_items"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
And this Layout is connected with MainActivty:
package com.example.listview2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity {
private ListView lvItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
Button but = (Button) findViewById(R.id.but);
lvItem = (ListView)this.findViewById(R.id.listView_items);
but.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListActivity.class);
startActivity(intent);
}
});
}
}
And then there is second layout activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".ListActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:id="#+id/input">
<EditText
android:id="#+id/editText_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="Add" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_above="#+id/input"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
And this activity is connected to ListActivity:
package com.example.listview2;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class ListActivity extends Activity {
private EditText etInput;
private Button btnAdd;
private ListView lvItem;
private ArrayList<String> itemArrey;
private ArrayAdapter<String> itemAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpView();
}
private void setUpView() {
// TODO Auto-generated method stub
etInput = (EditText)this.findViewById(R.id.editText_input);
btnAdd = (Button)this.findViewById(R.id.button_add);
lvItem = (ListView)this.findViewById(R.id.listView_items);
itemArrey = new ArrayList<String>();
itemArrey.clear();
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
etInput.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_ENTER) {
addItemList();
}
return true;
}
});
}
protected void addItemList() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
if (isInputValid(etInput)) {
itemArrey.add(0,etInput.getText().toString());
etInput.setText("");
itemAdapter.notifyDataSetChanged();
}
}
protected boolean isInputValid(EditText etInput2) {
// TODO Auto-generatd method stub
if (etInput2.getText().toString().trim().length()<1) {
etInput2.setError("Please Enter Item");
return false;
} else {
return true;
}
}
}
The idea of app is very simple. When you start the app, it start MainActivity which is button with ListView. Then you press button to open ListActivity to create new ListView item and this is my question: how can I add to ListView an item from another Activity?
I think you got the logic a little bit messed up there. For example, you are referencing in ListActivity a view that does not exist in its layout:
lvItem = (ListView)this.findViewById(R.id.listView_items);
listView_items is defined in first.xml layout, which means that the lvItem reference in ListActivity will be null.
In any case, here is a better way to design your app:
1- Have your MainActivity act as the central component of the app. Since it is displaying the listView, it should also be responsible of adding/removing items from it. MainActivity would then start ListActivity when a user wants to add a new item to the list.
2- Have your ListActivity act as a simple interface to get the user's information, and retuning it to your MainActivity.
In this case, the solution is to use startActivityForResult(). Here is a small rewrite to make it work:
public class MainActivity extends Activity {
private ListView lvItem;
private ArrayList<String> itemArrey;
private ArrayAdapter<String> itemAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
Button but = (Button) findViewById(R.id.but);
lvItem = (ListView)this.findViewById(R.id.listView_items);
itemArrey = new ArrayList<String>();
itemArrey.clear();
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
lvItem.setAdapter(itemAdapter);
but.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListActivity.class);
startActivityForResult(intent, 1);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
itemArrey.add(0,result);
itemAdapter.notifyDataSetChanged();
}
else if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
}
Now, for ListActivity, you will keep the same code, but add the following in your btnAdd onClickListener:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",etInput);
setResult(RESULT_OK,returnIntent);
finish();
You obviously will want to add input verification and other niceties.
First of all you cannot be doing
lvItem = (ListView)this.findViewById(R.id.listView_items);
you will get Null Pointer exception when lvItem is used as listView_items does not exist in your activity_main layout.
The right way to make your design work is to send "itemArrey" back as bundle extra in the intent you create for setResult.