Comparing Saved TXT and EditText text - android

I Want to Make A System that compares password (4 letter numeric).
Input Code (I Already Have fis)
fis = openFileInput(FILE_NAME);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String text;
while((text = br.readLine()) != null)
{
sb.append(text).append("\n");
}
String finalinput = sb.toString();
String finalpassinput = password.getText().toString();
Toast.makeText(this, "finalinput:"+finalinput+"finalpassinput:"+finalpassinput,Toast.LENGTH_LONG).show();
if(finalinput.equals(finalpassinput))
{
Toast.makeText(this,"Login!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this, HomeActivity.class));
}
else
{
Toast.makeText(this,"Incorrect Password",Toast.LENGTH_SHORT).show();
}
And This Source Code will keep say that the two passwords are different.
How I Wrote My File :
fos = openFileOutput(FILE_NAME_PW, MODE_PRIVATE);
fos.write(encodedpw.getBytes());
Toast.makeText(this, "Saved to " + getFilesDir() + "/" + FILE_NAME_PW, Toast.LENGTH_LONG).show();
I am curious if encodepw.getBytes() will change anything to the string (Including null characters, etc.) and if Java won't think them the same.
Thank you.

I found myself the answer to it. The finalinput variable had some null charachter before it, so you can get pure string using this function.
public static String FileStringParse(String FileString)
{
FileString = FileString.replaceAll("\\D+","");
return FileString;
}

Related

Strings mixed up reading from internal storage

I'm using internal storage to store multiple strings entered by the user through multiples edit text.
So the layout is composed of multiples Textviews which correspond to the title of the fields, and multiples Edittexts which correspond to the fields where the user can enter his string.
When the user has finished, he presses the save button and this function is triggered :
public void save(View view) // SAVE
{
File file= null;
String name = editname.getText().toString()+"\n";
String marque = editmarque.getText().toString()+"\n";
String longueur = editlongueur.getText().toString()+"\n";
String largeur = editlargeur.getText().toString()+"\n";
String tirant = edittirant.getText().toString()+"\n";
String immatri = editImmatriculation.getText().toString()+"\n";
String port = editPort.getText().toString()+"\n";
String contact = editContact.getText().toString()+"\n";
String panne = editPanne.getText().toString()+"\n";
String poste = editPoste.getText().toString()+"\n";
String police = editPolice.getText().toString()+"\n";
String assurance = editAssurance.getText().toString();
FileOutputStream fileOutputStream = null;
try {
file = getFilesDir();
fileOutputStream = openFileOutput("Code.txt", Context.MODE_PRIVATE); //MODE PRIVATE
fileOutputStream.write(name.getBytes());
fileOutputStream.write(marque.getBytes());
fileOutputStream.write(longueur.getBytes());
fileOutputStream.write(largeur.getBytes());
fileOutputStream.write(tirant.getBytes());
fileOutputStream.write(immatri.getBytes());
fileOutputStream.write(port.getBytes());
fileOutputStream.write(contact.getBytes());
fileOutputStream.write(panne.getBytes());
fileOutputStream.write(poste.getBytes());
fileOutputStream.write(police.getBytes());
fileOutputStream.write(assurance.getBytes());
Toast.makeText(this, "Saved \n" + "Path --" + file + "\tCode.txt", Toast.LENGTH_SHORT).show();
editname.setText("");
editmarque.setText("");
editlargeur.setText("");
editlongueur.setText("");
edittirant.setText("");
editImmatriculation.setText("");
editPort.setText("");
editContact.setText("");
editPanne.setText("");
editPoste.setText("");
editPolice.setText("");
editAssurance.setText("");
return;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Than, in another file I retrieve this data through another button that triggers this function :
public void load(View view)
{
try {
FileInputStream fileInputStream = openFileInput("Code.txt");
int read = -1;
StringBuffer buffer = new StringBuffer();
while((read =fileInputStream.read())!= -1){
buffer.append((char)read);
}
fileInputStream.close();
String tab[] = buffer.toString().split("\n");
String boatname = tab[0];
String marque = tab[1];
String longueur = tab[2];
String largeur = tab[3];
String tirant = tab[4];
String immatri = tab[5];
String port = tab[6];
String contact = tab[7];
String panne = tab[8];
String poste = tab[9];
String assurance = tab[10];
String police = tab[11];
getboatname.setText(boatname);
getmarque.setText(marque);
getlongueur.setText(longueur);
getlargeur.setText(largeur);
getTirantdeau.setText(tirant);
getImmatriculation.setText(immatri);
getPort.setText(port);
getContact.setText(contact);
getPanne.setText(panne);
getPoste.setText(poste);
getAssurance.setText(assurance);
getPolice.setText(police);
} catch (Exception e) {
e.printStackTrace();
}
}
So in the save function I'm splitting the entered strings with \n, and I save the file to the internal storage, and in the load function I retrieve the strings using an array and splitting with every \n and I set the text with the correct index.
What I don't understand is that the results are all mixed up, the string of the first field is displayed in the last field for example, why ?
You can Make a Single String and write it. Also, use a different separator. You can use StringBuffer for it.
StringBuffer s=new StringBuffer();
s.append(editname.getText().toString());
s.append("##########");
s.append(editmarque.getText().toString());
s.append("##########");
s.append(editlongueur.getText().toString());
s.append("##########");
s.append(editlargeur.getText().toString());
s.append("##########");
s.append(edittirant.getText().toString());
s.append("##########");
s.append(editPort.getText().toString());
s.append("##########");
s.append(editContact.getText().toString());
s.append("##########");
s.append(editPanne.getText().toString());
s.append("##########");
s.append(editPoste.getText().toString());
s.append("##########");
s.append(editPolice.getText().toString());
s.append("##########");
s.append(editAssurance.getText().toString());
s.append("##########");
FileOutputStream fileOutputStream = null;
try {
file = getFilesDir();
fileOutputStream = openFileOutput("Code.txt", Context.MODE_PRIVATE); //MODE PRIVATE
fileOutputStream.write(s.toString().getBytes());
Toast.makeText(this, "Saved \n" + "Path --" + file + "\tCode.txt", Toast.LENGTH_SHORT).show();
editname.setText("");
editmarque.setText("");
editlargeur.setText("");
editlongueur.setText("");
edittirant.setText("");
editImmatriculation.setText("");
editPort.setText("");
editContact.setText("");
editPanne.setText("");
editPoste.setText("");
editPolice.setText("");
editAssurance.setText("");
return;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
When you get FileInputStream split the String with this "##########" vlaue

How to read text file line by line?

My Goal is to be able to save as many high scores from my application to my text file i create using FileOutputStream. I then want to be able to read from the file and put each line into an array list item. While using InputStreamReader I am able to load all of the lines of text from the text file into the variable s. My problem now is i want to take each line from the text file and save it into an array list item. How would i accomplish this?
Example string variables for high scores:
String myStr = "Ryan 150 hard \n";
String myStr2 = "Andrew 200 Medium \n";
public void saveClick(){
try{
//String myNum = Integer.toString(life);
FileOutputStream fOut = openFileOutput("storetext.txt", Context.MODE_PRIVATE);
OutputStreamWriter outputWriter = new OutputStreamWriter(fOut);
outputWriter.write(myStr);
outputWriter.write(myStr2);
outputWriter.close();
/*OutputStreamWriter out = new OutputStreamWriter(openFileOutput(STORETEXT, 0));
out.write(life);
out.close();*/
Toast.makeText(getApplicationContext(), "Save Successful", Toast.LENGTH_LONG).show();
}
catch(Throwable t){
Toast.makeText(getApplicationContext(), "Save Unsuccessful", Toast.LENGTH_LONG).show();
}
}
public void readFileInEditor(){
try{
FileInputStream fileIn = openFileInput("storetext.txt");
InputStreamReader InputRead = new InputStreamReader(fileIn);
char [] inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0){
//char to string conversion
String readString = String.copyValueOf(inputBuffer,0,charRead);
s += readString;
}
InputRead.close();
Toast.makeText(getApplicationContext(), "New Text: " + s , Toast.LENGTH_LONG).show();
//myText.setText("" + s);
try{
//life = Integer.parseInt(s);
//Toast.makeText(getApplicationContext(), "My Num: " + life , Toast.LENGTH_LONG).show();
}
catch(NumberFormatException e){
//Toast.makeText(getApplicationContext(), "Could not get number" + life , Toast.LENGTH_LONG).show();
}
}
catch(java.io.FileNotFoundException e){
//have not created it yet
}
catch(Throwable t){
Toast.makeText(getApplicationContext(), "Exception: "+t.toString(), Toast.LENGTH_LONG).show();
}
}
To make your life easier, better to use (1) BufferedReader::readline() method, or (2) Scanner::nextLine() method. And add each line to a List<String> in the for loop.
A simple example:
List<String> lines = new ArrayList<>();
String curLine = null;
BufferedReader reader = new BufferedReader(new FileReader("storetext.txt"));
while ((curLine = reader.readLine()) != null) {
lines.add(curLine);
}
Use BufferedReader to read line by line and put them in an ArrayList right away.

Unable to split mix latin & arabic string from a file in android

Need to parse this file (mixed latin & arabic):
1|حِيمِ
2|الَمِينَ
The file was saved as UTF8 in notepad++, and put in android asset folder.
Expected result: for line1, the entries are "1" and "حِيمِ" (split by "|").
AssetManager manager = context.getAssets();
InputStream inStream = null;
inStream = manager.open("file.txt");
BufferedReader buffer = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
String line = "";
while ((line = buffer.readLine()) != null) {
String lineEnc = URLEncoder.encode(line, "UTF-8");
String[] columns = lineEnc.split("%7C");
if (columns.length>=3) {
Toast toast = Toast.makeText(context, "Line: " + columns[0] + " and " + columns[1], Toast.LENGTH_LONG);
toast.show();
}
}
Actual Result:
columns[0] = "1" ok, but
columns[1] = "%D8%AD%D9..." not Ok, expected "حِيمِ".
How to fix this, or is there better way? Please help. Thanks in advance.
Solved, changing:
while ((line = buffer.readLine()) != null) {
String lineEnc = URLEncoder.encode(line, "UTF-8");
String[] columns = lineEnc.split("%7C");
into
while ((line = buffer.readLine()) != null) {
String[] columns = line.split("\\|");

how to split string in textfile (retrieved from raw folder) then store it into two seperate variables in android?

this is the example text int text file
title: get this string and
desc: get this string
I want to split it with "title:" and "desc:"
it is simple :
after getting file content (https://stackoverflow.com/a/14768380/1725748), do :
String mystring= "title: xxxxxx desc: yyyyy";
String[] splits = mystring.split("title:|desc:");
splits[0] // is the title
splits[1] // is the description
There are various ways to get a String how you like, here I found the index of desc and split the String where desc appears:
try{
InputStream inputStream = getResources().openRawResource(R.raw.textfile);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
String title_content, desc_content;
// Read each line
while((line = reader.readLine( )) != null)
{
// title: get this string and desc: get this string
// ^
// (desc_location)
int desc_location;
if((desc_location = line.indexOf("desc:")) > 0)
{
title_content = line.substring(0, desc_location);
desc_content = line.substring(desc_location, line.length( ));
}
}
} catch (Exception e) {
// e.printStackTrace();
}

Extracting words from a website

Hi I want to try making a simple application for android phones for which I will be requiring a dictionary. I thought of using urbandictionary.com as the reference site. Is there any technique by which I can extract all the words with the definitions and their respective words in the thesaurus ?
I was checking out the Google example found at
http://developer.android.com/resources/samples/SearchableDictionary/index.html
It appears that they just add their words with this example
private void loadWords() throws IOException {
Log.d(TAG, "Loading words...");
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.definitions);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, "-");
if (strings.length < 2) continue;
long id = addWord(strings[0].trim(), strings[1].trim());
if (id < 0) {
Log.e(TAG, "unable to add word: " + strings[0].trim());
}
}
} finally {
reader.close();
}
Log.d(TAG, "DONE loading words.");
}
However, when I look for R.raw.definitions that directory is empty.
http://developer.android.com/resources/samples/SearchableDictionary/res/raw/index.html

Categories

Resources