Simple Encrypt Decrypt String with array in Android - java

My problem seems easy, I am trying to encrypt a string in android.
What the program should do
The objective of the program is, put a word or a letter in textbox1, click on button encrypt and textbox2 should to show the symbol in the same position in second array of the letter that you put in.
For example I write letter A (array 1 [0]) must show symbol $ (array 2 [0]) if a click on ENCRYPT button, if I put a symbol and click on DECRYPT must show the letter which is equivalent in position of array
Need help. Sorry for grammar and edit question, first time and no English speaker, i tried to make it more simple.
Arreglo Class, just for declare 2 arrays.
package PaqueteArreglo;
public class Arreglo {
public String [] encrypt = new String[3];
public String [] decrypt = new String[3];
}
Main Activity
package com.example.encrypt;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import PaqueteArreglo.Arreglo;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
//Instance the class with the arrays
PaqueteArreglo.Arreglo ins = new Arreglo();
public Button button1,button2;
public EditText text1, text2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
ins.encrypt[0] = "a";
ins.encrypt[1] = "b";
ins.encrypt[2] = "c";
ins.decrypt[0] = "$";
ins.decrypt[1] = "%";
ins.decrypt[2] = "&";
}
private void initialize(){
text1 = (EditText)findViewById(R.id.txtWord);
text2 = (EditText)findViewById(R.id.txtResult);
button1 = (Button)findViewById(R.id.btnEncrypt);
button1.setOnClickListener(this);
button2 =(Button)findViewById(R.id.btnDecrypt);
button2.setOnClickListener(this);
}
#Override
public void onClick(View view) {
String word = String.valueOf(this.text1.getText());
if (view.getId() == R.id.btnEncrypt)
{
String demo = "";
int lon = 0;
lon = word.length();
for (int i = 0; i < lon; i++ )
{
if (ins.encrypt[i].equalsIgnoreCase(String.valueOf(word.charAt(i))))
{
demo = demo + ins.decrypt[i];
text2.setText(demo);
}
}
}
}
}

There are two solutions to your problem using two different approach:
1- Using your defined structure (which is not optimized by the way) you need to put two nested loop for checking:
for (int i = 0; i < lon; i++ )
{
for(int j = 0; j<ins.encrypt.length;j++)
{
if (ins.encrypt[j].equalsIgnoreCase(String.valueOf(word.charAt(i))))
{
demo = demo + ins.decrypt[j];
}
}
}
text2.setText(demo);
2- Using much better data structure like HashMap:
Change your Arreglo to the following:
public class Arreglo {
public HashMap<Character, Character> encrypt = new HashMap<>();
public HashMap<Character, Character> decrypt = new HashMap<>();
}
Now change the way you add your data like:
ins.encrypt.put('a','#');
ins.decrypt.put('#','a');
...
and finally do the encryption like:
for (int i = 0; i < lon; i++ )
{
demo = demo + ins.encrypt.get(word.charAt(i));
}
text2.setText(demo);
The second implementation is more efficient

Related

Unable to get method to access characters in a String

I am trying to make a Caesar Cipher app on Android Studio. I have the XML file and most of the other code ready but was unable to continue past the point in the code where I must access each element of the string. I have tried using the charAt() function.
Also I just want the character at the point in the array to increase by the number specified, I say this because I saw that after 'z' special characters like '|' appear and that is fine by me. This is my first app and could really use some help. The error is at line 47 and 61.
Here is my code:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity
{
EditText input;
EditText output;
EditText num;
String inp;
String out;
int choice;
Character c;
Button enc, dec;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
input = (EditText) findViewById(R.id.input);
output= (EditText) findViewById(R.id.output);
num = (EditText) findViewById(R.id.num);
enc = (Button) findViewById(R.id.enc);
dec = (Button) findViewById(R.id.dec);
enc.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
inp=input.getText().toString();
choice= Integer.parseInt(num.getText().toString());
for(int i=0;i<input.length();i++)
{
inp.charAt(i)= (char) (inp.charAt(i)+choice);
}
}
});
dec.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v1)
{
inp=input.getText().toString();
choice= Integer.parseInt(num.getText().toString());
for(int i=0;i<input.length();i++)
{
inp.charAt(i)= (char) (inp.charAt(i)-choice);
}
}
});
}
}
Building on #corsiKa's answer, I suggest the following. First, convert your input string into a char[]:
char[] array = inp.toCharArray();
Now you can iterate over the array and modify its contents:
array[i] = array[i] + choice;
And, at the end, you can build your output string from that array:
output.setText(new String(array));
I believe your first problem is here:
inp.charAt(i)= (char) (inp.charAt(i)+choice);
You are trying to assign a value to a method return. This is not possible in Java.
Strings are immutable in Java - if you'd like to replace a value in a String, you must build a new String and resassign the reference that points to the old String to instead point to the new String.
There may be other issues that I have not had a chance to get to, but I believe this is the real issue. I don't fully understand what you're trying to do, so unfortunately I can't make a suggestion for what you should use instead.

