what is the value of AUTHORITY to delete messages - android

Good day to all!!!
We can delete call history using CallLog.AUTHORITY. Here is an utility method to delete calls...
public static void deleteCallLogsFromNative(Context context, long[] rowIds) {
ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(
rowIds.length);
for (int i = 0, N = rowIds.length; i < N; i++) {
operations.add(ContentProviderOperation
.newDelete(CallLog.Calls.CONTENT_URI)
.withSelection(CallLog.Calls._ID + " = ?",
new String[] { String.valueOf(rowIds[i]) }).build());
}
try {
context.getContentResolver().applyBatch(CallLog.AUTHORITY,
operations);
} catch (Exception e) {
Log.e(TAG,
"Error while deleting calls from native: " + e.toString());
}
}
You can observe that for applying batch operation, we need an AUTHORITY and here is CallLog.AUTHORITY is required to delete call logs.
Similarly I have another utility method for deleting messages...
public static void deleteMessagesFromNative(Context context, long[] rowIds) {
ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>(
rowIds.length);
for (int i = 0, N = rowIds.length; i < N; i++) {
long rowId = rowIds[i];
operations.add(ContentProviderOperation
.newDelete(Uri.parse("content://sms/"))
.withSelection(BaseColumns._ID + " = ?",
new String[] { String.valueOf(rowId) }).build());
}
try {
// here I need AUTHORITY value for deleting messages
} catch (Exception e) {
// TODO: handle exception
}
}
Now my question is, What is the value of AUTHORITY to delete messages?

Related

ThreadpoolExecutor data getting mixed up

