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.
Related
I am trying to create an app that implements the webview activity whenever you press a button but. Whenever I press it gives me an, unfortunately, message instead of going to it. Everything seems to be right and I put it through the debugger and it gave me the error "E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.time_app, PID: 7599
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.time_app/com.example.time_app.Browser}: android.view.InflateException: Binary XML file line #8: Error inflating class android.webkit.WebView".It says the problem is at line 42 in the browser.java file which is "setContentView(R.layout.activity_browser);".Ive checked all of my lines of code and it all seems right.
Browser.java
package com.example.time_app;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.util.Calendar;
import java.util.Date;
public class Browser extends AppCompatActivity {
//creating the webview variable
WebView wb;
//the end variable takes in the finshed load time(it is a long function because of the number length
long end;
//this is just a varibale to be used for the alert code
final Context context = this;
//this is the total number converted as a string because the alert function does not take in float
String numberAsString;
//the start variable takes in the start load time(it is a long function because of the number length
long start;
//The total variable takes in the substraction of the end and start and is a float variale do to its shorter length
float total;
Date end_Time;
Date start_Time;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browser);
wb = (WebView) findViewById(R.id.webview);
wb.setWebViewClient(new WebViewClient() {
//this function records the load time
public void onPageStarted(WebView view, String url, Bitmap favicon) {
start = System.currentTimeMillis();
start_Time = Calendar.getInstance().getTime();
}
//This function will take in the finished load time and create an alert
#RequiresApi(api = Build.VERSION_CODES.O)
public void onPageFinished(WebView view, String url) {
end = System.currentTimeMillis();
total=end-start;
end_Time = Calendar.getInstance().getTime();
// Total is the difference in milliseconds.
// Dividing by 1000, you convert it to seconds
numberAsString = String.valueOf(total/1000);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Your Load Time");
// set dialog message
alertDialogBuilder
.setMessage("Elapsed Time:"+numberAsString+"\n"+"Start Time:"+start_Time+"\n"+"EndTime:"+end_Time+"\n")
.setCancelable(false)
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
//declaring and setting the web setting variable
WebSettings webSettings = wb.getSettings();
//setting up the javascript to allow thw browser to use javascript
webSettings.setJavaScriptEnabled(true);
//loading url
wb.loadUrl("https://www.aa.com");
}
}
activity_browser.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".Browser">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout >
Manual_menu.java
package com.example.time_app;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class Manual_menu extends AppCompatActivity {
public ListView lv;
public EditText nametxt;
public Button addbtn,updatebtn,deletebtn,submit;
public ArrayList<String> names=new ArrayList<String>();
public ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual_menu);
lv=(ListView) findViewById(R.id.Listview1);
nametxt=(EditText) findViewById(R.id.nametxt);
addbtn=(Button) findViewById(R.id.addbtn);
updatebtn=(Button) findViewById(R.id.updatebtn);
deletebtn=(Button) findViewById(R.id.deletebtn);
submit=(Button) findViewById(R.id.Submit_btn);
//adapter
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice,names);
lv.setAdapter(adapter);
//Set Selected Item
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
nametxt.setText(names.get(i));
}
});
//add button event
addbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
add();
}
});
//update button event
updatebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
update();
}
});
//delete button event
deletebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
delete();
}
});
//clear button event
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivityDecision();
}
});
}
//add
private void add()
{
String name=nametxt.getText().toString();
if(!name.isEmpty() && name.length()>0)
{
//Add
adapter.add(name);
//Refresh
adapter.notifyDataSetChanged();
nametxt.setText("");
Toast.makeText(getApplicationContext(), "Added " +name,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "!!Nothing to Add " +name,Toast.LENGTH_SHORT).show();
}
}
//Update
private void update()
{
String name=nametxt.getText().toString();
int pos=lv.getCheckedItemPosition();
if(!name.isEmpty() && name.length()>0)
{
//Remove Item
adapter.remove(names.get(pos));
//insert
adapter.insert(name,pos);
//refresh
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Updated " +name,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "!!Nothing to Update " ,Toast.LENGTH_SHORT).show();
}
}
//delete
private void delete()
{
int pos=lv.getCheckedItemPosition();
if(pos > -1)
{
//remove
adapter.remove(names.get(pos));
//refresh
adapter.notifyDataSetChanged();
nametxt.setText("");
Toast.makeText(getApplicationContext(), "Deleted " ,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "!!Nothing to delete " ,Toast.LENGTH_SHORT).show();
}
}
//Submit
private void openActivityDecision()
{
Intent intent=new Intent(this, Browser.class);
startActivity(intent);
}
}
activity_manual_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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=".Manual_menu">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="35dp"
android:text="Name :"
/>
<EditText
android:id="#+id/nametxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView1"
android:ems="10"
/>
<ListView
android:id="#+id/Listview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/addbtn"
android:choiceMode="singleChoice"
android:layout_marginTop="20dp">
</ListView>
<Button
android:id="#+id/addbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Listview1"
android:layout_below="#+id/nametxt"
android:layout_marginTop="19dp"
android:text="add" />
<Button
android:id="#+id/updatebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Listview1"
android:layout_toRightOf="#+id/addbtn"
android:layout_marginTop="19dp"
android:text="Update" />
<Button
android:id="#+id/Submit_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Listview1"
android:layout_alignParentRight="true"
android:layout_marginTop="19dp"
android:text="Submit" />
<Button
android:id="#+id/deletebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Listview1"
android:layout_toRightOf="#+id/updatebtn"
android:layout_marginTop="19dp"
android:text="Delete" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.time_app">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".File_menu"></activity>
<activity android:name=".Browser" />
<activity android:name=".file_load" />
<activity android:name=".Manual_menu" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
How do I get it to open up the keyboard on click and change the cursor position when the user clicks within the text? I'm sure it's something simple, but I've tried setting focusable and focusableInTouchMode to true, enabled, textIsSelectable, and nothing has worked. Have also tried using the following in my code:
InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
im.showSoftInput(typeField, 0);
My .xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_chat"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/softGreen"
android:textColor="#color/darkBlue"
android:windowSoftInputMode="stateAlwaysVisible"
tools:context="com.angelwing.buddyup.ChatActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/softBlue"
android:title="Hey"
app:theme="#style/MyTheme"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:hint="Sample Text"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/sendButton"
android:layout_toStartOf="#+id/sendButton"
android:paddingLeft="5dp"
android:id="#+id/typeField"/>
<Button
android:layout_width="50dp"
android:layout_height="wrap_content"
android:src="#drawable/edittext_border"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/typeField"
android:clickable="true"
android:onClick="send"
android:id="#+id/sendButton" />
<ToggleButton
android:textOn="Sun"
android:textOff="Sun"
android:layout_width="#dimen/weekend_toggle_button_width"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:id="#+id/sundayButton" />
<ToggleButton
android:textOn="M"
android:textOff="M"
android:layout_width="#dimen/weekday_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/sundayButton"
android:layout_toRightOf="#+id/sundayButton"
android:layout_toEndOf="#+id/sundayButton"
android:layout_marginRight="-3dp"
android:layout_marginLeft="-3dp"
android:id="#+id/mondayButton" />
<ToggleButton
android:textOn="T"
android:textOff="T"
android:layout_width="#dimen/weekday_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/mondayButton"
android:layout_toRightOf="#+id/mondayButton"
android:layout_toEndOf="#+id/mondayButton"
android:layout_marginRight="-3dp"
android:id="#+id/tuesdayButton" />
<ToggleButton
android:textOn="W"
android:textOff="W"
android:layout_width="#dimen/weekday_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/tuesdayButton"
android:layout_toRightOf="#+id/tuesdayButton"
android:layout_toEndOf="#+id/tuesdayButton"
android:layout_marginRight="-3dp"
android:id="#+id/wednesdayButton" />
<ToggleButton
android:textOn="Th"
android:textOff="Th"
android:layout_width="#dimen/weekday_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/wednesdayButton"
android:layout_toRightOf="#+id/wednesdayButton"
android:layout_toEndOf="#+id/wednesdayButton"
android:layout_marginRight="-3dp"
android:id="#+id/thursdayButton" />
<ToggleButton
android:textOn="F"
android:textOff="F"
android:layout_width="#dimen/weekday_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/thursdayButton"
android:layout_toRightOf="#+id/thursdayButton"
android:layout_toEndOf="#+id/thursdayButton"
android:layout_marginRight="-3dp"
android:id="#+id/fridayButton" />
<ToggleButton
android:textOn="Sat"
android:textOff="Sat"
android:layout_width="#dimen/weekend_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/fridayButton"
android:layout_toRightOf="#+id/fridayButton"
android:layout_toEndOf="#+id/fridayButton"
android:layout_marginRight="3dp"
android:id="#+id/saturdayButton" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_below="#+id/sundayButton"
android:layout_above="#+id/edittext"
android:id="#+id/messageListView"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set"
android:textSize="13dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/toolbar"
android:layout_alignBottom="#+id/saturdayButton"
android:layout_toRightOf="#+id/saturdayButton"
android:layout_toEndOf="#+id/saturdayButton"
android:layout_marginLeft="2dp"
android:layout_marginRight="4dp"
android:id="#+id/setButton" />
</RelativeLayout>
My java file:
package com.angelwing.buddyup;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class ChatActivity extends AppCompatActivity {
Toolbar bar;
SharedPreferences sp;
Button sendButton;
EditText typeField;
String otherUserID;
String buddyID;
String buddyName;
String thisUserName;
String thisUserID;
ChatArrayAdapter adapter;
ArrayList<Message> allMessages;
DatabaseReference convoRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
// sendButton = (Button) findViewById(R.id.sendButton);
// typeField = (EditText) findViewById(R.id.typeField);
//
// View view = this.getCurrentFocus();
// if (view != null)
// {
// InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
// im.showSoftInputFromInputMethod(view.getWindowToken(), 0);
// }
//
// sp = getSharedPreferences("com.angelwing.buddyup", Context.MODE_PRIVATE);
//
// Bundle buddyInfo = getIntent().getExtras();
//
// otherUserID = buddyInfo.getString("otherUserID");
// buddyID = buddyInfo.getString("buddyID");
// buddyName = buddyInfo.getString("buddyName");
//
// thisUserID = buddyInfo.getString("thisUserID");
// thisUserName = buddyInfo.getString("thisUserName");
//
// bar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(bar);
// getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
// getSupportActionBar().setTitle(buddyName);
// Get allMessages from "Conversations" -> buddyID
// allMessages = new ArrayList<>();
// convoRef = FirebaseDatabase.getInstance().getReference("Conversations").child(buddyID);
//
// ListView messagesList = (ListView) findViewById(R.id.messageListView);
// adapter = new ChatArrayAdapter(getApplicationContext(), allMessages);
// messagesList.setAdapter(adapter);
//
// // Add new messages to allMessages
// convoRef.addChildEventListener(new ChildEventListener() {
// #Override
// public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//
// allMessages.add(dataSnapshot.getValue(Message.class));
// adapter.notifyDataSetChanged();
// }
//
// #Override
// public void onChildChanged(DataSnapshot dataSnapshot, String s) {
//
// }
//
// #Override
// public void onChildRemoved(DataSnapshot dataSnapshot) {
//
// }
//
// #Override
// public void onChildMoved(DataSnapshot dataSnapshot, String s) {
//
// }
//
// #Override
// public void onCancelled(DatabaseError databaseError) {
//
// }
// });
}
public void send(View view)
{
Log.i("Clicked", "Yuppers");
// String chat = typeField.getText().toString();
// chat = truncate(chat);
//
// Message newMessage = new Message(thisUserName, chat, thisUserID);
// convoRef.push().setValue(newMessage);
//
// typeField.setText("");
}
public String truncate (String str)
{
return str;
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.mymenu, menu);
return true;
}
public boolean profileClicked (MenuItem item)
{
Intent intent = new Intent(getApplicationContext(), ProfileScreen.class);
startActivity(intent);
return true;
}
public boolean settingsClicked (MenuItem item)
{
return true;
}
public boolean signOutClicked (MenuItem item)
{
sp.edit().putBoolean("signedIn", false).apply();
// auth.signOut();
Intent intent = new Intent(getApplicationContext(), SignInScreen.class);
startActivity(intent);
return true;
}
}
My activity extends AppCompatActivity, if that's important.
Once I click the back button to make the keyboard disappear, I can't make it reappear when I click inside the EditText. Another thing I can't do is move the cursor when I tap inside a String I've already written so if I messed up somewhere, I have to delete text and retype. It's just so frustrating because I have an EditText in another file that works fine and I didn't have to do anything special. The keyboard is opened when I first enter the activity, which is great.
I'm fairly new to Android development so please put things in simple terms, if possible. Thank you so much!
Try this code it may help you solve your problem...
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
public class AndroidExternalFontsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInputFromInputMethod(view.getWindowToken(), 0);
}
}
}
I have a 2 activities with edittexts on them the first activity work fine but the second activity's EditText is focused but I can't edit it nor can I click the button on it.
Also everything works in the emulator but not when I install it on the device. (The keyboard popup also does not come up in the second activity where as it does in the first activity)
Below is the code for the1st and second activity
First Activity Class
package com.rohan.rohan_pc.sportappnew;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginActivity extends ActionBarActivity {
EditText edtEmail, edtPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Initialize components
edtEmail = (EditText) findViewById(R.id.edtEmail);
edtPassword = (EditText) findViewById(R.id.edtPassword);
Button btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (edtEmail.getText().toString().length() > 0 && edtPassword.getText().toString().length() > 0) {
new GetAllCustomerTask().execute(new ConnecterClass());
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, 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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Connect to the DB
private class GetAllCustomerTask extends AsyncTask<ConnecterClass, Long, JSONArray>
{
#Override
protected JSONArray doInBackground(ConnecterClass... params) {
// Execute in background
return params[0].usrLogin(edtEmail.getText().toString(), edtPassword.getText().toString());
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
if (jsonArray != null) {
JSONObject json = null;
try {
json = jsonArray.getJSONObject(0);
if (edtEmail.getText().toString().equals(json.getString("email"))) {
if (edtPassword.getText().toString().equals(json.getString("pass"))) {
Toast toast = Toast.makeText(getApplicationContext(), "login successful", Toast.LENGTH_SHORT);
toast.show();
Intent intent = new Intent(LoginActivity.this, SearchActivity.class);
//Pass the school_id
intent.putExtra("SCHOOL_ID", json.getInt("school_id"));
startActivity(intent);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "password incorrect", Toast.LENGTH_SHORT);
toast.show();
}
} else {
Toast toast = Toast.makeText(getApplicationContext(), "failed to login ...", Toast.LENGTH_SHORT);
toast.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
//login(edtEmail.getText().toString(),""
/*
//Got to second screen if login is successful
Intent intent = new Intent(LoginActivity.this, AfterLogin.class);
//Pass the table name through
intent.putExtra("CLIENT_DB", clientDB);
startActivity(intent);
*/
}
}
}
}
Second Activity Class
> package com.rohan.rohan_pc.sportappnew;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SearchActivity extends ActionBarActivity {
EditText edtFName, edtLName, edtIDNum;
ListView listViewSearch;
String sFName, sLName, sIDNum;
int school_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
edtFName = (EditText) findViewById(R.id.edtFirstName);
edtLName = (EditText) findViewById(R.id.edtLastName);
edtIDNum = (EditText) findViewById(R.id.edtIDNum);
Button btnSearch = (Button) findViewById(R.id.btnSearch);
listViewSearch = (ListView) this.findViewById(R.id.listViewSearch);
//Initialize the default values for the search criteria variables
sFName = "";
sLName = "";
sIDNum = "";
//Load school_id
school_id = getIntent().getExtras().getInt("SCHOOL_ID");
if(edtFName.requestFocus()) { getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); }
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(edtFName.getText().toString().length() > 0)
{
sFName = edtFName.getText().toString().trim();
}
if(edtLName.getText().toString().length() > 0)
{
sLName = edtLName.getText().toString().trim();
}
if(edtIDNum.getText().toString().length() > 0)
{
sIDNum = edtIDNum.getText().toString().trim();
}
new SearchAllCustomers().execute(new ConnecterClass());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search, 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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//Search in the background
public void setListViewArray(final JSONArray jsonArray)
{
this.listViewSearch.setAdapter(new Search_ListView_Adapter(jsonArray, this));
//Setup what happens when a user clicks on a searched item
this.listViewSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try{
JSONObject clickedItem = jsonArray.getJSONObject(position);
Intent askActivity = new Intent(getApplicationContext(), AskActivity.class);
askActivity.putExtra("IDNUM", clickedItem.getString("idnum"));
askActivity.putExtra("SCHOOL_ID", clickedItem.getInt("school_id"));
startActivity(askActivity);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
// Connect to the DB
private class SearchAllCustomers extends AsyncTask<ConnecterClass, Long, JSONArray>
{
#Override
protected JSONArray doInBackground(ConnecterClass... params) {
// Execute in background
return params[0].searchPlayers(school_id, sFName, sLName, sIDNum);
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
if (jsonArray != null) {
setListViewArray(jsonArray);
//login(edtEmail.getText().toString(),""
/*
//Got to second screen if login is successful
Intent intent = new Intent(LoginActivity.this, AfterLogin.class);
//Pass the table name through
intent.putExtra("CLIENT_DB", clientDB);
startActivity(intent);
*/
}
}
}
}
The XML - First Activity
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".LoginAcivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/edtEmail"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp"
android:hint="email ..."
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/edtPassword"
android:layout_below="#+id/edtEmail"
android:layout_centerHorizontal="true"
android:layout_marginTop="44dp"
android:hint="password ..."
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/btnLogin"
android:layout_below="#+id/edtPassword"
android:layout_centerHorizontal="true"
android:layout_marginTop="49dp" />
</RelativeLayout>
The XML - Second Activity
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.rohan.rohan_pc.sportsappv001.SearchActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Search"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Name"
android:ems="10"
android:id="#+id/edtFirstName"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Surname"
android:ems="10"
android:id="#+id/edtLastName"
android:layout_below="#+id/edtFirstName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/edtIDNum"
android:hint="ID Number"
android:layout_below="#+id/edtLastName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="#+id/edtLastName"
android:layout_alignEnd="#+id/edtLastName" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:id="#+id/btnSearch"
android:layout_below="#+id/edtIDNum"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="64dp"
android:layout_marginTop="42dp" />
<ListView
android:layout_width="wrap_content"
android:layout_height="200dp"
android:id="#+id/listViewSearch"
android:layout_alignParentBottom="true"
android:layout_toEndOf="#+id/edtIDNum"
android:layout_alignTop="#+id/edtFirstName"
android:clickable="true"
/>
I just figured to re-create the app. I dont think it is a wise decision to copy the raw files to another directory and use that.
I have 5 buttons every one has letter (Button "H",Button "E"Button "L"Button "L"Button "O") which make the word "HELLO". what I need is to make on click sequence to these buttons so if I click "H" first and "E" second until complete the word the app will do something, But if I click "L" first will give me some error message.
Any Idea to do this sequence?
Thanks
Just have an Array like this:
int[] tracker = new int[5];
and when you click a button, say "H", set tracker[0] = 1;
but when you click a button, say "L", check whether all the previous button values are 1. If yes, then set the corresponding tracker to 1 else, show an error message, and do not make any change to the tracker Array.
Something Like this:
onHClick{
tracker[0] = 1;
}
onEClick{
for(int i=0; i<1; i++){
if(tracker[i] == 0){
//show error message and return;
}else{
tracker[1] = 1;
return;
}
}
}
You can do something like
When activity started you just make other button Enabled = false of something like that. But make the first button Enabled. Don't make the Visible=false.
Now on click of Button "H" make enable Button "E" and so on.
So user will only have to click the button in sequence. Button can not be presses in any random manner.
Try this and let me know that it works or not.
Very Interesting and exactly same to your requirement..check once..
If you give any string other than HELLO also works better.
public class ButtonTest extends Activity
{
private String result="";
String sampleText = "HELLO";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
int noOfBtns = sampleText.length();
LinearLayout ll = (LinearLayout)findViewById(R.id.btnlay);
final TextView tvtext = (TextView)findViewById(R.id.result);
final Button[] btns = new Button[noOfBtns];
for(int i=0;i<noOfBtns;i++)
{
btns[i] = new Button(this);
btns[i].setText(sampleText.substring(i,i+1));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btns[i], lp);
final int j = i;
btns[i].setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
System.out.println(j+" "+result.length());
if(j == result.length())
{
result = result+btns[j].getText().toString();
if(sampleText.startsWith(result))
{
tvtext.setText(result);
}
}
else
{
Toast.makeText(getApplicationContext(), "Wrong Button Pressed", Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
Layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/result"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:textColor="#fff"/>
<LinearLayout
android:id="#+id/btnlay"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>
Try the following
package com.example.buttonsequence;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
ArrayList<Button> buttonList=null;
TextView resultTextView=null;
Button buttons[]=null;
String helloStr="HELLO";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonList=new ArrayList<Button>();
buttons=new Button[5];
this.resultTextView=(TextView) this.findViewById(R.id.result_text);
this.resultTextView.setText("");
buttons[0]=(Button)this.findViewById(R.id.h_button);
buttons[1]=(Button)this.findViewById(R.id.e_button);
buttons[2]=(Button)this.findViewById(R.id.l_button);
buttons[3]=(Button)this.findViewById(R.id.l2_button);
buttons[4]=(Button)this.findViewById(R.id.o_button);
for(int k=0;k<5;k++)
buttons[k].setOnClickListener(onClickListener);
Button button=(Button)this.findViewById(R.id.exit_button);
button.setOnClickListener
(
new OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
}
);
}
OnClickListener onClickListener=new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Button b=(Button)v;
buttonList.add(b);
int size=buttonList.size();
if(size>0)
{
StringBuilder resultBuilder=new StringBuilder();
for(int i=0;i<size;i++)
{
Button tempButton=buttonList.get(i);
if(tempButton==buttons[i])
{
resultBuilder.append(helloStr.charAt(i));
if(i==4)
{
resultTextView.setText(resultBuilder.toString()+" clicked");
buttonList.clear();
}
else
{
resultTextView.setText(resultBuilder.toString()+" clicked");
}
}
else
{
buttonList.remove(i);
Toast.makeText(getApplicationContext(), "No correctly clicked", Toast.LENGTH_SHORT).show();
break;
}
}
}
else
{
resultTextView.setText("Invalid pressed");
}
}
};
}
activity_main.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/h_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="H" />
<Button
android:id="#+id/e_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="E" />
<Button
android:id="#+id/l_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="L" />
<Button
android:id="#+id/l2_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="L" />
<Button
android:id="#+id/o_button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="O" />
<TextView
android:id="#+id/result_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<Button
android:id="#+id/exit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit" />
</LinearLayout>
I don't know exactly your flow but you can try this.
set Tag to each button as its Text, like this.
b.setTag("H");
and than after like this.
Button b;
String name = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s = (String) v.getTag();
name +=s;
if( "HELLO".startsWith(name)){
<VALID>
}else{
<ERROR>
}
}
});
}
check the variable name on each button click with your original word i.e. HELLO like above.
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