How can I call all entries in an arraylist to be displayed on a graph in MPAndroidChart?

I apologize if I worded this poorly but for the sake of clarity I will explain as best I can. I'm using MPAndroidChart to draw a line graph and I followed this tutorial to get it up and running https://www.numetriclabz.com/android-line-chart-using-mpandroidchart-tutorial/#Defining_X-axis_labels. I've made some adjustments to suit my needs and so on.
On button click, I call a method that adds another entry using the value of the edit text field, at the position that i increment each button press so the code is something like entries.add(new Entry(editTextValue, numEntries));This does what I want it to do while I'm looking at the current activity screen, with the previous value remaining, and the next value being added. However, once i leave that activity and return to it, only the last value remains. My understanding is that I need to have a for loop that will iterate over each element in arraylist when I call the drawGraph method that I'm using, but I haven't had any luck with this. I've tried to use for(Entry e: entries) and use e in place of numEntries, but the data type is not compatible. Any help is greatly appreciated!
EDIT: `public class testActivity extends AppCompatActivity {
int counter = 0;
public ArrayList entries = new ArrayList<>();
public static int lifetimeNums;
public static int nums = 0;
public static int numEntries;
public static String entryLabel = Integer.toString(numEntries);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
reDrawGraph();
}
// Graphing method
public void reDrawGraph(){
LineChart chart = (LineChart) findViewById(R.id.chart);
XAxis xAxis = chart.getXAxis();
xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
chart.getAxisLeft().setAxisMaxValue(100);
chart.getXAxis().setAxisMaxValue(100);
//Creating list of entries
LineDataSet dataset = new LineDataSet(entries, "# of Calls");
// creating labels
ArrayList<String> labels = new ArrayList<String>();
for (int i = 0; i < 10 + numEntries; i++) {
labels.add(Integer.toString(i));
}
LineData data = new LineData(labels, dataset);
entries.add(new Entry(testActivity.nums, numEntries));
chart.animateXY(1000,1000);
chart.notifyDataSetChanged();
chart.invalidate();
chart.setData(data); // set the data and list of lables into chart
}
public void counterClicked(View view){
try {
EditText inputText = (EditText) findViewById(R.id.edit_text_val);
int localNums = Integer.parseInt(inputText.getText().toString());
if (counter < 3) {
nums += localNums;
counter++;
numEntries++;
Toast.makeText(this, "Total Entries" + entries.get(0),
Toast.LENGTH_SHORT).show();
reDrawGraph();
inputText.getText().clear();
}
if (counter == 3){
lifetimeNums++;
numEntries++;
Intent intent = new Intent(this, SelectionActivity.class);
startActivity(intent);
}
}catch (Exception e) {
Toast.makeText(this, "Please enter a value",
Toast.LENGTH_SHORT).show();
}`

Correct integer not being passed through PutExtra