I am using android's thread pool executor framework (initialized as below).
BlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<>();
ExecutorService executorService = new ThreadPoolExecutor(totalCores, totalCores * 3, 10, TimeUnit.SECONDS, taskQueue);
Now, consider the following function onFrameProcessed -
public void onFrameProcessed(RenderedImage renderedImage) {
String timeNow = new SimpleDateFormat("d-M-Y_HH_mm_ss_SSS").format(new Date()).toString();
CustomRunnable3 customRunnable3 = new CustomRunnable3(renderedImage, timeNow);
executorService.execute(customRunnable3);
}
Definition of CustomRunnable3 is as follows:
class CustomRunnable3 implements Runnable {
RenderedImage renderedImageLocal;
String basePath, timeNowCopy;
int hashCode;
CustomRunnable3(RenderedImage renderedImage, String timeNow) {
renderedImageLocal = renderedImage;
this.basePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
this.timeNowCopy = timeNow;
hashCode = renderedImageLocal.hashCode();
}
#Override
public void run() {
if (renderedImageLocal.imageType() == RenderedImage.ImageType.ThermalRadiometricKelvinImage) {
int[] thermalData = renderedImageLocal.thermalPixelValues();
String dataPath = basePath + "/" + this.timeNowCopy + ".csv";
try {
PrintWriter printWriter = new PrintWriter(dataPath);
int dataLen = thermalData.length;
for (int i = 0; i < dataLen; i++) {
printWriter.println(thermalData[i]);
}
printWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
String imgPath = basePath + "/" + this.timeNowCopy + ".jpg";
try {
if (hashCode != renderedImageLocal.hashCode()) {
Log.e("Checking", "Hash code changed..");
}
renderedImageLocal.getFrame().save(new File(imgPath), frameProcessor);
if (hashCode != renderedImageLocal.hashCode()) {
Log.e("Checking", "Hash code changed after writing..");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Usage Scenario : onFrameReceived is being called multiple times per second(like 4-5 times). In each call to onFrameReceived, I am saving two files from renderedImage object (1 csv file, 1 jpg file). Both of these files must be related to each other because both are created from one parent and have same name(except the extension).
Problem : But that is not happening and somehow I am ending up with jpg file content from 1 renderedImage and csv content from another renderedImage object.
What are the possible reasons for this problem, please share your opinion.

Android make AsyncTask wait for the activity to resume inside a for loop

I have a for loop inside onActivityResult() method that creates a Runnable object and assign in to an AsyncTask. Each Runnable object is responsible of operating on a pdf file, sealing it with a password and then starting an startActivityForResult() method with an Intent to send an email.
Everything works as a charm except that my problem is that the for loop will start all the AsyncTask immediately even though the the activity is paused and the user is on the email client app. I want to make sure that the next AsyncTask doesn't execute until the user gets back to the application after pressing send email button on the email client app.
UPDATE
if (requestCode == 2) {
// Create Insurer annexe, seal document with insurer password and trigger sending email
int lastInsurerPosition = -1;
for (int i = 0; i < Constat.getInstance().getAccidentList().size(); i++) {
if (Constat.getInstance().getAccidentList().get(i).getCar().getInsurerPosition() != -1 &&
!insurersEmails[Constat.getInstance().getAccidentList().get(i).getCar().getInsurerPosition()].equals("null") &&
Constat.getInstance().getAccidentList().get(i).getSendOption() != 1 &&
Constat.getInstance().getAccidentList().get(i).getSendOption() != 2) {
lastInsurerPosition = i;
}
}
if (lastInsurerPosition != -1) {
final int lastInsurerPositionCopy = lastInsurerPosition;
for (int i = 0; i < Constat.getInstance().getAccidentList().size(); i++) {
String insurerEmail = "null";
if (Constat.getInstance().getAccidentList().get(i).getCar().getInsurerPosition() != -1) {
insurerEmail = insurersEmails[Constat.getInstance().getAccidentList().get(i).getCar().getInsurerPosition()];
}
if (Constat.getInstance().getAccidentList().get(i).getSendOption() != 1 &&
Constat.getInstance().getAccidentList().get(i).getSendOption() != 2 &&
!insurerEmail.equals("null")) {
final int finalI = i;
Runnable progressRunnable = new Runnable() {
#Override
public void run() {
try {
String[] toArray = new String[1];
toArray[0] = insurersEmails[Constat.getInstance().getAccidentList().get(finalI).getCar().getInsurerPosition()];
String subject = getResources().getString(R.string.pdf_joint_report);
InputStream is;
String str;
byte[] buffer = null;
int size;
if (Locale.getDefault().getLanguage().equals("en")) {
is = getAssets().open("insurerEmailTemplateENG.html");
} else {
is = getAssets().open("insurerEmailTemplateFR.html");
}
size = is.available();
buffer = new byte[size];
is.read(buffer);
is.close();
String destPath = Constat.getInstance().getPdfPath().replace(".pdf", "_copy" + Constat.getInstance().getAccidentList().get(finalI).getNumAccident() + ".pdf");
String destPath1 = Constat.getInstance().getPdfPath().replace(".pdf", "_copy1.pdf");
if (insurersPdfStructure[Constat.getInstance().getAccidentList().get(finalI).getCar().getInsurerPosition()].equals("1")) {
List<File> filesList = new ArrayList<>();
if (PdfController.getInstance(activityRef.get()).getAnnexePref()) {
filesList.add(new File(Constat.getInstance().getPdfPath()));
filesList.add(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + PACKAGE_NAME + "/annexe.pdf"));
} else {
filesList.add(new File(Constat.getInstance().getPdfPath()));
}
File outputFile = new File(destPath1);
try {
Utilities.mergePdfDocuments(filesList, outputFile);
} catch (DocumentException | IOException e) {
e.printStackTrace();
}
} else {
try {
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(destPath1));
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfReader reader = new PdfReader(new FileInputStream(Constat.getInstance().getPdfPath()));
for (int j = 0; j < reader.getNumberOfPages(); j++) {
PdfImportedPage page = writer.getImportedPage(reader, j + 1);
if (j == 0) {
PdfDictionary parameters = new PdfDictionary();
parameters.put(PdfName.MODDATE, new PdfDate());
PdfFileSpecification fileSpec = PdfFileSpecification.fileEmbedded(
writer, Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + PACKAGE_NAME + "/annexe.xml",
"annexe.xml", null, "application/xml", parameters, 0);
fileSpec.put(new PdfName("annexe"), new PdfName("Data"));
writer.addFileAttachment("annexe.xml", fileSpec);
PdfFileSpecification fileSpec1 = PdfFileSpecification.fileEmbedded(
writer, Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + PACKAGE_NAME + "/xml_def.xsd",
"xml_def.xsd", null, "application/xml", parameters, 0);
fileSpec.put(new PdfName("xml_def"), new PdfName("Data"));
writer.addFileAttachment("xml_def.xsd", fileSpec1);
PdfArray array = new PdfArray();
array.add(fileSpec.getReference());
array.add(fileSpec1.getReference());
writer.getExtraCatalog().put(new PdfName("AF"), array);
}
cb.addTemplate(page, 0, 0);
document.newPage();
}
document.close();
} catch (DocumentException | IOException e) {
e.printStackTrace();
}
}
try {
File file1 = new File(destPath);
file1.getParentFile().mkdirs();
Utilities.sealPdf(destPath1, destPath, insurersPasswords[Constat.getInstance().getAccidentList().get(finalI).getCar().getInsurerPosition()]);
} catch (DocumentException e) {
e.printStackTrace();
}
ArrayList<Uri> uris = new ArrayList<Uri>();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
uris.add(Uri.fromFile(new File(destPath)));
else
uris.add(FileProvider.getUriForFile(context, getApplicationContext().getPackageName() + ".provider", new File(destPath)));
str = new String(buffer);
str = str.replace("{#CAROWNER}", Constat.getInstance().getAccidentList().get(finalI).getCar().getOwner().getFirstName() + " " + Constat.getInstance().getAccidentList().get(finalI).getCar().getOwner().getLastName());
final int i1 = finalI;
final int lastInsurerPosition1 = lastInsurerPositionCopy;
final String[] toArray1 = toArray;
final String str1 = str;
final String subject1 = subject;
final ArrayList<Uri> uris1 = uris;
runOnUiThread(new Runnable() {
#Override
public void run() {
if (i1 != lastInsurerPosition1) {
Utilities.sendEmails(activityRef.get(), toArray1, null, str1, subject1, uris1, 3);
} else {
Utilities.sendEmails(activityRef.get(), toArray1, null, str1, subject1, uris1, 4);
}
while (!activityRef.get().hasWindowFocus()) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
};
LongOperation lo = new LongOperation(PdfActivity.this, progressRunnable, getResources().getString(R.string.generating),
getResources().getString(R.string.generating_email_n_for_insurer, Constat.getInstance().getAccidentList().get(i).getDriver().getFirstName()));
lo.execute();
}
}
} else {
// delete signature image file and redirect user to home screen
for (int j = 0; j < Constat.getInstance().getAccidentList().size(); j++) {
File file = new File(Constat.getInstance().getAccidentList().get(j).getSignatureFilePath());
file.delete();
}
// Reset Pdf instance
PdfController.destroyInstance();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(getResources().getString(R.string.send_success))
.setMessage(getResources().getString(R.string.emails_sended))
.setCancelable(false)
.setPositiveButton(getResources().getString(R.string.ok_button), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
Thanks in advance.
I can write an abstract snippet, cuz i don't understand your code, it can be a guide (if it helps) to alter your code to, i will post answer
Declare this class scope
Queue<MyItem> queue = new LinkedList<MyItem>();
//MyItem is a type i think it's what in 'Constat.getInstance().getAccidentList()'
//it should be the type you have to be processed (email and PDF)
your current code (onActivityResult) don't start processing, just add to Queue, and process first item in Queue:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
for(int i = 0; i < Constat.getInstance().getAccidentList().size(); i++){
//add to-be-processed items in the Queue
queue.add(Constat.getInstance().getAccidentList().get(i));
}//for loop
//when loop finish, start processing first item
MyItem item = queue.remove();
processItem(item);
}
each time onResume() is called, check queue size, if empty
that can be all items were processed, or this is the first time the activity is open, so no items to process yet
#Override
protected void onResume()
{
super.onResume();
if(queue.size() != 0){
processItem(queue.remove());
}//we still have items to process
}
your actual code is here, to create PDF, create email , send email.
private void processItem(MyItem item){
//start runnable ... to create PDF ...
//create email body, and start email sending action
}

GCM MultiCastResult Approach

This is my approach to use gcm for more than 1000 devices. Is it right that way? As I cannot try it unless I have more than 1000 users so any feedback would be appreciated and most importantly am I checking errors correctly? and updating database in a right way?
public class MessagingEndpoint {
private static final Logger log = Logger.getLogger(MessagingEndpoint.class.getName());
/**
* Api Keys can be obtained from the google cloud console
*/
private static final String API_KEY = System.getProperty("gcm.api.key");
private List<RegistrationRecord> records;
private List<String> getRegistrationId() {
records = ofy().load().type(RegistrationRecord.class).list();
List<String> records_ID = new ArrayList<String>();
for (int i = 0; i < records.size(); i++) {
records_ID.add(records.get(i).getRegId());
}
return records_ID;
}
private List<List<String>> regIdInThousands(List<String> list, final int L) {
List<List<String>> parts = new ArrayList<List<String>>();
final int N = list.size();
for (int i = 0; i < N; i += L) {
parts.add(new ArrayList<String>(list.subList(i, Math.min(N, i + L))));
}
return parts;
}
*
* #param message The message to send
*/
public void sendMessage(#Named("message") String message) throws IOException {
if (message == null || message.trim().length() == 0) {
log.warning("Not sending message because it is empty");
return;
}
// crop longer messages
if (message.length() > 1000) {
message = message.substring(0, 1000) + "[...]";
}
Sender sender = new Sender(API_KEY);
Message msg = new Message.Builder().addData("message", message).build();
List<List<String>> regIdsParts = regIdInThousands(getRegistrationId(), 1000);
for (int i = 0; i < regIdsParts.size(); i++) {
MulticastResult multicastResult = sender.send(msg, regIdsParts.get(i), 5);
if (multicastResult.getCanonicalIds() != 0) {
List<Result> results = multicastResult.getResults();
for (int j = 0; j < results.size(); j++) {
if (results.get(j).getMessageId() != null) {
log.info("Message sent to " + regIdsParts.get(i).get(j));
String canonicalRegId = results.get(j).getCanonicalRegistrationId();
if (canonicalRegId != null) {
// if the regId changed, we have to update the datastore
log.info("Registration Id changed for " + regIdsParts.get(i).get(j) + " updating to " + canonicalRegId);
regIdsParts.get(i).set(j, canonicalRegId);
ofy().save().entity(records.get((i*1000)+j)).now();
} else {
String error = results.get(j).getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
log.warning("Registration Id " + regIdsParts.get(i).get(j) + " no longer registered with GCM, removing from datastore");
// if the device is no longer registered with Gcm, remove it from the datastore
ofy().delete().entity(records.get((i*1000)+j)).now();
} else {
log.warning("Error when sending message : " + error);
}
}
}
}
}
}
}
}
Your code looks good, Only thing I can notice is its quite verbose and complicated. You can take a look at this one just as a option if you are considerate about error handling:
public void sendMessageToMultipleDevices(String key, String value, ArrayList devices) {
Sender sender = new Sender(myApiKey);
Message message = new Message.Builder().addData(key, value).build();
try {
MulticastResult result = sender.send(message, devices, 5);
MTLog.info(TAG, "result " + result.toString());
for (int i = 0; i < result.getTotal(); i++) {
Result r = result.getResults().get(i);
if (r.getMessageId() != null) {
String canonicalRegId = r.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// devices.get(i) has more than on registration ID: update database
}
} else {
String error = r.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from devices.get(i) - unregister database
}
}
}
} catch (IOException ex) {
MTLog.err(TAG, "sending message failed", ex);
}
}

Compare contents of two files line by line

public class MainActivity extends Activity {
FileOutputStream fos;
FileInputStream fOne, fTwo;
ArrayList<String> arr1 = new ArrayList<String>();
ArrayList<String> arr2 = new ArrayList<String>();
ArrayList<String> words = new ArrayList<String>();
ArrayList<String> wordsTwo = new ArrayList<String>();
int count = 0;
int countTwo = 0;
int countThree = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button fileOne = (Button)findViewById(R.id.file1);
Button fileTwo = (Button)findViewById(R.id.file2);
Button compare = (Button)findViewById(R.id.compare);
arr1.add("1");
arr1.add("2");
arr1.add("3");
arr1.add("4");
//arr1.add("3");
arr2.add("1");
arr2.add("2");
fileOne.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
fos = openFileOutput("File1", Context.MODE_PRIVATE);
for(int temp = 0; temp< arr1.size(); temp++)
{
fos.write((arr1.get(temp).getBytes()) );
fos.write(System.getProperty("line.separator").getBytes());
}
fos.close();
fos.flush();
}
catch(Exception e)
{
}
}
});
fileTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
fos = openFileOutput("File2", Context.MODE_PRIVATE);
for(int temp = 0; temp< arr2.size(); temp++)
{
fos.write((arr2.get(temp).getBytes()) );
fos.write(System.getProperty("line.separator").getBytes());
}
fos.close();
fos.flush();
}
catch(Exception e)
{
}
}
});
compare.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try
{
fOne = openFileInput("File1");
fTwo = openFileInput("File2");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner scanFile = new Scanner(new DataInputStream(fOne));
Scanner scanFileT = new Scanner(new DataInputStream(fTwo));
words = new ArrayList<String>();
wordsTwo = new ArrayList<String>();
while (scanFile.hasNextLine())
{
if(scanFile.nextLine()!=null)
{
count++;
}
while(scanFileT.hasNextLine())
{
if(scanFileT.nextLine()!=null)
{
countTwo++;
}
}
}
try
{
fOne.close();
fTwo.close();
scanFile.close();
scanFileT.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(getBaseContext(), "One : " + count, 1000).show();
Toast.makeText(getBaseContext(), "Two : " + countTwo, 1000).show();
Toast.makeText(getBaseContext(), "Three : " + countThree, 1000).show();
count = 0 ;
countTwo = 0;
countThree = 0;
}
});
}
}
Above is the code to write and read the file. What I did here, write two files and read the contents..Now I have to compare contents of files line by line. What needs to be done?
Try following code. This will give you desired output. I took files from asset directory. So you need to replace that line of code if you are taking files from other directory.
private void compareFiles() throws Exception {
String s1 = "";
String s2 = "", s3 = "", s4 = "";
String y = "", z = "";
// Reading the contents of the files
BufferedReader br = new BufferedReader(new InputStreamReader(
getAssets().open("first.txt")));
BufferedReader br1 = new BufferedReader(new InputStreamReader(
getAssets().open("second.txt")));
while ((z = br1.readLine()) != null) {
s3 += z;
s3 += System.getProperty("line.separator");
}
while ((y = br.readLine()) != null) {
s1 += y;
s1 += System.getProperty("line.separator");
}
// String tokenizing
StringTokenizer st = new StringTokenizer(s1);
String[] a = new String[10000];
for (int l = 0; l < 10000; l++) {
a[l] = "";
}
int i = 0;
while (st.hasMoreTokens()) {
s2 = st.nextToken();
a[i] = s2;
i++;
}
StringTokenizer st1 = new StringTokenizer(s3);
String[] b = new String[10000];
for (int k = 0; k < 10000; k++) {
b[k] = "";
}
int j = 0;
while (st1.hasMoreTokens()) {
s4 = st1.nextToken();
b[j] = s4;
j++;
}
// comparing the contents of the files and printing the differences, if
// any.
int x = 0;
for (int m = 0; m < a.length; m++) {
if (a[m].equals(b[m])) {
} else {
x++;
Log.d("Home", a[m] + " -- " + b[m]);
}
}
Log.d("Home", "No. of differences : " + x);
if (x > 0) {
Log.d("Home", "Files are not equal");
} else {
Log.d("Home", "Files are equal. No difference found");
}
}
Input File 1
Hi
Hello
Chintan
Rathod
Input File 2
Hi
HellO
Chintan
RathoD
Output
08-26 12:07:58.219: DEBUG/Home(2350): Hello3. -- HellO3.
08-26 12:07:58.219: DEBUG/Home(2350): Rathod -- RathoD
08-26 12:07:58.229: DEBUG/Home(2350): No. of differences : 2
08-26 12:07:58.229: DEBUG/Home(2350): Files are not equal
Edit
To get Difference between two files
Use StringUtils library which is provide by Apache and check this Documentation for more about that library.
And modify following lines of code.
int x = 0;
for (int m = 0; m < a.length; m++) {
if (a[m].equals(b[m])) {
} else {
x++;
Log.d("Home", a[m] + " -- " + b[m]);
//to print difference
if (a[m].length() < b[m].length())
Log.d("Home", "" + StringUtils.difference(a[m], b[m]));
else
Log.d("Home", "" + StringUtils.difference(b[m], a[m]));
}
}
Output
08-26 17:51:26.949: DEBUG/Home(17900): 12 -- 123
08-26 17:51:26.949: DEBUG/Home(17900): Difference String : 3
08-26 17:51:26.949: DEBUG/Home(17900): No. of differences : 1
08-26 17:51:26.949: DEBUG/Home(17900): Files are not equal
Try using java.util.Scanner
while (sc1.hasNext() && sc2.hasNext()) {
String str1 = sc1.next();
String str2 = sc2.next();
if (!str1.equals(str2))
System.out.println(str1 + " != " + str2);
}
Change your while loop to the following:
while (scanFile.hasNextLine() && scanFileT.hasNextLine())
{
if(scanFileT.nextLine().equals(scanFile.nextLine()))
{
// The lines are equal.
} else {
// The lines are not equal.
}
}
if(scanFile.hasNextLine() || scanFileT.hasNextLine())
{
// If more lines remain in one of the files, they are not equal.
} else {
// If no content remains in both files, they are equal.
}
Depending on the size of your file, I would recommend some optimisation like checking the file sizes before you go through them line by line.
The overall logic reads as follows; if both have another line, compare it to see if it is equal. If they don't have another line, check if one of them has lines remaining, if so, they are not equal.
Update
After clarifying the objective of the comparison in chat, see the comments to this question, I have come to the conclusion that another comparison would be more effective and, as a matter of fact, correct. The comparison algorithm above works great if comparing the structure of text but not if comparing a data vector which may or may not be sorted. After some discussion, we came to the conclusion that data needs to be sorted or the comparison will blow the complexity to at least O(n^2)which could be done in O(2n) if the data is sorted. Here the algorithm's skeleton:
if(! scanGroupFriends.hasNextLine())
{
//simple sanity check to see if we need to compare at all. In this case, add all friends.
} else {
String nextFriend = scanGroupFriends.nextLine();
while(scanAllFriends.hasNextLine())
{
if(scanAllFriends.nextLine().equals(nextFriend))
{
// Friend already figures, do not add him and advance the list of group friends.
if(scanGroupFriends.hasNextLine())
{
nextFriend = scanGroupFriends.nextLine();
} else {
// There are no more friends in the group, add all remaining friends to list to show.
break; // Terminate the `while` loop.
}
}
}
}
However, I personally think it is bad to make to many assumptions. What I would suggest is that the friends be saved in a Set, a TreeSet for example. Then, serialize the object rather than manually writing it to file. Sets are neat because they hold several interesting objects. For example, you could easily use the following code to remove all friends in a group from the set of all friends:
allFriends.removeAll(groupFriends);
However, be aware that this removes it from the set completely so you should make a copy beforehand.

