Text Resources in Android sdk - java

I have book with lessons about android . Now i realize help screen when i have many text . In book type about text . that android sdk can use txt files with many text . and in book typed code but when im use him , it doesent work (my app launch but i dont have any text on screen ) what's wrong? Help with right variant . my code :
package com.lineage.goddess;
import java.io.InputStream;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class LineageHelpActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.help);
openRawResource();
InputStream iFile = getResources().openRawResource(R.raw.lineagehelp);
TextView helpText =(TextView) findViewById(R.id.TextView_HelpText);
String strFile = inputStreamToString(iFile);
helpText.setText(strFile);
}
private String inputStreamToString(InputStream iFile) {
// TODO Auto-generated method stub
return null;
}
private void openRawResource() {
// TODO Auto-generated method stub
}
}

Well... for one, you are returning null from inputStreamToString(...). You need to implement it correctly before you can expect it to return anything.

change
private String inputStreamToString(InputStream iFile) {
// TODO Auto-generated method stub
return null;
}
with
private String inputStreamToString(InputStream iFile)
{
Writer writer = new StringWriter();
if(iFile!=null)
{
char[] buffer = new char[1024];
try{
Reader reader = new BufferedReader(
new InputStreamReader(iFile, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} catch (UnsupportedEncodingException e) {
return e.toString();
} catch (IOException e) {
return e.toString();
}finally
{
try {
iFile.close();
} catch (IOException e) {
return e.toString();
}
}
}
String result = writer.toString();
return result;
}

Related

Using an async task to download xml into String[]

So I'm trying to get an AsyncTask to go out and grab three different XML files. The issue is, I don't know how to then bring them back out of the AsyncTask
There is the GetXML Class:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import android.os.AsyncTask;
public class GetXML extends AsyncTask<String,Integer,String[]> {
#Override
protected String[] doInBackground(String... params) {
// TODO Auto-generated method stub
String[] retreiver = new String[3];
try {
retreiver = getXMLs();
return retreiver;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0;i<retreiver.length;i++){
retreiver[i]="<object_list><object><title>ERROR</title></object></object_list>";
}
return retreiver;
}
private static String[] getXMLs() throws Exception {
String[] urls = new String[3];
urls[0] = "http://www.parkland.hostoi.com/XML_Files/indoor.xml";
urls[1] = "http://www.parkland.hostoi.com/XML_Files/outdoor.xml";
urls[2] = "http://www.parkland.hostoi.com/XML_Files/events.xml";
BufferedReader reader = null;
URLConnection uc = null;
int i = 0;
for(i=0;i<urls.length;i++){
try {
URL url = new URL(urls[i]);
uc = url.openConnection();
uc.connect();
reader = new BufferedReader(new InputStreamReader(uc.getInputStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
urls[i]= buffer.toString();
}
finally {
if (reader != null)
reader.close();
}
}
return urls;
}
And then... what's next? Currently I have this bit on my Main Activity and I know it is the part causing the problems:
String[] xmls = new String[3];
GetXML taskA = new GetXML();
try {
xmls = taskA.get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
But all this does is causes a crash or a timeout or something.... No errors are showing up in LogCat.
I just don't know. This is my first android project, and it is killing me.
You can try this:
String[] xmls = new String[3];
GetXML taskA = new GetXML();
try {
xmls = taskA.execute().get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Your Task not execute because you never executed,
Need to call
taskA .execute();
Refer Below:
In main Activity:
GetXML taskA = new GetXML();
taskA.execute();
Your AsyncTask is:
public class GetXML extends AsyncTask<String,Integer,String[]> {
#Override
protected String[] doInBackground(String... params) {
// TODO Auto-generated method stub
String[] retreiver = new String[3];
try {
retreiver = getXMLs();
return retreiver;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0;i<retreiver.length;i++){
retreiver[i]="<object_list><object><title>ERROR</title></object></object_list>";
}
return retreiver;
}
private String[] getXMLs() throws Exception {
String[] urls = new String[3];
urls[0] = "http://www.parkland.hostoi.com/XML_Files/indoor.xml";
urls[1] = "http://www.parkland.hostoi.com/XML_Files/outdoor.xml";
urls[2] = "http://www.parkland.hostoi.com/XML_Files/events.xml";
BufferedReader reader = null;
URLConnection uc = null;
int i = 0;
for(i=0;i<urls.length;i++){
try {
URL url = new URL(urls[i]);
uc = url.openConnection();
uc.connect();
reader = new BufferedReader(new InputStreamReader(uc.getInputStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
urls[i]= buffer.toString();
}
finally {
if (reader != null)
reader.close();
}
}
return urls;
}
#Override
protected void onPostExecute(String[] result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String[] xmls = result;
}
}
Result is populated in onPostExecute
Require Permission in manifest:
<uses-permission android:name="android.permission.INTERNET"/>
A nice example can be found in the docs.
You need to call the execute() method on your task, not get().
I'd also recommend at least implementing the onPostExecute() method as well in your AsyncTask.

Shared Preference VS Context?

I'm not that much experienced in Android, so every piece of code I have written so far was very simple. Now I need to implement a localization and navigation application, so I need to break my code into modules so that I can change each component alone. I have some variables that I need to share them between different classes. I used static variables but I read in some posts here that static variables are not preferred. Then I found some other posts talking about Context. So I created a class named Globals and I added the following lines in my Manifest file:
<application android:name="com.example.smartnav.Globals"
package="com.example.smartnav"
android:icon="#drawable/ic_launcher"
android:allowBackup="true"
android:label="#string/app_name"/>
And here is the Globals Class :
package com.example.smartnav;
import java.util.List;
import android.net.wifi.ScanResult;
import android.app.Application;
public class Globals extends Application {
private Boolean Scanning=false;
private String Logname;
private int interval;
private int numOfScans;
private List<ScanResult> result;
//getters
public Boolean getScannig(){
return Scanning;
}
public int getInterval()
{
return interval;
}
public int getScans()
{
return numOfScans;
}
public List<ScanResult> getRes()
{
return result;
}
public String getLog()
{
return Logname;
}
//setter
public void setScanning(Boolean s){
Scanning= s;
}
public void setRes(List<ScanResult> res)
{
result =res;
}
public void setInterval(int I)
{
interval = I;
}
public void setScans(int S)
{
numOfScans=S;
}
public void setLog(String s)
{
Logname= s;
}
}
Now I have two questions, the first one is that my application keeps crashing whenever I try to use the Globals class, here is the code: Did I use context incorrectly?
public class MainActivity extends Activity {
private Context context;
public WifiManager Wifi;
private WifiReceiver receiverWifi;
private IntentFilter filter;
private List<ScanResult> result;
private File AppDir;
private static String filename;
private File file;
private FileWriter writer;
private Globals AppState ;
private int Interval;
private int numOfScans;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Main ","activity created");
//
AppState = ((Globals)getApplicationContext());
context= this;
Wifi=(WifiManager) getSystemService(Context.WIFI_SERVICE);
receiverWifi = new WifiReceiver();
filter= new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(receiverWifi, filter);
Log.d("Main ","wifi registered");
// create the application directory
AppDir = new File(Environment.getExternalStorageDirectory()+"/SmartNavi/Log");
if(AppDir.isDirectory())
{
filename=Environment.getExternalStorageDirectory()+"/SmartNavi/Log/log.txt";
file = new File(filename);
if(!file.exists())
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
else
{
Date d= new Date();
filename=Environment.getExternalStorageDirectory()+"/SmartNavi/Log/log"+d.getTime()+".txt";
file = new File(filename);
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
AppDir.mkdirs();
filename=Environment.getExternalStorageDirectory()+"/SmartNavi/Log/log.txt";
file = new File(filename);
if(!file.exists())
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
else
{
Date d= new Date();
filename=Environment.getExternalStorageDirectory()+"/SmartNavi/Log/log"+d.getTime()+".txt";
file = new File(filename);
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//setting pars
Interval=250;
numOfScans=4;
AppState.setInterval(Interval);
AppState.setScans(numOfScans);
AppState.setLog(filename);
Wifi.startScan();
try {
writer = new FileWriter(file, true);
writer.append("Smart Navigation. \n");
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// AsyncScanning.AsyncScan();
}//on create
#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;
}
class WifiReceiver extends BroadcastReceiver {
public void onReceive(Context c, Intent intent) {
result=Wifi.getScanResults();
// AppState.setRes(result);
try {
writer = new FileWriter(file, true);
writer.append(result.size()+" s \n");
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//end of on receive
}// end of class
} // end of smartNav
My last question is this : I have read on some answers here that if my application becomes a background process then all the data in the context will be set to null, and I will lose my context. Is there is any method to overcome this point? or should I switch to SharedPreferences ?
Edit :Here is the output of Logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.smartnav/com.example.smartnav.MainActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to com.example.smartnav.Globals
Now I have two questions, the first one is that my application keeps crashing whenever I try to use the Globals class, here is the code: Did I use context incorrectly?
you should use getApplication() method for that, or make your application class singleton, so you would call Globals.getInstance().getMyVariable() etc.
My last question is this : I have read on some answers here that if my application becomes a background process then all the data in the context will be set to null, and I will lose my context. Is there is any method to overcome this point? or should I switch to SharedPreferences ?
if your app becomes background then Android is more likely to kill your app, and this way also destroy all your static objects. Inside your Globals class you should not store your data in static variables but rather in some persistant storage - if its small then use SharedPreferences, if its large then you can store it in json and save to application memory, or use sqlite db.

Convert Text File to String in java

i have a written a code to send a text file by converting it into string and sending it into a web service. Please can someone tell me other available methods for sending the string as stream to Web Service.
public class MainActivity extends Activity {
Button b1;
String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
File upfile=new File("sdcard/text/testfile.txt");
try {
FileInputStream fin=new FileInputStream(upfile);
byte[] buffer= new byte[(int)upfile.length()];
new DataInputStream(fin).readFully(buffer);
fin.close();
s=new String(buffer,"UTF-8");
System.out.print(buffer);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, s, 20).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
try this.
public void mReadJsonData() {
try {
File f = new File("sdcard/text/testfile.txt");
FileInputStream is = new FileInputStream(f);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String text = new String(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Use this code to read the data from file and get it into string and do your process ahead according to your need--
File upfile=new File("sdcard/text/testfile.txt");
try {
final BufferedReader reader = new BufferedReader(new FileReader(upfile));
String encoded = "";
try {
String line;
while ((line = reader.readLine()) != null) {
encoded += line;
}
}
finally {
reader.close();
}
System.out.print(encoded);
}
catch (final Exception e) {
}

Reading from a text file in android

I'm trying to read a random line from a file. My code doesn't have error, just comes up with a force close as soon as it runs in the emulator and I can't work out why!
public class filereader extends Activity {
TextView t = (TextView)findViewById(R.id.text);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
Scanner s = new Scanner(getResources().openRawResource(R.raw.lev1)); {
try {
while (s.hasNext()) {
String word = s.next();
t.setText(word);
}
}
finally {
s.close();
}
}
}
TextView t = (TextView)findViewById(R.id.text);
you can not run findViewById until the setContentView has been called:
TextView t = null; #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = (TextView)findViewById(R.id.text);
}
please be sure that you declare text inside the main.xml
do this
BufferedReader myReader = null;
try
{
fIn = openFileInput("customer_number.txt");
myReader = new BufferedReader(new InputStreamReader(fIn));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String aDataRow = "";
//String aBuffer = "";
try
{
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
// TO display Whole Data of File
Toast.makeText(getBaseContext(),aBuffer,Toast.LENGTH_SHORT).show();
}
// To display Last Entered Number
Toast.makeText(getBaseContext(),last_number,Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public void readfromfile(){
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
String s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
It will read the text file named "mytext.txt" string by string and store it by appending it to string variable s. So the variable "s" contains final string taken from file.

Service takes too much memory

I have a service that extracting html code from an URL, converting it to text only (with Jsoup) and then checks something on the string, and if some conditions are true it launches a notification and writes something to a file.
As far as I know, this kind of service shouldn't take much memory, and in Watchdog, it takes ~65 MB, and it is way too much. It takes more than any other process (even more than tw launcher and Android System).
I would like you to tell me what have I done wrong.
Heres my service class:
public class NotifyService extends Service
{
private int number=0;
private Timer timer=new Timer();
private long INTERVAL=1*1000*60*60;//1 hour
public static String Oldhtml;
public static String Newhtml;
public static String currHtml;
// hooks main activity here
/*
* not using ipc...but if we use in future
*/
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
super.onCreate();
_startService();
Log.w("myApp", "START");
}
#Override
public void onDestroy()
{
super.onDestroy();
_shutdownService();
Log.w("myApp", "STOPPED");
}
/*
* starting the service
*/
private void _startService()
{
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
try {
doServiceWork();
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Thread.sleep(INTERVAL);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
},0,INTERVAL);
;
}
/*
* start the processing, the actual work, getting config params, get data from network etc
*/
private void doServiceWork() throws ClientProtocolException, IOException
{
String FILENAME="blichData";
String info=null;
String classLetter = null,classNum1=null;
int classNum = 0;
try{
FileInputStream fis=openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray)!=-1)
{
info = new String(dataArray);
}
classLetter = info.substring(0, info.lastIndexOf(" "));
classNum1 =info.substring(info.lastIndexOf(" ")+1);
classNum=Integer.parseInt(classNum1);
fis.close();
}catch (Exception e){
}
if (classLetter!=null && classNum1!=null) {
Oldhtml=readHTMLfromFile();
if (GetHTML.isHavingChanges(classLetter,classNum))
{
myNotify();
writeHTMLtoFile(currHtml);
/*
try {
String data= "false";
FileOutputStream fos = openFileOutput("blichService", Context.MODE_PRIVATE);
fos = openFileOutput("blichService",Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
}
catch (Exception e) {}
*/
}
}
;
}
/*
* shutting down the service
*/
private void _shutdownService()
{
if (timer != null) timer.cancel();
Log.i(getClass().getSimpleName(), "Timer stopped...");
}
public void writeHTMLtoFile(String html) {
try {
String FILENAME = "blichNotifyData";
String data= html;
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos = openFileOutput(FILENAME,Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
}
catch (Exception e){}
}
public String readHTMLfromFile() {
String FILENAME = "blichNotifyData";
String info="";
try{
FileInputStream fis=openFileInput(FILENAME);
if (fis.available()>0)
{
byte[] dataArray = new byte[fis.available()];
while(fis.read(dataArray)!=-1)
{
info = new String(dataArray);
}
fis.close();
}
else {
Oldhtml="null";
}
}
catch (Exception e) {}
return info;
}
public void myNotify()
{
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent= new Intent (this,SchoolBlichActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
String body = " בליך";
String title = "ישנם שינויים חדשים!";
Notification n =new Notification(R.drawable.table, body, System.currentTimeMillis());
n.flags |=Notification.FLAG_AUTO_CANCEL;
n.setLatestEventInfo(getApplicationContext(), title, body, pi);
n.defaults = Notification.DEFAULT_ALL;
number++;
n.number=number;
nm.notify(0,n);
}
}
And if it is needed, the HTML extracting class:
public class GetHTML {
public static boolean isHavingChanges(String classLetter,int classNum) throws ClientProtocolException, IOException {
int classLetterCode = 0;
int timeTableCode=1;
if (classLetter.equals("ט"))
classLetterCode=0;
else if (classLetter.equals("י"))
classLetterCode=1;
else if (classLetter.equals("יא"))
classLetterCode=2;
else if (classLetter.equals("יב"))
classLetterCode=3;
switch(classLetterCode)
{
case 0:
if (classNum>=1 && classNum<=7)
timeTableCode=1;
else if (classNum>7 && classNum<=14)
timeTableCode=2;
break;
case 1:
if (classNum>=1 && classNum<=7)
timeTableCode=3;
else if (classNum>7 && classNum<=14)
timeTableCode=4;
break;
case 2:
if (classNum>=1 && classNum<=7)
timeTableCode=5;
else if (classNum>7 && classNum<=14)
timeTableCode=6;
break;
case 3:
if (classNum>=1 && classNum<=7)
timeTableCode=7;
else if (classNum>7 && classNum<=14)
timeTableCode=8;
break;
}
String url = "http://blich.iscool.co.il/DesktopModules/IS.TimeTable/MainScreen.aspx?pid=17&mid=6264&page="+timeTableCode+"&msgof=0&static=1";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
html = Jsoup.parse(html).text();
if (NotifyService.Oldhtml.equalsIgnoreCase(html)) {
return false;
}
if (timeTableCode%2!=0){
for (int i=0;i<8;i++) {
if (!html.contains(i+" "+i)) {
NotifyService.currHtml=html;
return true;
}
}
}
if (timeTableCode%2==0) {
for (int i=8;i<15;i++) {
if (!html.contains(i+" "+i)) {
NotifyService.currHtml=html;
return true;
}
}
}
return false;
}
}
Ignore the foreign language. xD
I just want to understand what have I done wrong?
Thanks
While I cannot tell out-of-the-box what portion of your code is problematic, you may try to analyze the memory usage through a heap dump taken with DDMS using Eclipse MAT. You will need to use the hprofconv tool to convert your Android heap dump into a format that MAT understands.
To get the HPROF Heap Dump, open the Dalvik Debug Monitor (DDMS), connect it you your emulator, select the process of your application and hit the "Dump HPROF file" icon.

Categories

Resources