I can display the information of my phone application but I am restricted to display only six.
I would like to know how to proceed to display the rest of the elements ( i have a list of 17 elements).
For the moment I use the first and last columns of my Template to do an invalidate() and display the previous or next items of my list
public Template onGetTemplate() {
ListTemplate.Builder templateBuilder = new ListTemplate.Builder();
ItemList.Builder sectionABuilder = new ItemList.Builder();
if(compteur < 4 ) {
try {
if (DataMgr.getInstance().getDataListAdress().size() > 0 && compteur < DataMgr.getInstance().getDataListAdress().get(0).length) {
for (int i = compteur; i < compteur + 5; i++) {
System.out.println("////Test + " + DataMgr.getInstance().getDataListAdress().get(0)[i]);
System.out.println("////TestLength + " + DataMgr.getInstance().getDataListAdress().get(0).length);
sectionABuilder.addItem(buildRow(DataMgr.getInstance().getDataListAdress().get(0)[i]));
}
}
sectionABuilder.addItem(buildRowClick("Suivant"));
templateBuilder.addSectionedList(
SectionedItemList.create(sectionABuilder.build(), "Header"));
} catch (Exception e) {
CarToast.makeText(getCarContext(), "No more", CarToast.LENGTH_SHORT).show();
}
} else {
sectionABuilder.addItem(buildRowClickPrecedent("Precedent"));
try {
if (DataMgr.getInstance().getDataListAdress().size() > 0 && compteur < DataMgr.getInstance().getDataListAdress().get(0).length) {
for (int i = compteur; i < compteur + 4; i++) {
System.out.println("////Test + " + DataMgr.getInstance().getDataListAdress().get(0)[i]);
System.out.println("////Test +" + DataMgr.getInstance().getDataListAdress().get(0).length);
sectionABuilder.addItem(buildRow(DataMgr.getInstance().getDataListAdress().get(0)[i]));
}
}
sectionABuilder.addItem(buildRowClick("Suivant"));
templateBuilder.addSectionedList(
SectionedItemList.create(sectionABuilder.build(), "Header"));
} catch (Exception e) {
CarToast.makeText(getCarContext(), "No more", CarToast.LENGTH_SHORT).show();
}
}
return templateBuilder
.setHeaderAction(Action.PAN)
.setTitle("ok")
.build();
}
#NonNull
private Row buildRow(String data) {
return new Row.Builder()
.setTitle(data)
.build();
}
#NonNull
private Row buildRowClick(String data) {
return new Row.Builder()
.setOnClickListener(new OnClickListener() {
#Override
public void onClick() {
compteur += 4;
invalidate();
}
})
.setTitle(data)
.build();
}
You can't use it like this. Use ConstraintManager.class.
Lists are limited by unit you have in a car. But there is special API to handle this.
Check ConstraintManager:
int listLimit = Math.min(MAX_LIST_ITEMS,
getCarContext().getCarService(ConstraintManager.class).getContentLimit(
ConstraintManager.CONTENT_LIMIT_TYPE_LIST));
Docs: https://developer.android.com/reference/androidx/car/app/constraints/ConstraintManager
You can take this limit count and interate your list only based on this number.
Related
i want to make app With Rest Api and Retrofit. i want to load Random posts when user pull down the RecyclerView, i made it but one thing that is annoying, when i load Random posts. it display after the first 10 posts, i mean after home page's 10 posts but i want to clear the old posts and display random posts from row 1.
the code i am using for scroll up
else if (!recyclerView.canScrollVertically(-1) && dy < 0)
{
yourURL1 = baseURL + baseModel + "&orderby=rand&page=" + pageNo++;
getRetrofit1();
}
Retrofit
try {
List<Model> list = new ArrayList<>();
Call<List<WPPost>> call = service.getPostInfo( yourURL);
call.enqueue(new Callback<List<WPPost>>() {
#Override
public void onResponse(Call<List<WPPost>> call, Response<List<WPPost>> response) {
Log.d("==>>", " response "+ response.body());
mListPost = response.body();
progressBar.setVisibility(View.GONE);
if (response.body() != null) {
for (int i = 0; i < response.body().size(); i++ ) {
Log.d("==>>", " title " + response.body().get(i).getTitle().getRendered() + " " +
response.body().get(i).getId());
String tempdetails = String.valueOf((Html.fromHtml(response.body().get(i).getExcerpt().getRendered().toString())));
tempdetails = tempdetails.replace("<p>", "");
tempdetails = tempdetails.replace("</p>", "");
tempdetails = tempdetails.replace("[…]", "");
list.add(new Model(String.valueOf((Html.fromHtml(response.body().get(i).getTitle().getRendered()))),
tempdetails, response.body().get(i).getPostViews().toString(),
response.body().get(i).getImages().getMedium(),response.body().get(i).getContent().getRendered()));
}
if (loading){
loading = false;
adapter.showHideProgress(false);
}
adapter.addItemsToList(list);
progressBar.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.GONE);
}
}
#Override
public void onFailure(Call<List<WPPost>> call, Throwable t) {
}
});
}catch (Exception exception){
Log.d("tisha==>>"," "+exception.getLocalizedMessage());
}
In adapter
void addItemsToList(List<Model> newItems){
if (dataset.isEmpty()){
dataset.addAll(newItems);
notifyDataSetChanged();
Log.d("tisha==>>","First time List size = "+dataset.size());
}else {
int lastItemPosition = dataset.size() -1;
Log.d("tisha==>>","Old list size = "+dataset.size()+ "Last Item position= "+lastItemPosition);
dataset.addAll(newItems);
Log.d("tisha==>>","Update List size = "+dataset.size());
notifyItemRangeInserted(lastItemPosition,newItems.size());
}
}
how can i clear list ?
once this list is set you are adding items to list , you have to remove elements first notify item ranged removed then add new and update on notify item inserted
void addItemsToList(List<Model> newItems)
{ if (dataset.isEmpty())
{ dataset.addAll(newItems);
notifyDataSetChanged();
Log.d("tisha==>>","First time List size = "+dataset.size());
}
else
{
int lastItemPosition = dataset.size() -1;
Log.d("tisha==>>","Old list size = "+dataset.size()+ "Last Item position= "+lastItemPosition); dataset.addAll(newItems);
Log.d("tisha==>>","Update List size = "+dataset.size()); notifyItemRangeInserted(lastItemPosition,newItems.size()); } }
Can someone please show me how I can pause my code in onCreate() until the event listener getting data from my firebase realtime DB has completed?
I have been stuck on this for a while now, anything that does not involve me completely reformatting my code would be awesome.
My code works but when getting data from the firebase my code continues to run without waiting for the EventListener to recieve the data...
I need to be able to stop the code but I do not know how...
-Just a suggestion: is it possible to use Thread.wait() and Thread.notify()?
I don't understand how threads/tasks/runnables work that well so a good explanation would be appreciated.
public void createNullRoom() {
room.setPlayerWhoIsSpyer(0);
room.add(1);
room.add(2);
room.add(3);
room.add(4);
room.add(5);
room.add(6);
room.setRoomCode("room_0");
room.setWinner(0);
room.setScene(0);
room.setRoundHasEnded(true);
room.setSecretWord("");
this.gameRoom.add(0,room);
pref.child(room.getRoomCode()).setValue(room);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.w(this.getClass().getName() + ".java/" + new Throwable().getStackTrace()[0].getLineNumber(), "Game.onCreate");
setContentView(R.layout.gameview_public);
pId = 0;
room = new Room();
AssignUser = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
gameRoom.clear();
long v = snapshot.child("gameRoom").getChildrenCount();
int count = (int) v;
for (int i = 0; i < count + 1; i++) {
Room r = new Room();
boolean temp = true;
try {
r = snapshot.child("gameRoom").child("room_" + i).getValue(Room.class);
} catch (IndexOutOfBoundsException e) {
temp = false;
}
if (temp) {
gameRoom.add(r);
}
}
Log.i(this.getClass().getName() + ".java/" + new Throwable().getStackTrace()[0].getLineNumber(), "gameRoom data retrieved");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
};
// ---- VALUE EVENT LISTENER TO GET DATA ------
AssignUser = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
gameRoom.clear();
long v = snapshot.child("gameRoom").getChildrenCount();
int count = (int) v;
for (int i = 0; i < count + 1; i++) {
Room r = new Room();
boolean temp = true;
try {
r = snapshot.child("gameRoom").child("room_" + i).getValue(Room.class);
} catch (IndexOutOfBoundsException e) {
temp = false;
}
if (temp) {
gameRoom.add(r);
Log.i(this.getClass().getName() + ".java/" + new Throwable().getStackTrace()[0].getLineNumber(), "\tSize: " + gameRoom.size());
}
}
Log.i(this.getClass().getName() + ".java/" + new Throwable().getStackTrace()[0].getLineNumber(), "gameRoom data retrieved");
Log.e(this.getClass().getName() + ".java/" + new Throwable().getStackTrace()[0].getLineNumber(), "inside the snapshot, gamerooms.size: " + gameRoom.size() + " line 343");
assignUser();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
};
// ------------------------------------------------
ref.addListenerForSingleValueEvent(AssignUser);
createNullRoom();
// ===================================THIS NEEDS TO PAUSE HERE
int i = 0;
while(playerjoined == false) {
boolean exists = true;
Log.i(this.getClass().getName() +".java/"+ new Throwable().getStackTrace()[0].getLineNumber(), "line 431: if");
try {
this.room = this.gameRoom.get(i);
} catch (IndexOutOfBoundsException e) {
exists = false;
}
if (exists) {
this.room = gameRoom.get(i);
this.roomcode = this.room.getRoomCode();
for (int q = 1; q < 7; q++) {
if(this.getFalse() == q) {
this.room.add(q);
this.pref.child(this.roomcode).setValue(this.room);
this.pId = q;
q = 6;
playerjoined = true;
}
}
if(playerjoined == false) {
i++;
}
} else {
CreateNewPublicRoom(i);
Log.i(this.getClass().getName() +".java/"+ new Throwable().getStackTrace()[0].getLineNumber(), "Game.java/" + Thread.currentThread().getStackTrace()[1].getLineNumber() + "\tNew Public Room Made");
pref.child(this.roomcode).setValue(this.room);
Log.e(this.getClass().getName() +".java/"+ new Throwable().getStackTrace()[0].getLineNumber(),"OUTSIDE the snapshot, gamerooms.size: " + gameRoom.size() + " line 403");
Log.i(this.getClass().getName() +".java/"+ new Throwable().getStackTrace()[0].getLineNumber(), "\tThis.playerjoined == "+playerjoined);
}
}
ref.child("gameRoom").child(this.room.getRoomCode()).setValue(this.room)
etc...
I am using Raspberry pi3 and DHT11 sensor for temperature monitoring project.
I have following pin positions
VCC to pin no : 2
Ground to pin no : 6
Output to GPIO : BCM22 i.e pin no 15
Code that I have used:
public class WeatherStationActivity extends Activity {
private Handler mHandler = new Handler();
private TextView mTxtStatus;
private PeripheralManagerService service = new PeripheralManagerService();
private Gpio tempGpio;
private int i = 0;
int[] dht11_dat = {0, 0, 0, 0, 0};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("Weather station", "Started Weather Station");
setContentView(R.layout.activity_main);
mTxtStatus = (TextView) findViewById(R.id.txtStatus);
try {
tempGpio = service.openGpio("BCM22");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (i == 10) {
handler.removeCallbacks(this);
} else {
getTemp();
handler.postDelayed(this, 5000);
}
i++;
}
}, 5000);
} catch (Exception e) {
e.printStackTrace();
}
}
private void getTemp() {
boolean laststate = false;
try {
laststate = tempGpio.getValue();
} catch (IOException e) {
e.printStackTrace();
}
int j = 0;
final int MAXTIMINGS = 85;
dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;
try {
tempGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
// tempGpio.setActiveType(Gpio.ACTIVE_LOW);
tempGpio.setValue(false);
// Thread.sleep(18);
TimeUnit.MILLISECONDS.sleep(18);
// tempGpio.setActiveType(Gpio.ACTIVE_HIGH);
// tempGpio.setActiveType(Gpio.ACTIVE_HIGH);
tempGpio.setValue(true);
TimeUnit.MICROSECONDS.sleep(40);
tempGpio.setDirection(Gpio.DIRECTION_IN);
/* tempGpio.setActiveType(Gpio.ACTIVE_HIGH);
tempGpio.setValue(true);*/
// tempGpio.setValue(true);
StringBuilder value = new StringBuilder();
for (int i = 0; i < MAXTIMINGS; i++) {
int counter = 0;
while (tempGpio.getValue() == laststate) {
counter++;
TimeUnit.MICROSECONDS.sleep(1);
if (counter == 255) {
break;
}
}
laststate = tempGpio.getValue();
mTxtStatus.append("\nLast State of Sensor " + laststate);
if (counter == 255) {
break;
}
//* ignore first 3 transitions *//*
if ((i >= 4) && (i % 2 == 0)) {
//* shove each bit into the storage bytes *//*
dht11_dat[j / 8] <<= 1;
if (counter > 16) {
dht11_dat[j / 8] |= 1;
}
j++;
}
}
// check we read 40 bits (8bit x 5 ) + verify checksum in the last
// byte
if ((j >= 40) && checkParity()) {
value.append(dht11_dat[2]).append(".").append(dht11_dat[3]);
Log.i("Logger", "temperature value readed: " + value.toString());
mTxtStatus.append("\nTemp " + value.toString());
} else {
mTxtStatus.append("\nNothing is working ");
Log.i("Logger", "Nothing is working ");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private boolean checkParity() {
return dht11_dat[4] == (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3] & 0xFF);
}
}
Above code is giving me "Nothing is working" as output.
Any suggestion where I might be doing wrong?
You can't read data from DHT11 using Raspberry Pi 3 with Android Things because duration of DHT11 response pulses is from 26-28 us to 70 us, but max frequency of RP3 with AT GPIO is around 3kHz, which means around 300 us pulse duration. Take a look at answers to this question.
I'm still newbie and I need help to coding my Android Studio >0<
I can't to send a long data, although I change the size of "buffer". What should I do ?
This is the receiver program :
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
while (!bStop) {
byte[] buffer = new byte[1024];
if (inputStream.available() > 0)
{
inputStream.read(buffer);
int i = 0;
/*
* This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
*/
for (i = 0; i < buffer.length && buffer[i] != 0; i++) {}
final String strInput = new String(buffer, 0, i);
/*
* If checked then receive text, better design would probably be to stop thread if unchecked and free resources, but this is a quick fix
*/
}
Thread.sleep(500);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This are the sender program :
public void sendStringBT(String s)
{
try {
mBTSocket.getOutputStream().write(s.getBytes());
sleep();
Toast.makeText(getApplicationContext(), "Sent...", Toast.LENGTH_SHORT).show();
mBTSocket.getOutputStream().flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This is how to we call to send data :
sendStringBT(dataPage6); //send data via Bluetooth
I think the problem is in the design of the receiver (using Sleep in an endless cycle ...) I Solved BTL communication in .net Xamarin, but the principle should be the same.
Reading from btlInputStream must be quick and can not use sleep. You use an endless cycle, reading in buffer (OK). Immediately a dune bytes to an auxiliary large buffer (use read / write cursor) and then, for example, in timer treat the data (I suppose you are using some packet protocol)
while (ContinueCycle)
{
int rxlen;
lock (InternalBufferReadLock)
{//Pouze rychle prectu a schovam si do pole
rxlen = USBConnection.BulkTransfer(USBEndPointRead, InternalBufferRead, InternalBufferRead.Length, 0);
Array.Copy(InternalBufferRead, TempBufferRead, rxlen);
}
lock (BufferReadLock)
{
for (int i = 2; i < rxlen; i++)
{
BufferRead[BufferReadWriteCursor] = TempBufferRead[i];
BufferReadWriteCursor++;
}
}
}
and in timer save it to MainBuffer from which the data is processing
if (tmpWriteCursor > tmpReadCursor)
{
lock (BufferReadLock)
{
int newBytes = tmpWriteCursor - tmpReadCursor;
for (int i = 0; i < newBytes; i++)
{
BufferReadMain[BufferReadReadCursor] = BufferRead[BufferReadReadCursor++];
}
}
}
...
bool newline = false;
string tmpRadek = "";
int lastLineIndex = 0;
List<string> list = new List<string>();
for (int i = LastWriteLineIndex; i < tmpWriteCursor; i++)
{
if (BufferReadMain[i] >= 32 && BufferReadMain[i] <= 255)
{
tmpRadek += (char)BufferReadMain[i];
}
else if (BufferReadMain[i] == 13) newline = true;
else if (BufferReadMain[i] == 10)
{
if (newline)
{
newline = false;
list.Add(Utils.GetFormatedDateTime(DateTime.Now) + " " + tmpRadek);
tmpRadek = "";
lastLineIndex = i + 1;
}
}
else
{
tmpRadek += "?" + BufferReadMain[i].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.