Showing result in Android layout - java

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.

Related

Ping app not working when added to Google Play

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.

How to make a random number only once in an android app?

I'm developing a "guess the number" app, it generates a random number between 1 and 10,000 and you have to try guessing, it will tell you if your prediction it is too big , etc
But when you press the button to probe your number, it generates a new random number every time you press the button.Keep in mind i'm a newbie so i'm learning java for android, but i want to know how to make this simple app.
Here's my code:
package com.boodle.guessthenumber;
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.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void guess (View view){
EditText textguess = (EditText) findViewById ( R.id.textguess );
TextView resulta = (TextView) findViewById(R.id.resulto);
String guessStr = textguess.getText().toString();
int theGuess = Integer.parseInt(guessStr);
int rand = (int) (Math.random()*10000+1);
if (theGuess > rand) {
resulta.setText(textguess.getText() + " is too big" );
}
if (theGuess < rand) {
resulta.setText(textguess.getText() + " is too small" );
}
if (rand == theGuess){
resulta.setText(textguess.getText() + " is the answer" );
}
}
}
Create rand as a member variable in your class:
public class MainActivity extends ActionBarActivity {
int rand;
initialize in onCreate():
rand = (int) (Math.random()*10000+1);
remove the initialization in your guess() function:
// not needed anymore:
// int rand = (int) (Math.random()*10000+1);
To make the number persist during orientation changes, add this code to your Activity:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("rand", rand);
super.onSaveInstanceState(savedInstanceState);
}
and then in onCreate() change your random number generation code to this:
if (savedInstanceState != null)
rand = savedInstanceState.getInt("rand");
else
rand = (int) (Math.random()*10000+1);
After you generate the number you have to store it in a persistent storage, for which you have many options: SharedPreferences (which can be passed between activities), a file, SQLiteDatabase...
When the activity starts, only if the number is not there - generate it!
The solution would be to create your random number in onCreate such that it is only created once and then simply access that variable in your guess method. Modify your code as follows:
public class MainActivity extends ActionBarActivity
{
private int rand;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
rand = (int) (Math.random()*10000+1);
}
// rest of code...
And then in guess remove the initialization and simply access the variable by name:
public void guess (View view)
{
// rest of code...
//int rand = (int) (Math.random()*10000+1);
if (theGuess > rand) {
resulta.setText(textguess.getText() + " is too big" );
}
// rest of code...
}
Also, just as a note, it is not necessary to post all the import statements and other similar code. Only posting the code relevant to your issue is the best way to invite concise answers.
The following solution will generate the number when the activity is started and the number will NOT change when the user rotates the screen. It will also make the activity a little bit more effective.
public class MainActivity extends ActionBarActivity {
TextView mResult;
EditText mTextGuess;
private int mNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
// you find your views in onCreate once, they don't change, it's effective
mResult = (TextView) findViewById(R.id.resulto);
mTextGuess = (EditText) findViewById(R.id.textguess);
// BRO-TIP: Google "Butterknife".
// Now you need to initialize the random number
// BUT you want it to stay the same when user rotates the screen, right?
if (savedInstanceState == null) {
// when the user first opens the app, generate new number
mNumber = (int) (Math.random()*10000+1);
} else {
// otherwise load the previously generated number from saved state
mNumber = savedInstanceState.getInt("mNumber");
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// here you save the number across orientation changes
outState.putInt("mNumber", mNumber);
}
public void guess(View v) {
int theGuess = Integer.parseInt(mTextGuess.getText().toString());
// else-if is better for you: when the first is true, you don't need to check the others and so on...
if (theGuess > rand) {
mResult.setText(textguess.getText() + " is too big" );
} else if (theGuess < rand) {
mResult.setText(textguess.getText() + " is too small" );
} else if (rand == theGuess){
mResult.setText(textguess.getText() + " is the answer" );
}
}
}

Android - cannot scroll up