My program displays a horizontally sliding row of buttons containing the text description of a work of art. When a button is clicked, ImageActivity launches to display the corresponding work of art. When I click on any of the text buttons, though, it always displays the very last painting in the Array.
I'm trying to pass an int ID to a second activity so that it will display the correct painting once it's corresponding description is clicked.
Thank you!
Here's my MainActivity:
import android.content.Intent;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
//CONTAINING PAINTINGS
private LinearLayout mLinearList;
private String id;
private Painting painting;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
//REFERENCE THE SCROLLABLE LAYOUT STRUCTURE IN MAIN_SCREEN.XML
mLinearList = (LinearLayout) findViewById(R.id.linearList);
//FILL THE SCROLLABLE LAYOUT STRUCTURE WITH PAINTINGS
fillTextCarousel();
}
private void fillTextCarousel() {
// POPULATE THE LINEAR LIST CAROUSEL WITH PAINTINGS AND DESCRIPTIONS
Button buttonItem;
for (int i = 0; i < RenaissanceDatabase.description.length; i++) {
//STORE THE INDIVIDUAL PAINTINGS AS BUTTONS
buttonItem = new Button(this);
painting = new Painting(RenaissanceDatabase.description[i], RenaissanceDatabase.id[i]);
//USE THE CONTENT DESCRIPTION PROPERTY TO STORE
//PAINTING DATA
buttonItem.setContentDescription(painting.getDescription());
buttonItem.setText(painting.getDescription());
//SET AN ONCLICK LISTENER FOR THE TEXT BUTTON
buttonItem.setOnClickListener(displayPainting);
//ADD THE IMAGE BUTTON TO THE SCROLLABLE LINEAR LIST
mLinearList.addView(buttonItem);
}
}
private View.OnClickListener displayPainting = new View.OnClickListener() {
public void onClick(View btn) {
// COLLECT THE IMAGE STORED FOR THE PAINTING
//String Painting_ID = Integer.toString(painting.getId());
Intent imgIntent = new Intent(getApplicationContext(), ImageActivity.class);
imgIntent.setAction(imgIntent.ACTION_SEND);
imgIntent.putExtra("image_id", painting.getId());
startActivity(imgIntent);
}
};
My ImageActivity that I am trying to pass an integer ID to:
public class ImageActivity extends Activity {
private Painting painting;
private int index;
private int[] IDs;
private String[] Desc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Intent objIntent = getIntent();
int ID_Val = objIntent.getIntExtra("image_id", 0);
ImageView art = (ImageView) findViewById(R.id.imageView2);
art.setImageResource(ID_Val);
}
}
And the painting database, which I'm taking taking the ID from:
public class RenaissanceDatabase {
public static String description[] = {
"Venus of Urbino\nTitan, 1538",
"St. John the Baptist\nLeonardo da Vinci, 1516",
"Protrait of Baldassare Castiglione\nRaphael, 1515",
"The Entombent of Christ\nCaravaggio, 1603",
"Coronation of the Virgin\nFra Angelico, 1435",
"Mars and Venus\n Sandro Bottcelli, 1483"};
public static int id[] = {
R.drawable.painting1, // VENUS OF URBINO
R.drawable.painting2, // ST.JOHN BAPTIST
R.drawable.painting3, // BALDASSARE
R.drawable.painting4, // ENTOMBENT OF CHRIST
R.drawable.painting5, // CORONOATION
R.drawable.painting6 // MARS AND VENUS
};
}
Set the id for every button in your for loop -
for (int i = 0; i < RenaissanceDatabase.description.length; i++) {
//STORE THE INDIVIDUAL PAINTINGS AS BUTTONS
buttonItem = new Button(this);
painting = new Painting(RenaissanceDatabase.description[i], RenaissanceDatabase.id[i]);
//USE THE CONTENT DESCRIPTION PROPERTY TO STORE
//PAINTING DATA
buttonItem.setId(painting.getId());
....
}
}
And then change your OnClickListener -
private View.OnClickListener displayPainting = new View.OnClickListener() {
public void onClick(View btn) {
....
imgIntent.putExtra("image_id", btn.getId());
startActivity(imgIntent);
}
};
The way your code is set up this makes perfect sense.
Look at the loop you're using to configure everything.
for (int i = 0; i < RenaissanceDatabase.description.length; i++) {
.....
painting = new Painting(RenaissanceDatabase.description[i], RenaissanceDatabase.id[i]);
...
}
What is the value of painting at the end of this loop? It's whatever was in the last position in the array.
Now look at your code to pass the ID:
private View.OnClickListener displayPainting = new View.OnClickListener() {
public void onClick(View btn) {
....
imgIntent.putExtra("image_id", painting.getId());
.....
}
};
The code presented never updates the "current painting" to the one which was touched. You need to figure out which painting the user has touched, and use the ID of that painting.
Another answer has a recommendation to set the buttonId to the id of the painting - this has some issues so I wouldn't personally recommend that.
Instead I would use an Adapter and ViewHolder pattern and leverage the viewholder to contain this meta data. This is a much more scalable solution.

