I am writing an Android program that parses data from the Translink API web page. The program works, but I am having an issue with the data that I am storing. It seems that each time the program loops, a "\n" is added to the String itself. Here is the code itself:
private class DownloadWebpageText extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String...urls) {
// params comes from the execute() call: params[0] is the url.
try {
// Test Code
for(int h=0; h<prev_stops.size(); h++) {
Document doc = Jsoup.connect("http://api.translink.ca/rttiapi/v1/stops/" + prev_stops.get(h) + "/estimates?&timeframe=120&apikey=XMy98rbwFPLcWWmNcKHc").get();
nextbuses = doc.select("nextbus");
schedules = doc.select("schedules");
String bus_times = "";
temp += "Arrival Times for Stop " + prev_stops.get(h) /*+ " (Previous Stop: " + prev_stop + "): \n" + "\nPrevious Stops: " + prev_stop*/;
for(int i=0; i<nextbuses.size(); i++) {
temp += parseData(nextbuses.get(i).select("routeno").toString()) + ": ";
schedule = schedules.get(i).children();
expectedleavetime = schedule.select("expectedleavetime");
for(int j=0; j<expectedleavetime.size(); j++) {
if(j != 0) {
temp = temp.concat(", ");
}
temp = temp.concat(parseData(expectedleavetime.get(j).toString()));
}
temp += "\n";
}
temp += "\n";
}
return "";
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
Where the parseData() function is just this:
public String parseData(String input) {
int beg = input.indexOf(">") + 1;
int end = input.lastIndexOf("<") - 1;
return input.substring(beg, end);
}
Here is the output from the console:
Arrival Times for Stop 56549
402:
4:10pm,
4:40pm,
5:10pm,
5:40pm
What I want the output to be like is this:
Arrival Times for Stop 56549
402: 3:40pm, 4:10pm, 4:40pm, 5:10pm
403: .....
You could use an ArrayList, which you define outside all for-loops
// Define our ArrayList
ArrayList<String> allStops = new ArrayList<String>();
// Define a string that holds information about the current stop
String currentStopInfo = "Arrival Times for Stop " + prev_stops.get(h);
for(int i=0; i<nextbuses.size(); i++) {
// Define a temporary String that holds all the times for a specific bus
String temp_2 = parseData(nextbuses.get(i).select("routeno").toString()) + ": ";
schedule = schedules.get(i).children();
expectedleavetime = schedule.select("expectedleavetime");
for(int j=0; j<expectedleavetime.size(); j++) {
if(j != 0) {
temp_2 += ", ";
}
temp_2 = temp_2.concat(parseData(expectedleavetime.get(j).toString()));
}
// Add the string that holds info for one bus to our Array
allStops.add(temp_2);
}
And when you want to print all of your strings(all of your stops for each bus)(every string contains information about one bus) you just do:
//Print the line that holds the current stop information
System.out.println(currentStopInfo);
for(String x : allStops) {
// Loop through our ArrayList, and print the information
System.out.println(x);
}
Related
This is method stopPing() in MainActivity to save data to realm.
If I want to use data in realm from another class, how can I coding.
private void stopPing() {
linkEdt.setEnabled(true);
pingBtn.setText("Start Ping");
isPing = false;
count = 0;
endTime = getTime();
/* Open the Realm for the UI thread. */
realm = Realm.getInstance(realmConfig);
/* All writes must be wrapped in a transaction to facilitate safe multi threading */
realm.beginTransaction();
Ping ping = realm.createObject(Ping.class);
/* Add ip */
ping.set_ip(ip);
/* Add start time */
ping.set_startTime(startTime);
/* Add end time. */
ping.set_endTime(endTime);
/* Add down amount */
ping.set_downAmount(downtime);
/* Add ping speed time. */
PingTime pingtime = realm.createObject(PingTime.class);
for(Double speedTime : speedList){
pingtime.time = speedTime;
ping.get_times().add(pingtime);
}
/* Add time. */
for(String time : timeList){
pingtime.pingTime = time;
ping.get_pingTime().add(pingtime);
}
realm.commitTransaction();
/* stop handler. */
this.mHandler.removeCallbacks(m_Runnable);
}
When I want to query in another class it has error with realm -->> io.realm.Realm.allObjects(java.lang.Class)' on a null object reference
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ping_list);
for (Ping pers : realm.allObjects(Ping.class)) {
String startT, endT;
if (pers.get_stratTime() == null) {
startT = "None";
} else {
startT = pers.get_stratTime();
}
if (pers.get_endTime() == null) {
endT = "None";
} else {
endT = pers.get_endTime();
}
status += "Start time: " + startT + "\n End time: " + endT + "\n";
status += "Ping total: " + pers.get_times().size() + "\n";
status += "Down amount: " + pers.get_downAmount() + " time.\n";
for (int i = 0; i < pers.get_times().size(); i++) {
double speed = pers.get_times().get(i).time;
String time = pers.get_pingTime().get(i).pingTime;
status += "time (" + (i + 1) + "): " + speed + " ms. at " + time + ".\n";
}
}
System.out.println(status);
}
How are you creating the realm instance in the 2nd class? If you didn't call realm = Realm.getInstance(...) the variable will be null, resulting in the NullPointerException you are seeing.
I am trying to sort a list of array based on the name in alphabetical order which contain type, name, url and date. I retrieved the information from Browser.BookmarkColumns except for type.
Before:
Default Browser Google www.Google.com 14/12/2013
Default Browser BBC www.BBC.com 13/12/2015
Default Browser Amazon www.Amazon.com 11/11/2014
After:
Default Browser Amazon www.Amazon.com 11/11/2014
Default Browser BBC www.BBC.com 13/12/2015
Default Browser Google www.Google.com 14/12/2013
Here is what i have tried but it is not working.
int j = mCur.getCount();
String[] mType = new String[j];
String[] mTitles = new String[j];
String[] murls = new String[j];
long[] date = new long[j];
for (int q=0; q<(j-1); q++) {
String a = (mTitles[q]).toLowerCase();
String b = (mTitles[q+1].toLowerCase());
char[] c = a.toCharArray();
char[] d = b.toCharArray();
String temp, temp2, temp3 = null;
long temp4 = 0;
int lenc = c.length;
int lend = d.length;
int min =0;
int count =0;
if (lenc < lend)
min = lenc;
else
min = lend;
if (c[count] > d[count]) {
temp = mTitles[count];
temp2 = mType[count];
temp3 = murls[count];
temp4 = date[count];
mTitles[count] = mTitles[count + 1];
mType[count] = mType[count + 1];
murls[count] = murls[count + 1];
date[count] = date[count + 1];
mTitles[count + 1] = temp;
mType[count + 1] = temp2;
murls[count + 1] = temp3;
date[count + 1] = temp4;
} else if (c[count] == d[count]) {
for (int w = 1; w < min; w++) {
if (c[w] > d[w]) {
temp = mTitles[w];
temp2 = mType[w];
temp3 = murls[w];
temp4 = date[w];
mTitles[w] = mTitles[w + 1];
mType[w] = mType[w + 1];
murls[w] = murls[w + 1];
date[w] = date[w + 1];
mTitles[w + 1] = temp;
mType[w + 1] = temp2;
murls[w + 1] = temp3;
date[w + 1] = temp4;
}
}
}
}
Above answers are giving best example for efficient sorting Array list in java.
Before it please read description of above mentioned answer here
I just simplified above answer for your better understanding it gives exact output what u required.
ArrayList<UserContainer> userList = new ArrayList<>();
userList.add(new UserContainer("www.Google.com", "Google", "14/12/2013"));
userList.add(new UserContainer("www.BBC.com", "BBC", "13/12/2015"));
userList.add(new UserContainer("www.Amazon.com", "Amazon", "11/11/2014"));
Log.i("Before Sorting :", "==========================>>");
for (UserContainer obj : userList) {
System.out.println("Default Browser: \t" + obj.name + "\t" + obj.date + "\t" + obj.webSite);
}
Collections.sort(userList, new Comparator<UserContainer>() {
#Override
public int compare(UserContainer first, UserContainer second) {
return first.name.compareToIgnoreCase(second.name);
}
});
Log.i("After Sorting :", "==========================>>");
for (UserContainer obj : userList) {
System.out.println("Default Browser: \t" + obj.name + "\t" + obj.date + "\t" + obj.webSite);
}
Model Class:
public class UserContainer {
public UserContainer(String webSite, String name, String date) {
this.webSite = webSite;
this.name = name;
this.date = date;
}
public String webSite = "";
public String name = "";
public String date = "";
}
First of all it would be much simplier task if instead of sorting 3 string arrays + long array You encapsulate all the fields and create a class (lets call it MyData) containing all four fields. Then you can use put all newly create objects in some collection (for example ArrayList).
So, when you have your ArrayList<MyData> you can easliy use Collections.sort passing both your list and implementation of Comparator<T> interface where all the sorting logic would be.
For example, if you want to sort whole list using only String title field it can look like this:
Comparator<MyData> with implemented compare function compare(MyData o1, MyData o2){return o1.title.compareTo(o2);
My advice to create custom array list.
private ArrayList<UserContainer> userList=new ArrayList<UserContainer>();
UserContainer usercontainer=new UserContainer()
usercontainer.name=Amazon;
usercontainer.date=11/11/2014;
userList.add(usercontainer);
UserContainer usercontainer2=new UserContainer()
usercontainer.name=Google;
usercontainer.date=11/11/2014;
userList.add(usercontainer);
UserContainer usercontainer3=new UserContainer()
usercontainer.name=BBC;
usercontainer.date=11/11/2014;
userList.add(usercontainer);
Collections.sort(userList, new Comparator<UserContainer>() {
#Override
public int compare(UserContainer s1, UserContainer s2) {
return s1.name.compareToIgnoreCase(s2.name);
}
});
Model:-
public class UserContainer {
public String name = "";
public String date = "";
}
I hope to help you.
Create a class and use comparator or comparable.
for further reference please check (How to sort an ArrayList in Java)
Arrays.sort(stringArray);
Its a nice way to sort.
I recommend you to create a Object for example 'BrowserStoredData' for each element of the list. With the strings required:
public class BrowserStoredData implements Comparable<BrowserStoredData> {
String browserType;
String browserName;
String browserUrl;
String browserDate;
public BrowserStoredData(String browserType, String browserName,
String browserUrl, String browserDate) {
super();
this.browserType = browserType;
this.browserName = browserName;
this.browserUrl = browserUrl;
this.browserDate = browserDate;
}
public int compareTo(BrowserStoredData bsd) {
return (this.browserName).compareTo(bsd.browserName);
}
#Override
public String toString() {
return browserType + "\t\t" + browserName + "\t\t" + browserUrl
+ "\t\t" + browserDate;
}
}
With that object you easily can order a list of BrowserStoredData objects simply by using Collections.sort(yourList)
For example:
BrowserStoredData bsd1 = new BrowserStoredData("Default Browser", "Google", "www.Google.com", "14/12/2013");
BrowserStoredData bsd2 = new BrowserStoredData("Default Browser", "BBC", "www.BBC.com", "13/12/2015");
BrowserStoredData bsd3 = new BrowserStoredData("Default Browser", "Amazon", "www.Amazon.com", "11/11/2014");
List<BrowserStoredData> listBrowsers = new ArrayList<BrowserStoredData>();
listBrowsers.add(bsd1);
listBrowsers.add(bsd2);
listBrowsers.add(bsd3);
Collections.sort(listBrowsers);
for (int i = 0 ; i < listBrowsers.size() ; i++){
BrowserStoredData bsd = listBrowsers.get(i);
System.out.println(bsd.toString());
}
The exit will be:
Default Browser Amazon www.Amazon.com 11/11/2014
Default Browser BBC www.BBC.com 13/12/2015
Default Browser Google www.Google.com 14/12/201
I hope you can help me.
I make a game like 4Pics1Word.
I want to load the Level Randomly, I want a loop which generate a Random number from 0 to 10, and then check if the generated number is the first time loaded.
If yes write it in an array and end the loop.
If the number is not the first time loaded, generate a new random number and check it again until it is not used.
For example this is my code (donĀ“t work right):
Boolean usedImageSet = false;
for (int t = 0; t <= usedImages.length; t++) {
if (usedImageSet == false) {
StringBuilder sb = new StringBuilder();
sb.append(currentQuestion);
String used = sb.toString();
if (usedImages[t] != null) {
System.out.println("usedImage" + t
+ " = not Null, it is" + usedImages[t]);
if (usedImages[t].equals(used)) {
System.out.println("String: "
+ used
+ " found it here: [" + t + "]");
currentQuestion = (int) (Math.random() * 10);
}else {
System.out.println("String: "
+ used + " not found");
}
}
if (usedImages[t] == null) {
usedImages[t] = used;
System.out.println("useddImage[" + t + "]: "
+ usedImages[t]);
System.out.println("usedImage" + t + " is Null, change to"
+ usedImages[t]);
usedImageSet = true;
}
}
}
PS:
Thank you all, I think the solution from Oren is the best
// naive implementation
ArrayList<Integer> list = new ArrayList();
for(int i=0; i<10; i++)
{
list.add(i);
}
Collections.shuffle(list);
// output the generated list
for(int i=0; i<10; i++)
{
System.out.print(list.get(i));
}
But how can I save the list if I close the game?
You would probably be much better off creating a List of the numbers you want and then calling Collections.shuffle() on that list.
// naive implementation
ArrayList<Integer> list = new ArrayList();
for(int i=0; i<10; i++)
{
list.add(i);
}
Collections.shuffle(list);
// output the generated list
for(int i=0; i<10; i++)
{
System.out.print(list.get(i));
}
int oldnumber = 5;
int newnumber = new Random().nextInt(10);
while (newnumber == oldnumber){
newnumber = new Random().nextInt(10);
}
JSON is only displaying the last object '100 g' of "serving_description" in the JSON Formatted Data, See below. instead of all of the "serving_description" objects.
The Array is serving
If you look at the JSON Formatted Data below you will see that there are multiple "serving_description" 's.
I am trying to get the "serving_description" of all of the the available options to display instead of the last object in which it is displaying. How do I display all of the "serving_descriptions"?
I believe the error lies in, but I can be wrong, that is why I am asking :
for (int n = 0; n < foodName.length(); n++) {
JSONObject object = foodName.getJSONObject(n);
String shit = object.getString("serving_description");
Log.v("FATSEC", "" + shit);
ret = shit + "";
}
Class, AsyncTask
#Override
public void onClick(View v) {
new AsyncTask<String, String, String>() {
#Override
protected String doInBackground(String... arg0) {
search = (EditText) findViewById(R.id.editText1);
String SEARCH = search.getText().toString();
JSONObject food = getFood(SEARCH);
Log.v("FATSEC", "TEST");
String ret = "";
try {
JSONArray foodName = food.getJSONObject("food")
.getJSONObject("servings")
.getJSONArray("serving");
for (int n = 0; n < foodName.length(); n++) {
JSONObject object = foodName.getJSONObject(n);
String shit = object
.getString("serving_description");
Log.v("FATSEC", "" + shit);
ret = shit + "";
}
} catch (JSONException e) {
e.printStackTrace();
}
return ret;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// ans.setText("# of Servings: " + result);
ans.setText("Servings: " + result);
}
}.execute();
}
});
Formatted JSON DATA
{
"servings":{
"serving":[
{
"vitamin_a":"0",
"calcium":"2",
"serving_description":"1 cup cooked",
"vitamin_c":"0",
"carbohydrate":"44.08",
"metric_serving_unit":"g",
"fat":"0.44",
"sodium":"577",
"polyunsaturated_fat":"0.119",
"fiber":"0.6",
"cholesterol":"0",
"iron":"10",
"serving_id":"16834",
"protein":"4.20",
"monounsaturated_fat":"0.138",
"potassium":"55",
"number_of_units":"1.000",
"calories":"204",
"measurement_description":"cup, cooked",
"saturated_fat":"0.120",
"metric_serving_amount":"158.000",
"sugar":"0.08",
"serving_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular?portionid=16834&portionamount=1.000"
},
{
"vitamin_a":"0",
"calcium":"6",
"serving_description":"1 cup, dry, yields",
"vitamin_c":"0",
"carbohydrate":"159.03",
"metric_serving_unit":"g",
"fat":"1.60",
"sodium":"2080",
"polyunsaturated_fat":"0.429",
"fiber":"2.3",
"cholesterol":"0",
"iron":"38",
"serving_id":"15284",
"protein":"15.16",
"monounsaturated_fat":"0.497",
"potassium":"200",
"number_of_units":"1.000",
"calories":"735",
"measurement_description":"cup, dry, yields",
"saturated_fat":"0.432",
"metric_serving_amount":"570.000",
"sugar":"0.29",
"serving_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular?portionid=15284&portionamount=1.000"
},
{
"vitamin_a":"0",
"calcium":"1",
"serving_description":"1 oz, dry, yields",
"vitamin_c":"0",
"carbohydrate":"24.27",
"metric_serving_unit":"g",
"fat":"0.24",
"sodium":"318",
"polyunsaturated_fat":"0.065",
"fiber":"0.3",
"cholesterol":"0",
"iron":"6",
"serving_id":"18252",
"protein":"2.31",
"monounsaturated_fat":"0.076",
"potassium":"30",
"number_of_units":"1.000",
"calories":"112",
"measurement_description":"oz, dry, yields",
"saturated_fat":"0.066",
"metric_serving_amount":"87.000",
"sugar":"0.04",
"serving_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular?portionid=18252&portionamount=1.000"
},
{
"vitamin_a":"0",
"calcium":"1",
"serving_description":"1 serving (105 g)",
"vitamin_c":"0",
"carbohydrate":"29.30",
"metric_serving_unit":"g",
"fat":"0.29",
"sodium":"383",
"polyunsaturated_fat":"0.079",
"fiber":"0.4",
"cholesterol":"0",
"iron":"7",
"serving_id":"17592",
"protein":"2.79",
"monounsaturated_fat":"0.092",
"potassium":"37",
"number_of_units":"1.000",
"calories":"135",
"measurement_description":"serving (105g)",
"saturated_fat":"0.080",
"metric_serving_amount":"105.000",
"sugar":"0.05",
"serving_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular?portionid=17592&portionamount=1.000"
},
{
"vitamin_a":"0",
"calcium":"1",
"serving_description":"100 g",
"vitamin_c":"0",
"carbohydrate":"27.90",
"metric_serving_unit":"g",
"fat":"0.28",
"sodium":"365",
"polyunsaturated_fat":"0.075",
"fiber":"0.4",
"cholesterol":"0",
"iron":"7",
"serving_id":"53181",
"protein":"2.66",
"monounsaturated_fat":"0.087",
"potassium":"35",
"number_of_units":"100.000",
"calories":"129",
"measurement_description":"g",
"saturated_fat":"0.076",
"metric_serving_amount":"100.000",
"sugar":"0.05",
"serving_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular?portionid=53181&portionamount=100.000"
}
]
},
"food_url":"http:\/\/www.fatsecret.com\/calories-nutrition\/generic\/rice-white-cooked-regular",
"food_type":"Generic",
"food_name":"White Rice",
"food_id":"4501"
}
Use + to append all serving_description value in ret as:
ret += shit + "\n\n";
Each iteration of the loop overrides the value of ret so that you are never able to accumulate them. For this reason, when you return it has the last value you stored there and none of the previous values that were wiped out. Consider using a StringBuilder.
StringBuilder builder = new StringBuilder();
...
for (int n = 0; n < foodName.length(); n++) {
JSONObject object = foodName.getJSONObject(n);
String shit = object.getString("serving_description");
Log.v("FATSEC", "" + shit);
builder.append(shit).append("\n");
}
...
return builder.toString();
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.