Double FOR loop and FileOutputStream - android

In this portion of my app, I have a database which is absorbing data from my light sensor. It has a RowID associated with each row.
In the background I have an AsyncTaskRunner which is reading that table and writing each row to a CSV file. It should loop through the entire table as data is being written to it, looking for all rows for the current TID that have not been copied to CSV. THen it should write the row values to CSV and go back and mark the row as copied.
THe first loop should come in where no it goes back to the database cursor and looks for the next row which has not been copied to the CSV file. After each copy to CSV it should evaluate the size of that CSV file to make sure it is not full. If not Full then should go back to the Database cursor and look for the next row to write to the CSV file. If isfull then it should loop back to LoopMain and start over creating a new CSV file to write to.
While the full method is not complete yet, I am at the part where the row data is suposed to be written to the CSV file. At the moment, it does not write to it. Before I made this method a For Loop, it did, now it does not. I can not figure out what has changed. I have inserted all of these Log comments to follow the method as it passes values, receives values and then does an action to see where it is failing. THe method passes the section where it is to write to the CSV file and continues on, but the file is empty.
public void lightloop(){
//Loop Main
int loopcounter;
LoopMain: for(loopcounter = 0; loopcounter < 4; loopcounter++ ){
Log.d(CSV, "lightloop loopcounter = " + loopcounter);
String CSVFinalFileName=createlightcsv();
Log.w(CSV, "LightLoop, CSVFinalFileName = " + CSVFinalFileName);
//Loop 2
Loop2: for(int useless=1; useless > 0; useless++ ){
String flightRowId = evaluateLightTable(filenamePrefix); //returns the rowid of the first line not transmitted
Log.w(CSV, "LightLoop, flightRowId = " + flightRowId);
Log.d(CSV, "filefullBoolean " + useless);
if(flightRowId != null){
Log.w(CSV, "LightLoop flightRowId is NOT NULL");
//write row to csv
//Get all row values and put into a string
String lightRowValues=fetchLightRowData(flightRowId, filenamePrefix);
Log.w(CSV, "lightLoop, lightRowValues are " + lightRowValues);
//Append that data to the CSV file
Log.w(CSV, "Opening File Output Stream");
try {
FileOutputStream csvfos = mContext.openFileOutput(CSVFinalFileName, Context.MODE_PRIVATE);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
OutputStreamWriter sensorCSVWriter = new OutputStreamWriter(csvfos);
try {
sensorCSVWriter.append("LIGHT " + lightRowValues);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/** try {
sensorCSVWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} **/
//mark row as transmitted
SQLDatabase updatelightrow = new SQLDatabase(mContext);
updatelightrow.open();
SQLDatabase.updateLightRow(flightRowId);
updatelightrow.close();
}// end If rowid is not null
//evaluate size of csv
Boolean filefull = CsvStreamer.checkFileSize(CSVFinalFileName);
if(!filefull){
//return to cursor
Log.d(CSV, "lightloop, File is NOT full");
break Loop2;
}else{
Log.d(CSV, "lightloop, File IS full");
//file is full. close it,
//transmit it,
//open a new one
//goto CSV table and mark it transmitted
break LoopMain;
}
}//end Loop2
}//end LoopMain
}
Can anyone see why this is failing to write to the File?

The csvfos is not in the same scope. I assume the class has a property called csvfos also, hence the method is accessing the property and not the csvfos variable created in the try catch.
Try changing
try
{
FileOutputStream csvfos = mContext.openFileOutput(CSVFinalFileName, Context.MODE_PRIVATE);
}
catch (FileNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
to
FileOutputStream csvfos = null;
try
{
csvfos = mContext.openFileOutput(CSVFinalFileName, Context.MODE_PRIVATE);
}
catch (FileNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}

Related

CallLog.Calls Call's logs Android

Yesterday I was looking into a way to acquire the call log of an android device.
My idea was to acquire everything posible and then parse it and get only what I really needed.
Following the documentation See CallLog.Calls Documentation I saw the different fields there are but when trying to get them I got erros caused by differences in the documentation.
Finally I got it to work so I wanted to share the code in case anyone else needs it.
In the code I use JSON objects and save them in the Documents folder.
private void getCallLog(Context context) {
#SuppressLint("MissingPermission") Cursor cursor = getApplicationContext().getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null,
null, CallLog.Calls.DATE + " DESC");
if (cursor.getCount() > 0) {
try{
// Get the directory for the user's public pictures directory.
final File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
// Make sure the path directory exists.
if (!path.exists()) {
// Make it, if it doesn't exit
path.mkdirs();
}
final File file = new File(path, "call.txt");
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
while (cursor.moveToNext()) {
try {
JSONObject object = new JSONObject();
object.put("ANSWERED_EXTERNALLY_TYPE", CallLog.Calls.ANSWERED_EXTERNALLY_TYPE);
object.put("BLOCKED_TYPE", CallLog.Calls.BLOCKED_TYPE);
object.put("CACHED_FORMATTED_NUMBER", cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_FORMATTED_NUMBER)));
object.put("CACHED_LOOKUP_URI", cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_LOOKUP_URI)));
object.put("CACHED_MATCHED_NUMBER", cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_MATCHED_NUMBER)));
object.put("CACHED_NAME", cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME)));
object.put("CACHED_NORMALIZED_NUMBER", cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NORMALIZED_NUMBER)));
object.put("CACHED_NUMBER_LABEL", cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NUMBER_LABEL)));
object.put("CACHED_NUMBER_TYPE", cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NUMBER_TYPE)));
object.put("CACHED_PHOTO_ID", cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_PHOTO_ID)));
object.put("CACHED_PHOTO_URI", CallLog.Calls.CACHED_PHOTO_URI); // Wrong docs
object.put("CONTENT_ITEM_TYPE", CallLog.Calls.CONTENT_ITEM_TYPE); // Wrong docs
object.put("CONTENT_TYPE", CallLog.Calls.CONTENT_TYPE); // Wrong docs
object.put("COUNTRY_ISO", cursor.getString(cursor.getColumnIndex(CallLog.Calls.COUNTRY_ISO)));
object.put("DATA_USAGE", cursor.getString(cursor.getColumnIndex(CallLog.Calls.DATA_USAGE)));
object.put("DATE", cursor.getString(cursor.getColumnIndex(CallLog.Calls.DATE)));
object.put("DEFAULT_SORT_ORDER", CallLog.Calls.DEFAULT_SORT_ORDER); // Wrong docs
object.put("DURATION", cursor.getString(cursor.getColumnIndex(CallLog.Calls.DURATION)));
object.put("EXTRA_CALL_TYPE_FILTER", CallLog.Calls.EXTRA_CALL_TYPE_FILTER); // Wrong docs
object.put("FEATURES", cursor.getString(cursor.getColumnIndex(CallLog.Calls.FEATURES)));
object.put("FEATURES_HD_CALL", CallLog.Calls.FEATURES_HD_CALL);
object.put("FEATURES_PULLED_EXTERNALLY", CallLog.Calls.FEATURES_PULLED_EXTERNALLY);
object.put("FEATURES_VIDEO", CallLog.Calls.FEATURES_VIDEO);
object.put("FEATURES_WIFI", CallLog.Calls.FEATURES_WIFI);
object.put("GEOCODED_LOCATION", cursor.getString(cursor.getColumnIndex(CallLog.Calls.GEOCODED_LOCATION)));
object.put("INCOMING_TYPE", CallLog.Calls.INCOMING_TYPE);
object.put("IS_READ", cursor.getString(cursor.getColumnIndex(CallLog.Calls.IS_READ)));
object.put("LAST_MODIFIED", CallLog.Calls.LAST_MODIFIED); // Wrong docs
object.put("LIMIT_PARAM_KEY", CallLog.Calls.LIMIT_PARAM_KEY); // Wrong docs
object.put("MISSED_TYPE", CallLog.Calls.MISSED_TYPE);
object.put("NEW", cursor.getString(cursor.getColumnIndex(CallLog.Calls.NEW)));
object.put("NUMBER", cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER)));
object.put("NUMBER_PRESENTATION", cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER_PRESENTATION)));
object.put("OFFSET_PARAM_KEY", CallLog.Calls.OFFSET_PARAM_KEY); // Wrong docs
object.put("OUTGOING_TYPE", CallLog.Calls.OUTGOING_TYPE);
object.put("PHONE_ACCOUNT_COMPONENT_NAME", cursor.getString(cursor.getColumnIndex(CallLog.Calls.PHONE_ACCOUNT_COMPONENT_NAME)));
object.put("PHONE_ACCOUNT_ID", cursor.getString(cursor.getColumnIndex(CallLog.Calls.PHONE_ACCOUNT_ID)));
object.put("POST_DIAL_DIGITS", CallLog.Calls.POST_DIAL_DIGITS); // Wrong docs
object.put("PRESENTATION_ALLOWED", CallLog.Calls.PRESENTATION_ALLOWED);
object.put("PRESENTATION_PAYPHONE", CallLog.Calls.PRESENTATION_PAYPHONE);
object.put("PRESENTATION_RESTRICTED", CallLog.Calls.PRESENTATION_RESTRICTED);
object.put("PRESENTATION_UNKNOWN", CallLog.Calls.PRESENTATION_UNKNOWN);
object.put("REJECTED_TYPE", CallLog.Calls.REJECTED_TYPE);
object.put("TRANSCRIPTION", cursor.getString(cursor.getColumnIndex(CallLog.Calls.TRANSCRIPTION)));
object.put("TYPE", cursor.getString(cursor.getColumnIndex(CallLog.Calls.TYPE)));
object.put("VIA_NUMBER", CallLog.Calls.VIA_NUMBER); // Wrong docs
object.put("VOICEMAIL_TYPE", CallLog.Calls.VOICEMAIL_TYPE); // Wrong docs
object.put("VOICEMAIL_URI", cursor.getString(cursor.getColumnIndex(CallLog.Calls.VOICEMAIL_URI)));
myOutWriter.append(object.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
myOutWriter.close();
fOut.flush();
fOut.close();
} catch (Exception e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
}