if statement to match users input to string answer [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm doing a word shuffle app on android studio for a class project. I need help understanding how I can get the users input and match it to the correct String answer. I tried a few approaches and have fallen short. I tried using an if(word.equals(userAnswer)) statement but having a hard time understanding it. How can I write the if statement for text input/output to match my answer in android studio?
(Optional question) Also is public void OnClick(View v) a good approach or should I go with something else?
Any help will be greatly appreciated. Thanks in advance!
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private EditText userAnswer;
private TextView answerOutput;
private TextView scrambledWord;
public void OnClick(View v){
scrambledWord = (TextView) findViewById(R.id.scrambledWord);
userAnswer = (EditText) findViewById(R.id.answerInput);
answerOutput = (TextView) findViewById(R.id.answerOutput);
Button button = (Button) v;
String word = "Animals"; // scan for word
ArrayList<Character> chars = new ArrayList<Character>(word.length()); // gets array with length of word
for ( char c : word.toCharArray() ) {
chars.add(c);
}
Collections.shuffle(chars); //shuffles the characters
char[] shuffled = new char[chars.size()];
for ( int i = 0; i < shuffled.length; i++ ) {
shuffled[i] = chars.get(i);
}
String shuffledWord = new String(shuffled);
if (word.equals(userAnswer)){
answerOutput.setText("Correct!!");
} else {
answerOutput.setText("Sorry try again.");
}
}
This will allow you to determine if they are the same
if(word.equalsIgnoreCase(userAnswer.getText().toString())) {
answerOutput.setText("Correct");
}
However, generally speaking you have a much larger problem, unless it's in code somewhere that you aren't showing us.
Somewhere in your activity onCreate/onStart you want to initialize your button with whatever view it might be.
Button checkAnswer = (Button) findViewById(//whatever your id is)
Then you want to set the onClick listener of the button. With the approach that you are using, it would end up needing two things. First this
public class MainActivity extends Activity implements View.OnClickListener {
Then in you need to set the onClick listener to your Button, probably in OnCreate.
checkAnswer.setOnClickListener(this);
Then your onClick would look something like
#Override
public void onClick(View v) {
if (word.equals(userAnswer)){
answerOutput.setText("Correct!!");
}
else {
answerOutput.setText("Sorry try again.");
}
}
The logic for scrambling the word etc, probably wouldn't be in onClick here.
Also, if you have multiple things you want to set click listeners for you would do something like this
#Override
public void onClick(View v) {
switch(v.getId()) {
case(R.id.//whatever): {
//dosomething
break;
}
}
}
Where you can multiple cases for all of the views that you have set the MainActivity to handle.
Edit: Since you updated your code
public class MainActivity extends Activity implements View.OnClickListener {
private EditText userAnswer;
private TextView answerOutput;
private TextView scrambledWord;
private String word;
private String shuffledWord;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scrambledWord = (TextView) findViewById(R.id.scrambledWord);
userAnswer = (EditText) findViewById(R.id.answerInput);
answerOutput = (TextView) findViewById(R.id.answerOutput);
createWord();
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
private void createWord() {
word = "Animals";
ArrayList<Character> chars = new ArrayList<Character>(word.length()); // gets array with length of word
for ( char c : word.toCharArray() ) {
chars.add(c);
}
Collections.shuffle(chars); //shuffles the characters
char[] shuffled = new char[chars.size()];
for ( int i = 0; i < shuffled.length; i++ ) {
shuffled[i] = chars.get(i);
}
shuffledWord = new String(shuffled);
shuffledText.setText(shuffledWord);
}
#Override
public void OnClick(View v){
if (word.equalsIgnoreCase(userAnswer.getText().toString())){
answerOutput.setText("Correct!!");
} else {
answerOutput.setText("Sorry try again.");
}
}
Did you set the onClickListener of the button to your MainActivity?
Your MainActivity should implement OnClickListener too
You need to use userAnswer.getText() to get the answer. Your userAnswer variable currently is of type EditText, which means a check to see if word.equals(userAnswer) will always return false, as they are of different types. Instead, try word.equals(userAnswer.getText()) to check if their answer equals the original word. To check if their answer equals the scrambled word, use shuffledWord.equals(userAnswer.getText()).

Java [Android] - accessing instance variable of an object array in child class

I am quite a beginner and trying to access the instance variable of an object array in the child class but all I get is the initialized values instead of updated values. It is a little more complex but making it simple, the code can be put this way.
Seed.java
public class Seed {
int weight = 0;
}
Apple.java
public class Apple {
public Seed[] seed = new Seed[10];
}
MainActivity.java
Main Activity {
public static Apple[] apple = new Apple[2];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
apple[0] = new Apple();
for (int i = 0; i < 10; i++)
apple[0].seed[i] = new seed();
assign();
//and here new activity childActivity starts
}
public void assign() {
for(int i =0; i < 10; i++)
apple[0].seed[i].weight = 10;
}
}
ChildActivity.java
ChildActivity extends mainActivity {
//display a layout with a button
//upon button click
display();
public void display() {
//output to textview
String.valueOf(apple[0].seed[0].weight);
}
gives me output of 0 instead of 10. I am not able to figure out whats wrong. I checked the values are being assigned properly in the mainActivity. I get no errors or crashes. Thanks for the help!

Categories