Split every character of a word in android? - java

I am trying to Split every character of a word..Such as
"CAT"=C,A,T
I have been able get the full length of the word..by taking input in a edit text..
package com.pack.name;
import android.R.array;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class NamtestActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
EditText name;
Button save;
String sname;
int pname, i;
char eachword[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
name = (EditText) findViewById(R.id.editText1);
save = (Button) findViewById(R.id.button1);
save.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sname = name.getText().toString();
pname = sname.length();
Toast.makeText(getApplicationContext(), "" + pname, Toast.LENGTH_LONG)
.show();
//for (i = 0; i < pname; i++) {
}
}
}
Here we take input from the edittext and then by clicking the button it shows the length of the word ...Now what i need to split the word ..i was trying to do this in a for loop...
Help Please .....

You can do this using BreakIterator class with getCharaterInstance() static method.
see this link for more detail:
http://docs.oracle.com/javase/6/docs/api/java/text/BreakIterator.html
You can manually do this using toCharArray().
public void processSong(String word){
//Conversion of String to Character Array//
String s = word.toUpperCase();
char[] tempArr = s.toCharArray();
Character[] arr = new Character[tempArr.length];
for (int i=0,j=0 ; i<tempArr.length ; i++,j++){
arr[i] = tempArr[j];
}
for (Character c : l){
tempL.add(c);
}
Log.d("Vivek-Characters",tempL.toString());
}

You can simply use:
eachword = sname.toCharArray();

You can iterate through them like this:
for (char c: sname.toCharArray()) {
...
}
or just save them
char[] chars = sname.toCharArray();

just call
"CAT".toCharArray();
you will get as the result
[C, A, T]

Related

Send Data to Firebase

I'm developing a program that generates random passwords, but I'm bad at databases. I can generate password, but I want to send the generated password to realtime database with Firebase, but I can't. What should I do?
My code in mainactivity is like this :
import androidx.appcompat.app.AppCompatActivity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
CheckBox num;
CheckBox upper;
CheckBox lower;
CheckBox sym;
EditText max_lenght;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button5);
button = (Button)findViewById(R.id.button5);
textView = (TextView)findViewById(R.id.textView) ;
textView=(TextView)findViewById(R.id.textView2);
num= (CheckBox)findViewById(R.id.num);
upper=(CheckBox)findViewById(R.id.upper) ;
lower=(CheckBox)findViewById(R.id.lower) ;
sym=(CheckBox)findViewById(R.id.sym) ;
max_lenght=(EditText) findViewById(R.id.editTextNumberSigned);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View pas) {
String pass = randompassword(Integer.parseInt(max_lenght.getText().toString()),upper.isChecked(),lower.isChecked(),num.isChecked(),sym.isChecked());
if (pass.isEmpty()){
Toast.makeText(getApplicationContext(),"Lütfen Veri Giriniz !!",Toast.LENGTH_SHORT).show();
}
else {
ClipboardManager clipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText("Veri",pass);
clipboardManager.setPrimaryClip(clipData);
Toast.makeText(getApplicationContext(),"Sifreniz Olusturuldu... ",Toast.LENGTH_LONG).show();
}
textView.setText(pass);
}
});
}
private static String randompassword(int max_lenght, boolean upperCase, boolean lowerCase, boolean numbers, boolean specialCharacters)
{
String upperCaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lowerCaseChars = "abcdefghijklmnopqrstuvwxyz";
String numberChars = "0123456789";
String specialChars = "!##$%^&*()_-+=<>?/{}~|";
String allowedChars = "";
Random rn = new Random();
StringBuilder sb = new StringBuilder(max_lenght);
if (upperCase){
allowedChars+=upperCaseChars;
sb.append(upperCaseChars.charAt(rn.nextInt(upperCaseChars.length()-1)));
}
if(lowerCase){
allowedChars+=lowerCaseChars;
sb.append(lowerCaseChars.charAt(rn.nextInt(lowerCaseChars.length()-1)));
}
if (numbers){
allowedChars+=numberChars;
sb.append(numberChars.charAt(rn.nextInt(numberChars.length()-1)));
}
if (specialCharacters){
allowedChars+=specialChars;
sb.append(specialChars.charAt(rn.nextInt(specialChars.length()-1)));
}
sb.append(allowedChars.charAt(rn.nextInt(allowedChars.length()-1)));
for(int i=sb.length();i < max_lenght; ++i){
sb.append(allowedChars.charAt(rn.nextInt(allowedChars.length())));
}
return sb.toString();
}
}
I have defined the things required for firebase, but I don't know where to write in the main part.
After generating the random password, you can send to the database in the following way:
private DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("passwords").child(/*how so ever you want to nest data*/).setValue(password);
This is just a snippet to get you started, you can read more Read and write data.

