Basically the code I have below does currently read from a text file, but what I want it to do is store a value so that I can use it later for a another function. So from the text file I would like to store the height (175) and weight (80) value. How would that be done?
Text File:
Name: ..........
Height: 175
Weight 80
MainActivity:
package com.example.readfromfiletest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
Button b_read;
TextView tv_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b_read = (Button) findViewById(R.id.b_read);
tv_text = (TextView) findViewById(R.id.tv_text);
b_read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = "";
try {
InputStream is = getAssets().open("test.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException ex) {
ex.printStackTrace();
}
tv_text.setText(text);
}
});
}
}
Judging from your comments, it sounds like you're asking how to properly read in the values into different variables rather than reading them into one String. I think the first thing you should do to achieve this is read the file in line by line with a BufferedReader. Then for each line you read in you can determine which variable to assign the value to. For instance, you could do this:
Button b_read;
TextView tv_text;
String name = "";
int height = 0;
int weight = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b_read = (Button) findViewById(R.id.b_read);
tv_text = (TextView) findViewById(R.id.tv_text);
b_read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = "";
try {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(getAssets().open("test.txt")));
String line;
while((line = bufferedReader.readLine()) != null){
text = text.concat(line + "\n");
String[] lineVals = line.split(":");
if(lineVals[0].equalsIgnoreCase("name")){
name = lineVals[1].trim();
} else if(lineVals[0].equalsIgnoreCase("height")){
height = Integer.parseInt(lineVals[1].trim());
} else if(lineVals[0].equalsIgnoreCase("weight")){
weight = Integer.parseInt(lineVals[1].trim());
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
tv_text.setText(text);
}
});
}
The BufferedReader reads in one line at a time. For example just, "Height: 175"
The line is then split on the ":", returning a String[] with two values. Continuing with our Height example, the array looks something like this: ["Height", " 175"]
The if statements (could also be case statements) then determine whether we're dealing with the name, height or weight variable.
The value is then assigned to its appropriate variable. The trim() method is called during this assignment to remove the space after the colon. You could also circumvent this by performing the split() method on ": ".
You could also stick with your current method and do some String manipulation involving splitting, Regex, or some other method, but I am of the opinion that my proposed solution will be a bit easier to read/work with in the future.
Related
I added an onRestoreInstanceState and onSaveInstanceState in my code to save a variable that is to be saved, but yet that variable is not getting preserved after rotation
I tried googling it, I have seen the Logcat and android do call both of these functions here is the important section of the Logcat
I/SimpleActivity: PlayTheGame #9469915 onPause()
I/SimpleActivity: PlayTheGame #9469915 onSaveInstanceState()
I/SimpleActivity: PlayTheGame #9469915 onStop()
I/SimpleActivity: PlayTheGame #9469915 onDestroy()
I/SimpleActivity: PlayTheGame #245612069 onStart()
I/SimpleActivity: PlayTheGame #245612069
onRestoreInstanceState(bundle=Bundle[{points=-4, android:viewHierarchyState=Bundle[{android:views={/some weird numbers/}
I/SimpleActivity:
PlayTheGame #245612069 onResume()
So it seems like the functions I have made are getting called but not getting implemented
package com.example.rishabhjain.myapplication;
import android.content.Intent;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.TreeMap;
import stanford.androidlib.AutoSaveFields;
import stanford.androidlib.SimpleActivity;
//SimpleActivity is standford library I have downloaded,It only makes
//Syntax easy. Not used uch in this code although
public class PlayTheGame extends SimpleActivity {
private static Map<String, String> dictionary = null;//keeps words and
//defns
private static ArrayList<String> arr = null;//keeps only words
TextView score = null;
private MediaPlayer mp;//for starting music when playing the game
private int sc;//this variable saves score
//the next two functions read files containing words and their meanings
private void readFileData() {
Scanner scan = new Scanner(
getResources().openRawResource(R.raw.text)//scans from raw file
);
readIt(scan);//readIt and store it in dictionary
try {//in try in case user didn't added a word and file was not created
Scanner scan2 = new Scanner(
openFileInput("dictionary.txt")//reads the user saved words
);
readIt(scan2);
} catch (Exception e) {
//do noting
}
}
private void readIt(Scanner scan) {
/*splits appart the words of each file from their definitions*/
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] parts = line.split("\t");//stores the splitted parts
if (parts.length < 2)
continue;//in case encountered an emply line
dictionary.put(parts[0], parts[1]);//words and correspondind defns
//added to the dictionary
arr.add(parts[0]);//stores words
}
}
//to reset word after each click or onCreate
private void resetWord() {
Random randy = new Random();
int nextInt = randy.nextInt(arr.size());
String nextWord = arr.get(nextInt);
TextView word = (TextView) findViewById(R.id.word);
for (; nextWord.equals(word.getText()); ) {
nextInt = randy.nextInt(arr.size());
nextWord = arr.get(nextInt);
}
String realdefn = dictionary.get(nextWord);
List<String> options = new ArrayList<>(dictionary.values());
options.remove(realdefn);
Collections.shuffle(options);
options = options.subList(0, 3);
options.add(realdefn);
Collections.shuffle(options);
word = (TextView) findViewById(R.id.word);
word.setText(nextWord);
//the listview, onClick of it is on onCreate
ListView list = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
options
);
list.setAdapter(adapter);
}
//checks if the user clicked correct answer or not it too works file
private void checkCorrect(String defn) {
TextView word = (TextView) findViewById(R.id.word);
score = (TextView) findViewById(R.id.score);
if (defn.equals(dictionary.get(word.getText()))) {
sc++;
score.setText("Score: " + sc);
toast("Nice One");
} else {
sc--;
score.setText("Score: " + sc);
toast("booooo!");
}
resetWord();
}
//To save the variable sc when performing rotation but not working,sc
//getting
//set to zero after rotation
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("sc", sc);
}
//this may be the reason of the problem to the world either
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
sc = savedInstanceState.getInt("sc");
}
//onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_the_game);
setTraceLifecycle(true);//library function that generates Log
//nothing to do with app, just displays the activity life cycle
dictionary = new TreeMap<>();
arr = new ArrayList<String>(dictionary.keySet());
sc = 0;
readFileData();//read file data into the dictionary
resetWord();//reset word
//setting the onClick for the List works fine
ListView list = (ListView) findViewById(R.id.list);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String defn = parent.getItemAtPosition(position).toString();
checkCorrect(defn);
}
});
//plays the song Makhana, nice song must listen :)
//works fine
mp = MediaPlayer.create(this, R.raw.recordings);
mp.start();
}
//the layout of this activity has a button to other activity called AddWord
//onResume when you return from that activity, works fine
#Override
protected void onResume() {
super.onResume();
mp.start();
}
//onPause when goning from this activity to AddWord, this too works fine
#Override
protected void onPause() {
super.onPause();
mp.pause();
}
//this directs to AddWord, attached with a button, works fine
public void addAWordClick(View view) {
Intent intent = new Intent(this, AddWord.class);
startActivity(intent);
}
}
The game is something like the program reads from the files two things: words and their meanings, the word and 4 options are then displayed and if you choose correct one your score increases, else decreases. This score is saved in the variable sc. I wished to preserve this variable when did screen rotation. But this does not seem to happen
I also tried:
I tried removing onRestoreInstanceState and changed the code
arr = new ArrayList<String>(dictionary.keySet());
sc = savedInstanceState.getInt("sc",0);// previosly sc=0
readFileData();
but that generate an error
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String, int)' on a null object reference
I then updated the code in onCreate to this
if(savedInstanceState!=null)
sc = savedInstanceState.getInt("sc",0);
else
sc = 0;
this didn't returned any error but still after rotation sc is getting set to zero again
It's not that it's not working, but that onRestoreInstanceState() is called after onStart() which is called after onCreate().
You do all your processing in onCreate() and you only store sc in OnRestoreInstanceState() while onCreate() has sc = 0;
This will cause all that processing you're doing in onCreate() to use the 0 value instead of the sc value you saved. Because it hasn't reached the step in the Activity Lifecycle where it fetches your sc value.
Use sc = savedInstanceState.getInt("sc", 0); instead of sc = 0 in your onCreate() method. You can get rid of the onRestoreInstanceState() method.
This way, if you previously saved sc through onSaveInstanceState(), you will be able to get that value in your onCreate(). If you didn't save it, it'll use the default value of 0.
Edit:
Check to see if savedInstanceState is null, because it will be null if nothing was passed in from onSaveInstanceState() which normally happens on the first run.
arr = new ArrayList<String>(dictionary.keySet());
sc = savedInstanceState==null ? 0 : savedInstanceState.getInt("sc", 0);
readFileData();//read file data into the dictionary
I have an app on Google Play that works on my phone when using it as a remote testing device but when I upload it to the Play Store and then download it onto my phone it wont work it fails to transmit any packets.
See code below, I dont know what the problem is i've been scratching my head all day perhaps a permissions issue?
package com.example.dale.whatismyip;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* Created by Dale on 22/01/2017.
*/
public class PingActivity extends AppCompatActivity
{
private EditText pingEdit;
private String pingVal;
private TextView finalResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ping);
finalResult = (TextView) findViewById(R.id.result);
pingEdit = (EditText) findViewById(R.id.editText2);
final Button button = (Button) findViewById(R.id.button5);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finalResult.setText("");
pingVal = pingEdit.getText().toString();
if(pingVal.contains(".") && pingVal.length() > 6)
{
PingTest runner = new PingTest();
runner.execute();
}
else
{
finalResult.setText("Invalid Address");
}
}
});
}
private class PingTest extends AsyncTask<String, String, String>
{
private String res;
#Override
protected String doInBackground(String... strings) {
try {
boolean sudo = false;
String cmd = "/system/bin/ping -c 4 -w 4 " + pingVal;
Process p;
if(!sudo)
p= Runtime.getRuntime().exec(cmd);
else{
p= Runtime.getRuntime().exec(new String[]{"su", "-c", cmd});
}
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s;
res = "";
while ((s = stdInput.readLine()) != null) {
// CODE TO DO - create an array and populate it
System.out.println(res += s + "\n");
}
p.destroy();
return res;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
// CODE TO DO - pass this method both an array of type string and a string
// then do a while loop through it whilst the array is populated and set the value of the textview to the strings
finalResult.setText(result);
}
}
}
Issue sorted.
The code itself was fine but the power saving feature on android stops the ping functionality as it disables background network usage.
Okay this is such a suggestion but are you testing your phone through a computer? is the phone connected through a usb to a computer?
and could you print a toast to see what's going on in doInBackground
I can't find anything wrong in your code.
I'm trying to make a simple dictionary which searches the words from txt file. I created the txt file and stored some English words. I want to write the word to EditText. Then, this word will be found and displayed on the TextView. Here is my code. It displays the whole txt file. How can i find the specific word ?
public class MainActivity extends Activity {
//creating variables
TextView myText;
EditText myEdit;
Button myButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializing the TextView EditText and Button
myText=(TextView) findViewById(R.id.idTextView);
myEdit=(EditText) findViewById(R.id.idEditText);
myButton=(Button) findViewById(R.id.idButton);
myButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String saveData=myEdit.getText().toString();
try{
myText.setText(readfile());
}catch(IOException e){
e.printStackTrace();
}
}
});
}
private String readfile()throws IOException {
String str="";
InputStream is = getResources().openRawResource(R.raw.translate);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line=reader.readLine();
while (line!=null)
{
str = str + line + "\n";
line = reader.readLine();
}
reader.close();
return str;
}
}
It all depends on how your readFile() is implemented. I suggest that you modify it to accept a String parameter. That way, it will search for that word in the file and return its meaning as another String that you can assign to TextView via setText()
myText.setText(readFile(saveData)));
is how the suggested implementation would look like.
Inside this method, when you read the file line-by-line, check if the String you just read from the file contains the required word. This can be done using the contains() method.
Think you're after a simple contains() check:
String fileText = readFile();
Boolean textFound = fileText.contains(saveData);
If that boolean is true, then you would display the value of saveData in the box. You could put this operation in a loop and search for multiple words as well if you wanted.
I'm totally new to this and am trying to figure out how to actually show the result of this little function in the layout of android. Have been searching and searching and I can't figure out exactly what it requires.
package com.example.proyectoparteb;
import java.io.IOException;
import java.io.RandomAccessFile;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
readUsage();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private float readUsage() {
try {
RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
String load = reader.readLine();
String[] toks = load.split(" ");
long idle1 = Long.parseLong(toks[5]);
long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
+ Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
try {
Thread.sleep(360);
} catch (Exception e) {}
reader.seek(0);
load = reader.readLine();
reader.close();
toks = load.split(" ");
long idle2 = Long.parseLong(toks[5]);
long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4])
+ Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
return (float)(cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));
} catch (IOException ex) {
ex.printStackTrace();
}
return 0;
}
}
Well, kind of a vague question but here is an example of something you could do.
Add a TextView to your layout in your main_activity.xml or whatever you have named it.
Set the id as #+id/myTextView.
In your code, import the TextView widget with:
import android.widget.TextView;
Then initialize it in your method:
TextView cpu = (TextView) findViewById(R.id.myTextView);
and set the text to something:
cpu.setText(readUsage().toString());
There you go. As with any language make sure you play around with stuff to learn it. You can use the eclipse graphical editor to add widgets and change properties like text size and colour etc.
I am a total newbie when it comes to both java and android coding. However, I am trying to piece together a simple notepad widget and app. It's basically a widget which displays the note text in a textView and an activity which can be loaded by tapping the widget. In the activity I have an EditText and two buttons - one to save the note text and one to cancel and close the activity.
An example of note-text entered in the EditText could be:
Buy milk
Kiss girlfriend
Bother Snape
When I save my note data from the activity, it saves my note data to an internal storage file. It then updates the widget and here my note-text is shown WITH linebreaks. But if I then open my activity to edit the text it loads the note-text as a single line file and not a multiline file.
Do any of you guys have suggestions for what I could do to load my note-data as multiline text with linebreaks?
Here's my activity code:
package dk.mfoller.android.basicnote;
import android.app.Activity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.Toast;
import android.widget.EditText;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import java.io.*;
public class BasicNoteActivity extends Activity {
/** Called when the activity is first created. */
private Button saveBtn;
private Button cancelBtn;
private EditText inputTxt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Defines objects
saveBtn = (Button) findViewById(R.id.basicNoteActivity_save);
cancelBtn = (Button) findViewById(R.id.basicNoteActivity_cancel);
inputTxt = (EditText) findViewById(R.id.basicNoteActivity_input);
// Calls a function to update/replace the displayed note text
readNoteData();
// Creates event handler for the save-button
saveBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Calls a function to write to a file
writeToFile();
// Updates the displayed text in the widget
String noteinput = inputTxt.getText().toString();
RemoteViews views = new RemoteViews("dk.mfoller.android.basicnote", R.drawable.main_widget);
views.setTextViewText(R.id.basicNoteWidget_notetext, noteinput);
// Updates the actual widget - NOTE: This updates ALL instances of the widget
ComponentName cn = new ComponentName(getBaseContext(), BasicNoteWidget.class);
AppWidgetManager.getInstance(getBaseContext()).updateAppWidget(cn, views);
}
});
// Creates event handler for the cancel-button
cancelBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
// A function to write to a file
protected void writeToFile() {
String FILENAME = "basicNote_data";
String noteinput = inputTxt.getText().toString();
try {
FileOutputStream fos = openFileOutput(FILENAME, MODE_PRIVATE);
//noteinput.replace("\\r", "\n");
fos.write(noteinput.getBytes());
fos.close();
// Displays a popup
Toast.makeText(this, "Note saved!", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// A function to read from a file on load
protected void readNoteData() {
String FILENAME = "basicNote_data";
try {
FileInputStream fis = openFileInput(FILENAME);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
// How do I make this load as multiline text?!?!
String line = null;
String output = "";
while((line = br.readLine()) != null) {
output += line;
}
// Updates/replaces the displayed note text
if(output != "") {
inputTxt.setText(output);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thanks in advance! ..oh, and please be very specific. Like I said: I'm a total newbie :)
The readLine() call does not include the end-of-line characters.
Quickest solution is to change the read loop in readNoteData:
while((line = br.readLine()) != null) {
output += line + "\n";
}
You could also just read in the entire file and skip that step, but get this working first.
See the BufferedReader.readLine() docs for info.