First off, I first laid eyes on Java three weeks ago so bear with me if this code is terrible. It's an assignment for school that I am to build on a prototyped app and give it a UI, so the Adapter is basically all I've done to this.
My problem being that as soon as I touch the scroll, I get thrown to the bottom of the list and can't scroll back up without getting pushed back down.
/**
* VaxjoWeather.java
* Created: May 9, 2010
* Jonas Lundberg, LnU
*/
package dv106.weather;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
/**
* This is a first prototype for a weather app. It is currently
* only downloading weather data for Växjo.
*
* This activity downloads weather data and constructs a WeatherReport,
* a data structure containing weather data for a number of periods ahead.
*
* The WeatherHandler is a SAX parser for the weather reports
* (forecast.xml) produced by www.yr.no. The handler constructs
* a WeatherReport containing meta data for a given location
* (e.g. city, country, last updated, next update) and a sequence
* of WeatherForecasts.
* Each WeatherForecast represents a forecast (weather, rain, wind, etc)
* for a given time period.
*
* The next task is to construct a list based GUI where each row
* displays the weather data for a single period.
*
*
* #author jlnmsi
*
*/
public class VaxjoWeather extends ListActivity {
//private InputStream input;
private WeatherReport report = null;
//private ArrayList<WeatherForecast> forecastList = new ArrayList<WeatherForecast>();
private WeatherAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
adapter = new WeatherAdapter(this);
setListAdapter(adapter);
//getListView().setTranscriptMode(ListView.TRANSCRIPT_MODE_DISABLED);
try {
URL url = new URL("http://www.yr.no/sted/Sverige/Kronoberg/V%E4xj%F6/forecast.xml");
AsyncTask task = new WeatherRetriever().execute(url);
} catch (IOException ioe ) {
ioe.printStackTrace();
}
//adapter.notifyDataSetChanged();
}
private void PrintReportToConsole() {
if (this.report != null) {
/* Print location meta data */
//System.out.println(report);
/* Print forecasts */
int count = 0;
for (WeatherForecast forecast : report) {
count++;
adapter.add(forecast);
}
}
else {
System.out.println("Weather report has not been loaded.");
}
//adapter.notifyDataSetChanged();
}
private class WeatherRetriever extends AsyncTask<URL, Void, WeatherReport> {
protected WeatherReport doInBackground(URL... urls) {
try {
return WeatherHandler.getWeatherReport(urls[0]);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected void onProgressUpdate(Void... progress) {
}
protected void onPostExecute(WeatherReport result) {
report = result;
PrintReportToConsole();
}
}
// custom ArrayAdpater to show, weather icon, temperature, and precipation.
class WeatherAdapter extends ArrayAdapter<WeatherForecast> {
public WeatherAdapter(Context context) {
super(context,R.layout.forecast);
}
#Override // Called when updating the ListView
public View getView(int position, View convertView, ViewGroup parent) {
View row;
if (convertView == null) { // Create new row view object
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.forecast,parent,false);
}
else // reuse old row view to save time/battery
row = convertView;
// TextView for Temperature
TextView temperature = (TextView)row.findViewById(R.id.temperature);
temperature.setText(Integer.toString(this.getItem(position).getTemp())+" °C");
// TextView for out Precipation.
TextView precipation = (TextView)row.findViewById(R.id.rain);
precipation.setText(String.valueOf(this.getItem(position).getRain())+" mm");
// Image Icon for forecast.
ImageView icon = (ImageView)row.findViewById(R.id.icon);
String iconPath = "ic_";
if (this.getItem(position).getWeatherCode() <= 9){
iconPath = iconPath+"0"+(Integer.toString(this.getItem(position).getWeatherCode()));
}
else {
iconPath = iconPath+(Integer.toString(this.getItem(position).getWeatherCode()));
}
int resId = getResources().getIdentifier(iconPath, "drawable", getPackageName());
// If the resource ID is invalid, as in the image not existing, we'll add the postfix for periods.
if (resId == 0){
// Set the icon image source dependent on period code given.
if(this.getItem(position).getPeriodCode() == 3){
iconPath = iconPath +"n";
}
else if (this.getItem(position).getPeriodCode() == 2){
iconPath = iconPath +"d";
}
else {
iconPath = iconPath +"m";
}
resId = getResources().getIdentifier(iconPath, "drawable", getPackageName());
icon.setImageResource(resId);
}
// Or if everything checked out, we'll just run with the resource ID and find our Icon.
else {
icon.setImageResource(resId);
}
return row;
}
}
}
I tried applying another standard arrayadapter and actually got the same unwanted scrolling results, so I got no idea what part it is I got issues with.
Way to do it is:
1: Place ListView in main.xml
2: In your Activity Make object of ListView like so -> private ListView listView; in onCreate connect it to the main.xml like this, listView = (ListView) R.id.listView1; // whatever it is called
3: next create an ArrayList:-> private ArrayList arrayWeather = new ArrayList();
4: fill the arraylist with weather data then finally create object of class you created and make it use your arraylist to display data.
Example:
public class ListUser extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
return arraylistData.size(); // the arraylist u created
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arraylistData.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return arraylistData.size();
}
#Override
public View getView(final int position, View v, ViewGroup parent) {
if(v == null){
LayoutInflater lf = (LayoutInflater) BuyPets.this.getSystemService( Context.LAYOUT_INFLATER_SERVICE);
v = lf.inflate(R.layout.forecast, null);
}
// setup here, done
return v;
}
}
Solution was found and apparently it had nothing to do with my code. Class suggested we'd use Intel x86 instead of ARM for our emulators. Running it with ARM scrolling work just as expected.

ArcGIS Runtime SDK for Android zooming to a feature from a spinner dropdown list

