I have a little idea of the Utility Classes with a slight doubt on demand.
If I use a Utility class in my Application than to use that class in my main Activity do I have to create the object of that class or I can directly Import that class in my main activity?
I am Sorry if I am not making a clear sense.
In the nutshell, all I want to be clear about is that basically how can I use the utility class in my Main Activity?
Thanks,
david
It mainly depends on what your utility class does. But, most of the time, if you create an Utility class, you will want to create static methods and invoke them without creating an instance:
class MyUtilities{
public static String foo(String bar){
return bar.toUppercase;
}
}
Then, on your activity:
MyUtilities.foo("baz");
Of course, there are cases where you will want to create instance of a Utility class. For instance, if you have created a global Adapter which will be used by all your ListViews.
It heavily depends on what kind of utility you're referring to. There are
1) utility classes that implement static methods. In that case you just call them directly using class name
2) utility classes methods that are not static - requires creating and possibly initializing an instance of that class. Then the instance is used to call those methods.
3) utility classes that can be accessed thru Context. then you can call getApplicationContext() and then you can get access to the utility classes
public final class Utils
{
private Utils()
{
}
public static void makeToast(Context context, String text){
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
}
}
It's usually a class which only has static methods (possibly with a private constructor and marked abstract/final to prevent instantiation/subclassing). It only exists to make other classes easier to use - for example, providing a bunch of static methods to work with String values, performing extra actions which String itself doesn't support.
Utility classes generally don't operate on classes you have control over, as otherwise you'd usually put the behaviour directly within that class. They're not terribly neat in OO terms, but can still be jolly useful.
as answered by Jon Skeet
If the methods in your utility class are static then you can call them from your main activity. eg:
int i = Utility.RandInt();
If they are not static then you have to create an object:
Utility u = new Utility();
int i = u.randInt();
If your utility class is created in your Application then you can refer to it by first creating a getMethod in the application class, then going
Application mc = (Application) context.getApplicationContext();
mc.getUtilityClass().SomeMethod()
I dont know what yiur exact question is. But here is a code where I used Utility class in my activity. AnimationUtil is used to load animation onto a ImageView.
ImageView waitImg = (ImageView) findViewById(R.id.ImageView02);
Animation waitAnim = AnimationUtils.loadAnimation(this, R.anim.wait_rotate);
waitImg.startAnimation(waitAnim);
waitAnim.cancel();
waitAnim.reset();
public class Utils {
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public static void unlockScreenOrientation(Activity activity) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
public static void lockScreenOrientation(Activity activity) {
int currentOrientation = activity.getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_PORTRAIT)
{
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
else
{
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
// Get Http Post response
#Nullable
public static String getHttpResponse(String url, List<NameValuePair> nameValuePairs) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
UrlEncodedFormEntity entity;
try {
entity = new UrlEncodedFormEntity(nameValuePairs);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
String res = EntityUtils.toString(resEntity);
return res;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
public static JSONObject getJsonObjectFromXmlResponse(String xmlString) {
JSONObject objectJson = new JSONObject();
//JSONArray arrayJson = new JSONArray();
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(new StringReader(xmlString));
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String name;
switch (eventType) {
case XmlPullParser.START_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("string")) {
String yourValue = parser.nextText();
//arrayJson = new JSONArray(yourValue);
objectJson = new JSONObject(yourValue);
}
break;
}
eventType = parser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return objectJson;
}
}
Related
I Googled alot, but no chance for this.
For now, i a have an Inner AsyncTask class that i want to use the return values in the upper class.
And it successfully work, cause i have put a Log.e() and it shows my value, Here is my code :
public class Consume extends AsyncTask<Void, Void, Void> {
private List<LatLng> latLngs = new ArrayList<>();
private List<ContactModel> contacts = new ArrayList<>();
InputStream inputStream = null;
String result = "";
#Override
protected Void doInBackground(Void... params) {
String URL = "http://x.x.x.x/MYWCF/Service1.svc/Json/getContact";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
post.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(post);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncoding", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding", "Error converting result " + e.toString());
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
List<ContactModel> contactModels;
List<LatLng> myLatLngs = new ArrayList<>();
try {
JSONObject object = new JSONObject(result);
JSONArray jArray = object.getJSONArray("getContactResult");
Type listType = new TypeToken<List<ContactModel>>() {
}.getType();
contactModels = new Gson().fromJson(String.valueOf(jArray), listType);
setContacts(contactModels);
setContacts(contactModels);
for(ContactModel contactModel : contactModels) {
Double latitude = Double.valueOf(contactModel.getLatitude());
Double longitude = Double.valueOf(contactModel.getLongitude());
LatLng latLong = new LatLng(latitude, longitude);
myLatLngs.add(latLong);
}
setLatLngs(myLatLngs);
Log.e("SizeOfArray", myLatLngs.size()+"");
} catch (JSONException e) {
e.printStackTrace();
}
}
public void setContacts(List<ContactModel> contacts) {
this.contacts = contacts;
}
public List<ContactModel> getContacts() {
return contacts;
}
public void setLatLngs(List<LatLng> latLngs) {
this.latLngs = latLngs;
}
public List<LatLng> getLatLngs() {
return latLngs;
}
And in my Activity Class :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.osmdroid_map);
Consume consume = new Consume();
consume.execute();
When i run the app, cause of the line :
Log.e("SizeOfArray", myLatLngs.size()+"");
it returns me the correct int number of array size in logcat, But i want to use that in my App,
I even do all stuff in doInBackground method, and even make a static variable,
No chance.
Can any one give a real sample by my code?
Thx
As far as your AsyncTask class is an inner class. It can directly access objects of outer class.
Create an object of below at your outer class level.
List<LatLng> myLatLngs = new ArrayList<>();
And remove same from inner class so that single object instance will be their.
Another approach will be to use callback from your inner asyntask you need to have interface callback to outer class to start further process.
interface CallBack {
public void processingDone();
}
Consume consume = new Consume(new CallBack() {
#Override
public void processingDone(List<LatLng> mLatLngs) {
// Do your stuff here
}
});
consume.execute();
And inside your Consume constructor store callback to pass data back to outer class.
class Consume {
private Callback mCallback;
public Consume(Callback callback) {
mCallback = callback;
}
}
And from below link you can do
if (mCallback != null) {
mCallback.processingDone(myLatLngs);
}
Log.e("SizeOfArray", myLatLngs.size()+"");
First of all I will say that you should use static inner class instead of non-static inner class to avoid memory leaks as non-static inner class holds reference to the outer class. Another thing is that you can pass a WeakReference of outer parent class so that you can return the value from onPostExecute() of AsyncTask like
public static class Consume extends AsyncTask<Void, Void, Void> {
WeakReference<MainActivity> mActivity;
public Consume(MainActivity activity){
mActivity = new WeakReference<SampleActivity>(activity);
}
}
In your AsyncTask's onPostExecute method it will be
mActivity.response(latLngs);
And in your other class it will be like
private static void response(List<LatLng> latLngs){
// handle response here in your outer class
}
Update: Here is how you can pass WeakReference of Activity to Inner or Anonymous class and use it.
Thx all, for all replies.
Thx, I really did not understand what the problem is and cause of that i asked this simple question ! And unfortunately none of you notice that.
After the code :
Consume consume = new Consume();
consume.execute():
Compiler goes to execute next code too,Cause consume.execute() start another thread but the main thread continues.
Cause of that i received the value i wanted with a delay and therefore i though the problem is how to get the value,
But actually the problem was that i could not handle the thread asynchronization.
So i moved all them in onPre and onPost methods of AsyncTask class,And then it worked !
I'm trying to write a class that iterates through a textfile, it looks like this (it's ~5000 lines):
Postnr Poststad Bruksområde Kommunenummer Lat Lon Merknad Nynorsk Bokmål Engelsk
0001 Oslo Postboksar 301 59.91160 10.75450 Datakvalitet: 2. Koordinatar endra 28.09.2012. Oppdatert 04.12.2012 url1 url2 url3
My trouble is: the method getassets is undefined for the type SearchTabTxt
I'm trying to read the file from the assets folder and I can't seem to find a solution to this. I tried to write a search class for this:
public class SearchTabTxt extends AsyncTask<String, Void, ArrayList<String[]>> {
protected ArrayList<String[]> doInBackground(String... inputString) {
ArrayList<String[]> list = new ArrayList<String[]>();
try {
InputStream is = getAssets().open("file.txt");
if (is != null) {
String search = inputString[0].toString();
InputStreamReader inputreader = new InputStreamReader(is,
"UTF-8");
BufferedReader buffreader = new BufferedReader(inputreader);
int antallTreff = 0;
while (buffreader.readLine() != null) {
ArrayList<String> placeInformation = new ArrayList<String>();
if (buffreader.readLine().contains(search)) {
antallTreff++;
System.out.println("Found: " + search);
placeInformation.clear();
for (String i : buffreader.readLine().split("\t")) {
placeInformation.add(i);
}
System.out.println(placeInformation.get(11));
// Sorry about the Norwegian will rewrite
if (antallTreff >= 3) {
System.out.println("Did I find something?");
break;
}
if (buffreader.readLine() == null) {
break;
}
}
}
}
} catch (ParseException e) {
Log.e("Error", e + "");
} catch (ClientProtocolException e) {
Log.e("Error", e + "");
} catch (IOException e) {
Log.e("Error", e + "");
}
return list;
}
}
Well it's simple. There is no method getAssets() in your SearchTabTxt class. To get the assets, you need a Context. Make a public constructor to your SearchTabTxt class, and pass a Context.
private Context context;
public SearchTabTxt (Context myContext) {
this.context = myContext;
}
Now in the doINbackground method you can do:
InputStream is = context.getAssets().open("file.txt");
Now in the Activity when you createyour AsyncTask you can start the task like this: new SearchTabTxt(this).execute(params); This works because your Activity (this) is a subtype of Context.
More on this here: getAssets(); from another class
I am writing an android application, I previously had a problem NetworkOnMainThreadException and I solved using threads. I now don't get any error and also I don't get any output.
here is my code: there is no errors in the LogCat
public class Currency_convert extends Activity {
public int to;
public int from;
public String [] val;
public String s;
public Handler handler;
public double am=0.0;
StringBuilder build=null ;
HttpClient client=null;
HttpGet httpGet =null;
HttpResponse response=null;
HttpEntity entity=null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.currency);
Spinner s1 = (Spinner) findViewById(R.id.spinner11);
Spinner s2 = (Spinner) findViewById(R.id.spinner22);
final EditText e=(EditText) findViewById(R.id.amountt);
// am=Double.parseDouble(e.getText().toString());
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.name, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
val = getResources().getStringArray(R.array.value);
s1.setAdapter(adapter);
s2.setAdapter(adapter);
s1.setOnItemSelectedListener(new spinOne(1));
s2.setOnItemSelectedListener(new spinOne(2));
Button b = (Button) findViewById(R.id.button11);
b.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
TextView t = (TextView) findViewById(R.id.textView44);
if(from == to) {
Toast.makeText(getApplicationContext(), "Invalid", 4000).show();
}
else {
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
//s=getJson("http://www.google.com/ig/calculator?hl=en&q=1USD=?INR");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
am=Double.parseDouble(e.getText().toString());
double totalR=(Double.parseDouble(exResult))*am;
String r=String.valueOf(totalR);
t.setText(r);
// Log.println(priority, tag, msg)
System.out.println("r =" +r);
Log.i("hello", r);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
public String getJson(final String url)throws ClientProtocolException, IOException {
// private String getJson(String url)throws ClientProtocolException, IOException e {
build = new StringBuilder();
client = new DefaultHttpClient();
httpGet = new HttpGet(url);
new Thread(new Runnable() {
public void run() {
try {
response = client.execute(httpGet);
entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
// response = client.execute(httpGet);
// entity = response.getEntity();
// InputStream content = entity.getContent();
// BufferedReader reader = new BufferedReader(new InputStreamReader(content));
// String con;
// while ((con = reader.readLine()) != null) {
// build.append(con);
// }
return build.toString();
//return url;
}
private class SpinOne implements OnItemSelectedListener {
int ide;
SpinOne(int i) {
ide =i;
}
public void onItemSelected(AdapterView<?> parent, View view,
int index, long id) {
if(ide == 1) {
from = index;
}
else if(ide == 2) {
to = index;
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}}
The way it is written, getJson() will return immediately without giving time for the thread to run completely, so the returned value will not be what you want. Use an AsyncTask so you can run your thread code in the AsyncTask's doInBackground() method and then pass the result to the onPostExecute() method where you can then perform setText() as you intend.
An alternative is to move the JSON parsing and setText() code into the thread's run() method after the HTTP request is made but since running UI-related code (in this case setText()) in a separate thread is not allowed you can use a Handler to schedule setText() to run in the UI thread.
You can read the basics on AsyncTask and Handler here.
When you spawn a thread, code execution splits into different time frames, so even though global scope is shared, you won't get objects populated in a timely fashion for your UI update task if you don't implement some logic to prevent inconsistencies.
Android provides multiple flow control and inter-thread communication patterns built-in that can help you solve such inconsistencies. One such option involves AsyncTask, in your case you can do the following:
Extended AsyncTask with your UI thread-forbidden tasks inside the doInBackground() method;
Get logic that needs to run on UI thread (such as manipulating Views) inside onPostExecute() handler from the same AsyncTask instance. This handler will only be called after doInBackground returns, so the program knows that the logic to populate the object was triggered.
You can look up a sample of AsyncTask in this answear for a practical approach.
Note: If you want to use parent class members such as findViewByID inside an AsyncTask instance, you will need to manually invoke the parent file scope using the <UIThreadName>.this., e.g. <UIThreadName>.this.findViewByID(id). You can do this freely in onPostExecute which has no restrictions due to running on the UI thread, but you are restricted to not performing UI changes in doInBackground (which doesn't run on the UI thread).
I solved it, I just added t.join after the thread declaration :)
I'm really new working with Android, so there's a lot that's confusing me. I've looked at what seems like 100 tutorials and examples of how to get information from a web service on Android, but what I need is something for a guy that doesn't have a clue. Here are a couple of things in particular that I'm not getting:
I don't know what to do with XML files.. meaning, once I do the Java work, is that all that needs to be done? or does anything need to be changed in the XML files?
Seems like maybe I'm supposed to create a new class for some of these tutorials, but I'm not sure, and if so, I'm not sure what to do once I've made the class
I want to retrieve the information in JSON format. For right now as long as I can get just that information that's fine, I can learn how to work with JSON later.
It seems like kSoap2 is the best way to do this. I have the jar file that's needed to work with it
I've delved a little into phonegap, so if there's an answer that uses that, then I can work with that
My web service is working properly, and is essentially the same as what I've seen in a number of tutorials, so there's no problem there.
If anyone can point me to a tutorial that will help me out to learn ALL that I need to know to create a sample app that gets information from my web service, or if anyone is willing to walk me through it, I would greatly appreciate it!
Thanks in advance!
Initially you have to make an http connection so that you can get the response from your api be it xml response or json response. You can use the following code for it.
Keep the class separate than activity. :-
public class Response {
String get_url, response;
Activity activity;
public Response(String url){
this.get_url = url;
}
public String getResponse(){
InputStream in = null;
byte[] data = new byte[1000];
try {
URL url = new URL(get_url);
URLConnection conn = url.openConnection();
conn.connect();
/* conn.*/
in = conn.getInputStream();
Log.d("Buffer Size +++++++++++++", ""+in.toString().length());
BufferedReader rd = new BufferedReader(new InputStreamReader(in),in.toString().length());
String line;
StringBuilder sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
response = sb.toString();
in.read(data);
Log.d("INPUT STREAM PROFILE RESPONSE",response);
in.close();
} catch (IOException e1) {
Log.d("CONNECTION ERROR", "+++++++++++++++++++++++++++");
// TODO Auto-generated catch block
e1.printStackTrace();
}
return response;
}
}
You may call the class in your activity like this :-
Response res = new Response("your_url");
String getResponse = res.getResponse();
So here you get the response from the api.
Now Lets make the parser
//Extend the class with Default Handler
public class XMLParser extends DefaultHandler {
//You must have basic knowledge about Array List and setter/getter methods
// This is where the data will be stored
ArrayList<Item> itemsList;
Item item;
String data;
String type;
private String tempVal;
//Create the Constructor
public XMLParser(String data){
itemsList = new ArrayList<Item>();
this.data = data;
}
public byte parse(){
SAXParserFactory spf = null;
SAXParser sp = null;
InputStream inputStream = null;
try {
inputStream = new ByteArrayInputStream(data.getBytes());
spf = SAXParserFactory.newInstance();
if (spf != null) {
sp = spf.newSAXParser();
sp.parse(inputStream, this);
}
}
/*
* Exceptions need to be handled MalformedURLException
* ParserConfigurationException IOException SAXException
*/
catch (Exception e) {
System.out.println("Exception: " + e);
e.printStackTrace();
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (Exception e) {
}
}
if (itemsList != null && itemsList.size() > 0) {
// //Log.d("Array List Size",""+tipsList.get(4).getTitle());
return 1;
} else {
return 0;
}
}
public ArrayList<Item> getItemList(){
return itemsList;
}
// Here you can check for the xml Tags
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if(localName.equalsIgnoreCase("item")){
item = new Item();
Log.d("Working", "+++++++++++++++++++++++");
}
}
//tempVal is the variable which stores text temporarily and you
// may save the data in arraylists
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(localName.equalsIgnoreCase("item")){
itemsList.add(item);
Log.d("Working in endelement", "+++++++++++++++++++++++");
item.setTitle(tempVal);
}
}
Combining all this :-
Now lets see the activity
public void oncreate(){
// Do something or mostly the basic code
// Call the class to initate the connection and get the data
FetchList fl = new FetchList();
fl.execute();
}
//Always better to use async task for these purposes
public class FetchList extends asyncTask<Void,Void,Byte>{
doinbackground{
// this was explained in first step
Response res = new Response("url");
String response = res.getResponse();
XmlParser xml = new XmlParser(response);
ArrayList<item> itemList = xml.getItemList();
xml.parse();
}
}
Well that is all to it.
I've searched around and haven't been able to coem up with a solution to this one..
my (first) problem is that i'm getting NPE on FileInputStream instream = context.getApplicationContext().openFileInput(textname);in the getLengthOfText(); method. I've debugged and the correct filename appears to be passed to this method. I've been stuck on this for weeks and really want it to work (newb).
this method is being called by another class. Also, the files are there in data/data and everything else is as it should be. please help!!
-Tricknology
/***** this class takes a text file and loads it into an array **/
public class loadArray {
Context context;
textWriter textwriter;
public loadArray (Context cxt) {
this.context = cxt;
textwriter = new textWriter (cxt);
context = cxt;
}
FileInputStream instream;
textWriter tw = new textWriter(context);
String[] choiceAry, dummyAry;
P p = new P(); // shared prefs helper
String Choice;
String comp = "notnull";
int addChoiceCount, length;
// Context context = this.getApplicationContext();
public void buildDummies(int length) {
// addChoiceCount = p.gisI("addChoiceCount");
choiceAry = new String[length];
p.pisI("length", length, context);
// dummyAry = new String[100];
}
public Integer getLengthOfText(String textname)
throws FileNotFoundException {// counts how many lines of text
// DataInputStream dis = new DataInputStream(openFileInput("file.dat"));
int length = 0;
instream = context.getApplicationContext().openFileInput(textname);
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
try {
// while (!comp.equals(null)){
while (buffreader.ready()) {
String temp = buffreader.readLine();
length++;
}
buffreader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return length;
}
public String[] laft(String textname) throws FileNotFoundException {
// loads a text file to an array...load array from text........
length = getLengthOfText(textname);
buildDummies(length);
try {
instream = context.getApplicationContext().openFileInput(textname);
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
// load array from text
for (int i = 0; i < (length); i++) {
try {
Choice = buffreader.readLine();
choiceAry[i] = Choice;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buffreader.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return choiceAry;
}
public String getOrderName() {
// TODO Auto-generated method stub
return null;
}
}
I found the answer thanks to Leeds and billiard from #android-dev
what I was doing is also calling loadArry from another class that did not extend activity.. so it was activity >calling> class that doesnt extend activity >calling> class that doesnt extend activity. somehow in there the context was lost. I basically applied similar lines at the top starting with
Context context;
textWriter textwriter;
public loadArray (Context cxt) {
this.context = cxt;
textwriter = new textWriter (cxt);
context = cxt;
hope this saves someone a lot of time in the future.
You have made things much too complicated for yourself in the code. In the end, complicated code = harder debugging.
I load text files into arrays all the time.
Consider using the java.util.StringTokenizer class or the String split() method in class java.lang.String.
TenFour4 brings up another good point.
This is what the code should look like...
Context context;
textWriter textwriter;
public loadArray (Context cxt){
this.context = cxt;
textwriter = new textWriter (cxt);
}
--UPDATE--
A common mistake is that the file you are trying to read from has not been closed properly, therefore you are getting a NullPointerException whenever you try to access the still open file.
e.g.
PrintWriter pw = new PrintWriter (new FileWriter (fileName));
pw.println ("This is output data: " + data);
//new loadArray ().getLengthOfText (fileName); //ERROR Throws NPE
pw.close(); //Make Sure you Close Before trying to read the file again!
new loadArray ().getLengthOfText (fileName); //Works like a charm :)
As it seems to me, the only reason you may get NPE in the line you said you get it is that context is somehow NULL (openFileInput doesn't throw NPE) make sure that context is not NULL.
Your textWriter instance is getting instantiated while context is still null. Any definitions that occur outside of methods will happen before the constructor is called.
By the way, class names should start with a capital letter and not start with a verb, by convention. It will help you avoid errors and be easier for other people to understand.