Trying to get a random Number for two String lists

I am trying to develop an app that helps kids to learn French but I have difficulties getting a random number twice, so that if the user presses the second button he gets the German answer.
package com.example.calebseeling.french;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class FrenchActivity extends AppCompatActivity {
private Button Next;
private TextView German;
private TextView French;
private Button Answer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_french);
Answer = (Button) findViewById(R.id.Answer);
German = (TextView) findViewById(R.id.German);
French = (TextView) findViewById(R.id.French);
Next = (Button) findViewById(R.id.NextButton);
Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String getLetter = Letter.getLetter();
German.setText(getLetter);
}
});
Answer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
And here is the following code for the Strings:
package com.example.calebseeling.french;
import java.util.Random;
public class Letter {
public static String[] Letters = {
"Oui",
"Ca va"
};
public static String[] LettersG = {
"Ja",
"Wie Gehts"
};
public static String getLetter() {
Random randomgenerator = new Random();
int Random = randomgenerator.nextInt(Letters.length);
return Letters[Random];
}
}
In the first sample, there is the Answer listener that is empty. This is where I would like to get the answer from the German array. What can I do ? I would like them to correspond, so at the moment I thought about picking a number and getting the corresponding answer, but I can't figure out how, through the Activity. Can you help me ?
The question isn't very clear, but here is my attempt -
package com.example.calebseeling.french;
import java.util.Random;
public class Letter {
private static Random randomgenerator = new Random();
private static int randomNumber;
public static String[] Letters = {
"Oui",
"Ca va"
};
public static String[] LettersG = {
"Ja",
"Wie Gehts"
};
public static String getLetter() {
randomNumber = randomgenerator.nextInt(Letters.length);
return Letters[randomNumber];
}
public static String getCorrespondingGermanLetter() {
return LettersG[randomNumber];
}
}
What we are doing here is basically saving the generated random number.
So if you need the same German word, you can do so by calling getCorrespondingGermanLetter.
By the way they are words not letters.
What about simply returning a number from the method instead of a String:
int getRandomNumber(){...}
int a = getRandomNumber();
then fetch items from your arrays based on this number

I need to sort my random numbers generated and add them to the second editText2

package com.example.sai.generatinrandomnumbers;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
// I need to sort my random numbers generated and add them to the second editText2 in my application i tried using collections but i couldn't figure it out plz help me and I'm attaching my code below.should i use a arraylist again??
public class MainActivity extends AppCompatActivity {
EditText editText, editText2;
Button button, button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
editText.setEnabled(false);
editText2 = (EditText) findViewById(R.id.editText2);
editText2.setEnabled(false);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random r = new Random();
ArrayList<Integer> num = new ArrayList<Integer>();
for (int i = 0; i < 6; i++) {
int answer = r.nextInt(10) + 1;
num.add(answer);
editText.setText(String.valueOf(num));
}
}
});
}
}
You need to read all the Integers into your data structure and then print them back sorted to a 2nd EditText Widget. Alright, let's do something like this:
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random r = new Random();
ArrayList<Integer> num = getRandomNums(6);
editText.setText(getStringNum(num));
Collections.sort(num);
editText2.setText(getStringNum(num));
});
private List<Integer> getRandomNums(final int theNumDigits) {
Random r = new Random();
ArrayList<Integer> num = new ArrayList<>();
for (int i = 0; i < theNumDigits; i++) {
int answer = r.nextInt(10) + 1;
num.add(answer);
}
return num;
}
private String getStringNum(final List<Integer> theNumbers) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < theNumbers.size(); i++) {
sb.append(num.get(i));
}
String toReturn = sb.toString();
sb.setLength(0);
return toReturn;
}
I reformatted the code for you to help you understand exactly what is going on. You're getting all the randomly generated numbers and adding them to an ArrayList. Then creating a String using a StringBuilder You were overwriting your previously set value in the EditText each time your loop iterated
Then you call Collections.sort() and do the whole thing over again.

Why do I not seem to have access to my title variable in my OnClick method