I am relatively new to Java and working with the ArcGIS Runtime SDK for Android. I am making an app where the user selects the parcel id from spinner list. If the user clicks on a 'ZOOM' button the map should zoom to the parcel that was selected. Here is my code:
package gist8010.main;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.esri.android.map.MapView;
import com.esri.android.map.ags.ArcGISDynamicMapServiceLayer;
import com.esri.android.map.ags.ArcGISTiledMapServiceLayer;
import com.esri.core.geometry.Envelope;
import com.esri.core.geometry.Point;
import com.esri.core.map.Feature;
import com.esri.core.map.FeatureResult;
import com.esri.core.tasks.query.QueryParameters;
import com.esri.core.tasks.query.QueryTask;
public class Spinner_WalkActivity extends Activity {
MapView mMapView;
Button mBtnZoom;
ArcGISDynamicMapServiceLayer mDynamicLayer;
Spinner mSpnParcels;
String mMapServiceURL = "http://indy14.athena.bcit.ca:8080/"
+ "esri_rest/services/gist_8010_test_ms/MapServer";
int mLotLayerID = 0;
String mLotLayerURL = mMapServiceURL + "/" + mLotLayerID;
String mLotNumColName = "PARCELS_ID";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** Allow querying on main thread */
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
/** Create spinner and button */
setMapView();
this.mBtnZoom = (Button) findViewById(R.id.btnZoom);
mBtnZoom.setOnClickListener(new OnClickListener() {
/** Upon click of zoom button, invoke th zoomtoFeature Method */
public void onClick(View v) {
zoomToFeature(v);
}
});
this.mSpnParcels = (Spinner) findViewById(R.id.spnParcels);
/** Add Layer to map */
mDynamicLayer = new ArcGISDynamicMapServiceLayer(mMapServiceURL);
mMapView.addLayer(mDynamicLayer);
QueryParameters qryLotNums = new QueryParameters();
qryLotNums.setReturnGeometry(false);
qryLotNums.setOutFields(new String[] { mLotNumColName });
qryLotNums.setWhere(mLotNumColName + ">0");
com.esri.core.tasks.query.QueryTask qtask = new com.esri.core.tasks.query.QueryTask(
mLotLayerURL);
try {
FeatureResult fSet = qtask.execute(qryLotNums);
ArrayList<String> listOfLotsNums = new ArrayList<String>();
Feature tmpFeat;
for (Object featAsObj : fSet) {
tmpFeat = (Feature) featAsObj;
listOfLotsNums.add(tmpFeat.getAttributeValue(mLotNumColName)
.toString());
}
ArrayAdapter<String> adtTmp = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item,
listOfLotsNums);
mSpnParcels.setAdapter(adtTmp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// of catch
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
mMapView.pause();
}
#Override
protected void onResume() {
super.onResume();
mMapView.unpause();
}
// =============================================================================
// Zooms the map the the MBR of the feature selected in the spinner
// import android.view.View;
// =============================================================================
public void zoomToFeature(View v) {
QueryParameters zoomQuery = new QueryParameters();
zoomQuery.setReturnGeometry(true);
zoomQuery.setOutFields(new String[] { mLotNumColName });
zoomQuery.setWhere(mLotNumColName + "=" + mSpnParcels.getSelectedItem());
QueryTask qtask = new QueryTask(mLotLayerURL);
try {
FeatureResult fset = qtask.execute(zoomQuery);
Feature tmpFeat = (Feature) fset.iterator().next();
Envelope envelope = new Envelope();
envelope.queryEnvelope((Envelope) tmpFeat.getGeometry());
getMapView().setExtent(envelope);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// =============================================================================
// getter for the main map
// =============================================================================
private MapView getMapView() {
// =============================================================================
// if MapView is underlined in red, change the name to match your
// MapView
// =============================================================================
return mMapView;
}
// =============================================================================
// setter for the main map
// =============================================================================
private void setMapView() {
// ========================================================================
// if mapView is underlined in red then sync class-level var names
// if R.id.map is underlined in red ensure that you added the xml
// fragment
// such as "MapView Generic" to a layout
// ========================================================================
mMapView = (MapView) findViewById(R.id.map);
}
}
After attempting to debug, I think my issue is with the Envelope class. The queryEnvelope method accepts a Envelope argument. As you can see, I cast the geometry of the Feature tmpFeat from a geometry type into a Envelope type.
When I run the application on my phone I get an System.Err in my log Cat saying:
java.lang.ClassCastException: com.esri.core.geometry.Polygon cannnot be cast to com.esri.core.geometry.Envelope
Am I doing the casting incorrectly? I cannot think of another way of linking my Envelope instance with the geometry of the feature class i want to zoom to.
Envelop is a child class of com.esri.core.geometry.Geometry, not vice versa. I guess this is why you fail when do the cast.
https://developers.arcgis.com/android/api-reference/reference/com/esri/core/geometry/Envelope.html
As it to your question, I guess envelop is not necessary to zoom to a feature. MapView.zoomToResolution(Point centerPt, double res) or zoomTo(Point centerPt, float factor) may be a better choice. You may find these sample codes helpful:
https://developers.arcgis.com/android/sample-code/geocoding/

Android - Retrieve data as multiline (i.e. with linebreaks) from internal storage datafile

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.

Categories

Resources