Cant read file in android

I am using this code in my project. I need to read .xls which i have placed in my raw folder.
ReadExcel test = new ReadExcel();
test.setInputFile(BitmapFactory.decodeStream(getClass().getResourceAsStream(("/SPPDashProject/res/raw/aging_busket_key.xls"))).toString());
try {
test.read();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
public class ReadExcel {
private String inputFile;
public void setInputFile(String inputFile) {
this.inputFile = inputFile;
}
public void read() throws IOException {
File inputWorkbook = new File(inputFile);
Workbook w;
try {
w = Workbook.getWorkbook(inputWorkbook);
// Get the first sheet
Sheet sheet = w.getSheet(0);
// Loop over first 10 column and lines
for (int j = 0; j < sheet.getColumns(); j++) {
for (int i = 0; i < sheet.getRows(); i++) {
Cell cell = sheet.getCell(j, i);
CellType type = cell.getType();
if (cell.getType() == CellType.LABEL) {
System.out.println("I got a label: "
+ cell.getContents());
}
if (cell.getType() == CellType.NUMBER) {
System.out.println("I got a number "
+ cell.getContents());
}
}
}
} catch (BiffException e) {
e.printStackTrace();
}
}
}
what path should i give as my main read class takes path in string format.Plz suggest
You can use the following code:
Uri uri=Uri.parse("android.resource://com.mypackage.myapp" + R.raw.MyXLS);
String filePath=uri.getPath();
You should use the following code to open file in the /res/raw
getResources().openRawResource(R.raw.yourfilename)
You can put your file in the assets folder and use AssetManager to acess it.

Categories

Resources