I am building an app that will search an array for two or more strings and return some information related to both strings. I need to access my variable entitled title in my OnClick. Here my code:
package com.rottenapi.applogictest;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;
public class Main extends Activity {
private static String url = "http://api.rottentomatoes.com/api/public/v1.0/movies/770672123/cast.json?apikey=3p9ehnhzbxwpbd6mk8fncf67";
private static String TAG_CAST = "cast";
private static String TAG_LINKS = "links";
private static String TAG_NAME = "name";
public static String TAG_REL = "rel";
private static String TAG_TITLE = "Title";
EditText enterName;
EditText enterNameTwo;
EditText result;
Button findMovie;
String searchOne;
String searchTwo;
public String title;
List<String> castMembers = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainlayout);
JSONArray cast = null;
JSONArray rel = null;
JSONArray links = null;
final JSONParser jParser = new JSONParser();
final JSONObject jSon = jParser.getJSONFromUrl(url);
enterName = (EditText) findViewById(R.id.enterName);
enterNameTwo = (EditText) findViewById(R.id.enterNameTwo);
result = (EditText) findViewById(R.id.result);
searchOne = enterName.getText().toString();
searchTwo = enterNameTwo.getText().toString();
try{
cast = jSon.getJSONArray(TAG_CAST);
for(int i=0; i < cast.length(); i++){
JSONObject c = cast.getJSONObject(i);
String name = c.getString(TAG_NAME);
castMembers.add(name);
}
if (castMembers.contains(searchOne) && castMembers.contains(searchTwo)){
links = jSon.getJSONArray(TAG_LINKS);
for(int i=0; i < links.length(); i++){
JSONObject d = links.getJSONObject(i);
String movieInfoLink = d.getString(TAG_REL);
JSONObject jSonMovie = jParser.getJSONFromUrl(movieInfoLink);
rel = jSonMovie.getJSONArray(TAG_REL);
}for(int i =0; i < rel.length(); i++){
JSONObject e = rel.getJSONObject(i);
title = e.getString(TAG_TITLE);
}
findMovie.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("Result contents", title);
result.setText(title);
}
});
}
}
catch(Exception e){
Log.e("Error", e.toString());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mainlayout, menu);
return true;
}
When I run this the app displays in the emulator however after clicking the button nothing happens also no errors print in the logcat. My results contents log doesnt print out either in the log. Any ideas whats going on?
Button findMovie is not called throug findViewById()
This is because you haven't linked your Button findMovie to the layout id for the Button. All you need to do is simply add the following line to your code and it will work:
findMovie = (Button) findViewById(R.id.findMovieButton);
Hope this helps..

Randomly pick an index from an array, display in TextView

I'm new to Android development and I'm wondering why my code crashes the Android Emulator. What I'm doing is creating an array of strings, then picking an index from the array at random and displaying the value inside a TextView. But it always seems to crash my emu.
package com.test.randomTest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class randomTestActivity extends Activity {
private Button button;
private TextView helloTextView;
private String[] hellos;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
helloTextView = (TextView)findViewById(R.id.helloText);
button = (Button)findViewById(R.id.button);
hellos = new String[7];
hellos[0] = "Hello";
hellos[1] = "G'days";
hellos[2] = "Yo!";
hellos[3] = "Hi";
hellos[4] = "Hay";
hellos[5] = "Bonjour";
hellos[6] = "Hay there!";
hellos[7] = "Hallo";
button.setOnClickListener(buttonListener);
}
private OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
int x = 0 + (int)(Math.random() * ((7 - 0) + 1));
String helloText = hellos[x];
helloTextView.setText(helloText);
}
};
}
Any help/advice would be great!
Thanks.
You created a String[] of size 7.
hellos = new String[7];
Therefore the indices range from 0 to 6. Trying to access hellos[7] will cause an IndexOutOfBoundsException.
I assume your getting a nullpointerexecption. Try generating your random number like this instead:
Random rando = new Random();
int x = rando.nextInt(hellos.lenght);
package com.test.randomTest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class randomTestActivity extends Activity {
private Button button;
private TextView helloTextView;
private String[] hellos;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
helloTextView = (TextView)findViewById(R.id.helloText);
button = (Button)findViewById(R.id.button);
hellos = new String[8];
hellos[0] = "Hello";
hellos[1] = "G'days";
hellos[2] = "Yo!";
hellos[3] = "Hi";
hellos[4] = "Hay";
hellos[5] = "Bonjour";
hellos[6] = "Hay there!";
hellos[7] = "Hallo";
button.setOnClickListener(buttonListener);
}
private OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
int x = 0 + (int)(Math.random() * ((7 - 0) + 1));
String helloText = hellos[x];
helloTextView.setText(helloText);
}
};
}
Increase string array size you gave 7 as size, but you are passing 8 values to string.
so it throws indexoutofbounds exception.
Thats probably because of array IndexOutOfBoundException... since sometimes your x will have value 8 but array length is just 7..

Categories

Resources