Eclipse - Functions issue [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm trying to get text from server and then check it a to know what actions to take with the text adopted. The problem is that when I try to check if the received text for example is "Exited" the query always return the value "false" when the received text is really "Exited".
Here is the code :
class Get_Message_From_Server implements Runnable
{
public void run()
{
InputStream iStream = null;
try
{
iStream = Duplex_Socket_Acceptor.getInputStream();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//Create byte array of size image
byte[] Reading_Buffer = null;
try
{
Reading_Buffer = new byte [Duplex_Socket_Acceptor.getReceiveBufferSize()];
//New_Buffer = new byte [100];
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
byte[] Byte_Char_1 = new byte[1];
int Byte_String_Lenght = 0;
//read size
try
{
iStream.read(Reading_Buffer);
String Reading_Buffer_Stream_Lenghtor = new String(Reading_Buffer);
//System.out.println("full : " + Reading_Buffer_Stream_Lenghtor);
Byte_String_Lenght = Reading_Buffer_Stream_Lenghtor.indexOf(new String(Byte_Char_1));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//Convert to String
Meassage = new String(Reading_Buffer);
Meassage = Meassage.substring(0, Byte_String_Lenght);//The text that received
Message_Getted = 1;
}
}
The query :
if(Message_1 != "Exited")//the message query
{
System.out.println("Continued 253");
continue;
}
Its always return the value - false
its important to know that the message is in Utf - 8 encoding
so how i can to fix the issue ?
If you compare strings by using oparators, Java will not look at the contents of the string but at the reference in memory. To compare String content in Java, you should use the following:
String Message_1; // Hopefully has a value sent by the server
if(Message_1.equals("Exited")) {
// Do stuff when exited
} else {
// Do stuff when not exited
}
String is a variable - and variables should start with lower Case letter - Please read Java Code conventions. Also to check if your message contains string you thing it should just do System.out.println(Message_1); and if the message contains what you expect you compare string doing
if(Message_1.equals("Exited")) {
System.out.println("Yes they are equal");
} else {
System.out.println("No they are not");
}
If this will print "No they are not" that simply means that your variable Message_1 is not what you think it is.. As simple as that. There is no such a thing as .equals method does not work. Its your variable that doesn't ;)

Get random words from android dictionary

I am kind of learning android...and I would like to know if there is a way to access 3 letter words or 4 letter words or some specif type of words at random from the android User Dictionary class??Considering the fact that android has an auto correct feature I'm guessing it also has a dictionary in it...thus how do I use that...where can I find a proper tutorial?
i have no idea about the code...searched around a lot...please help me with the code and also the explanation possibly :)
I don't know how to access the android dictionary but you can have a "custom" dictionary as a txt file in the app's assets folder. This link has several word lists from around 20,000 words to 200,000 words. You could find more lists with google.
Afterwards, you can read the txt file and add it to an Array List if it matches the word length. A random word can then be selected from the dictionary list. The following code will create the dictionary and select a random word from it.
private ArrayList<String> dictionary;
private int wordLength; //Set elsewhere
private void createDictionary(){
dictionary = new ArrayList<String>();
BufferedReader dict = null; //Holds the dictionary file
AssetManager am = this.getAssets();
try {
//dictionary.txt should be in the assets folder.
dict = new BufferedReader(new InputStreamReader(am.open("dictionary.txt")));
String word;
while((word = dict.readLine()) != null){
if(word.length() == wordLength){
dictionary.add(word);
}
}
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dict.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Precondition: the dictionary has been created.
private String getRandomWord(){
return dictionaryList.get((int)(Math.random() * dictionaryList.size()));
}

Why do Android updates of my app erase information?

In my app, I have a list of objects that are stored with a FileOutputStream in the code below. Also, I have any settings in my app stored with SharedPreferences. Whenever I updated my app on the Google Play store for the first time (for those unfamiliar with the process, I upload the new APK), all objects were deleted for anyone using the app, and all settings set to default. Why did it do this and how can I have the objects stored where they don't disappear after update?
public ObjectStorage readListFromFile()
{
ObjectStorage temp = null;
String filename = "storefileobj";
FileInputStream fis;
try {
fis = getActivity().openFileInput(filename);
ObjectInputStream is = new ObjectInputStream(fis);
temp = (ObjectStorage) is.readObject();
is.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return temp;
}
public void updateStorage()
{
String filename = "storefileobj";
FileOutputStream fos;
try {
fos = getActivity().openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(mainObjectList);
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
For normal updates, your users would not have lost these values.
I believe that each of your users who lost their stored SharedPreference and saved file data were forced to delete their old application in order to install the new application from the Play Store. Otherwise, some of your keys or file formats must have changed.
Signature:
You certainly used Android's Signing Your Applications documentation in order to update at the Play Store, but perhaps the users in question were using an app signed with a different signature (such as a Debug Mode signature) that you had delivered to them separately. This could explain why they were forced to uninstall before updating at the Play Store, thus erasing all of the saved information.
Data Format:
Another alternative is that perhaps the Keys used for the SharedPreference values changed OR the file format or class structure for the ObjectStorage changed, making it impossible to read the old values. This would appear to the users as if the old values disappeared. Then, as the users saved values in the new format, your app would continue to work properly for them.
Summary:
One of the following must have happened:
Your users deleted before reinstall. Or,
Your stored data format changed between versions.

Get int from text file and set it to variable

I'm trying to get the int value of a text file that have text like:
123456789 12345678 1234567 123456 12345 1234 123 12 1
as you can see every number is different and they are in a same line separated by a "space". I need to get the values separated. to get something like this:
INT1 = 123456789, INT2 = 12345678, INT3 = 1234567;
and so on. I don't create the text so I don't know how much numbers and groups they are, but they are always separated by a "space". I know how to read it. This is how I'm reading it:
try {
TEST1 = new BufferedReader(new FileReader("/sdcard/test.txt")).readLine();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TEST.setText(""+scaling_available_frequencies);
and I got this output
194208 776175 958253 767883 700246 243663 966618 345199 945363 459833
NOTE: This is just a test.txt that I created to see if it works. The current code will ask the user for entering path and file name.
Now how can I set them to a variable per group?
Thanks
This is one way to parse the String to an integer array:
public int[] toIntArray( String stringFromFile ){
String[] allStrings = stringFromFile.split( "\\s" );
int[] intArray = new int[allStrings.length];
for( int i = 0; i < allStrings.length; ++i ){
try{
intArray[i] = Integer.parseInt( allStrings[i] );
}catch( NumberFormatException e ){
// Do whatever you think is appropriated
intArray[i] = -1;
}
}
return intArray;
}
Hope this helps.
I believe readLine() get you String.
You will need to use the Split() method of String and pass in the regularExpression (whitespace).
then you will need to use Integer.parseInt( ) method and pass in every string to parse them into Integer.
you also need a loop to do the parse until nothing left

Categories

Resources