I have a ListView in Android that contains Orders. When you click on a specific order you can choose whether to remove it or not. When the list contains >1 items, the removed item does not appear on the ListView anymore. However, when the list size is 1 and you remove the only order left, the order does get removed from the list but not from the ListView. So you can still see it on the screen, but if you try to open it an error message is shown "Can't open this order.".
When you return to the Home screen and reopen the ListView, the order is properly removed, and an empty list is shown. However, I'm not sure why this is happening. Here is some sample code:
method {
VerkoopOrder orderToBeSaved = CurrentOrder;
UUID CurrentID = CurrentOrder.getId();
orderToBeSaved.setId(null);
String Result = OrderHelper.SaveOrder(orderToBeSaved, APIKey);
JSONObject json = new JSONObject(Result);
String res = json.getString("nummer");
if (Result != null) {
Messager.showMessage(getString(R.string.Saved), getString(R.string.OrderSavedAs) + " " + res, true, this);
DeleteCurrentOrder(APIKey, CurrentID);
UnsavedOrdersActivity.UnsavedOrderAdapter.notifyDataSetChanged();
}
}
public void DeleteCurrentOrder(String APIKey, UUID OrderId) {
try {
OrderScanPreference orderScanPreference = OrderScanPreference.GetCurrentSavedPreference(this, getString(R.string.OrderScanUserPreference));
String finalAPIKey = APIKey;
try {
for (UnsavedOrderPreference unsavedOrderPreference : orderScanPreference.unsavedOrderPreferences) {
if (unsavedOrderPreference.APIAdministrationToken.equals(finalAPIKey)) {
unsavedOrderPreference.UnsavedOrders.removeIf(r -> r.getId().equals(OrderId)); //Order gets removed from the list!
}
}
orderScanPreference.Save(this, getString(R.string.OrderScanUserPreference));
} catch (Throwable throwable) {
//TODO
}
} catch (Exception ex) {
Log.d("Exception: ", ex.toString());
//TODO
}
}
This code was written by a colleague but he left the company a few weeks ago, so I have to finish his project. Let me know if you require more information.
I placed a check to see if the list is empty or not. If it is, it reassigns the Adapter to the ListView so the list gets cleared completely.
Not a great fix, so I won't accept this as the answer yet. Only if there are no better answers soon I'll accept this.
Related
I'm creating an API that return Vaccination Info of people. The code below is that I'm getting list of vaccination IDs. If people injected 1 or more, the API working fine, I get a list as expected. Vice versa, if they haven't injected, the data on server is null. In that case, when I make an API call I will get the error that vaccinationInfoList is null, but it's still have the size 1. I tried as below to locate the error but it's cannot catch any exception.
try {
Response<List<Vaccination_info>> res = call.execute();
Log.v("RES" , String.valueOf(res));
if (res.body() != null){
try {
vaccinationInfoList = res.body();
}
catch (Exception n){
Log.v("ExceptionN" , String.valueOf(n));
}
} else {
Log.v("NULL" , "NULL");
}
} catch (IOException e) {
e.printStackTrace();
}
Log.v("VACC", String.valueOf(vaccinationInfoList.size()));
Can someone recommend me a solution or a different aproach? Thanks so much
If you have access and can change api response so change response from null to empty array list []
If not You can use com.google.gson.JsonElement
I'm continuing a project that has been coming for a few years at my university. One of the activities this project does is to collect some web pages using the google bot.
Due to a problem that I cannot understand, the project is not getting through this part. Already research a lot about what may be happening, if it is some part of the code that is outdated.
The code is in Java and uses Maven for project management.
I've tried to update some information from maven's "pom".
I already tried to change the part of the code that uses the bot, but nothing works.
I'm posting the part of code that isn't working as it should:
private List<JSONObject> querySearch(int numSeeds, String query) {
List<JSONObject> result = new ArrayList<>();
start=0;
do {
String url = SEARCH_URL + query.replaceAll(" ", "+") + FILE_TYPE + "html" + START + start;);
Connection conn = Jsoup.connect(url).userAgent("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)").timeout(5000);
try {
Document doc = conn.get();
result.addAll(formatter(doc);
} catch (IOException e) {
System.err.println("Could not search for seed pages in IO.");
System.err.println(e);
} catch (ParseException e) {
System.err.println("Could not search for seed pages in Parse.");
System.err.println(e);
}
start += 10;
} while (result.size() < numSeeds);
return result;
}
what some variables do:
private static final String SEARCH_URL = "https://www.google.com/search?q=";
private static final String FILE_TYPE = "&fileType=";
private static final String START = "&start=";
private QueryBuilder queryBuilder;
public GoogleAjaxSearch() {
this.queryBuilder = new QueryBuilder();
}
Until this part is ok, it connect with the bot and can get a html from google. The problem is to separate what found and take only the link, that should be between ("h3.r> a").
That it does in this part with the result.addAll(formatter(doc)
public List<JSONObject> formatter(Document doc) throws ParseException {
List<JSONObject> entries = new ArrayList<>();
Elements results = doc.select("h3.r > a");
for (Element result : results) {
//System.out.println(result.toString());
JSONObject entry = new JSONObject();
entry.put("url", (result.attr("href").substring(6, result.attr("href").indexOf("&")).substring(1)));
entry.put("anchor", result.text());
So when it gets to this part: Elements results = doc.select ("h3.r> a"), find, probably, no h3 and can't increment the "results" list by not entering the for loop. Then goes back to the querysearch function and try again, without increment the results list. And with that, entering in a infinite loop trying to get the requested data and never finding.
If anyone here can help me, I've been trying for a while and I don't know what else to do. Thanks in advance.
I have two methods. The first retrieves a list of results from a search method in another class.
/* 2 - Retrieve list of results */
qmitResultsList = QMITSearchUtil.execute(URL, keyword);
/* 3 - Show results */
populateTable(qmitResultsList, tableView)
The second, populateTable() adds all the items to the table at once by calling:
ObservableList<QMITResult> dataPriority = FXCollections.observableArrayList(
qmitResultsList
);
tableView.setItems(dataPriority);
My goal is to add each new element to the TableView as it is being processed in real-time. For example, instead of processing and returning the entire list in the first method, QMITSearchUtil.execute(), I would like to update the UI with each result that is returned, one at a time. How can this be accomplished? I've tried a few ways, using a Platform.runLater() hack for example, with no success...
I discovered the answer to my question. I first define the ObservableList for my TableView:
ObservableList<QMITResult> dataPriority = FXCollections.observableArrayList();
Then I pass that into the execute() method that runs the background thread:
private void execute(String URL, String keyword, ObservableList<QMITResult> dataPriority) throws Exception {
/* Download HTML page and create list of URLs from relevant links */
Elements links = getLinkList(URL);
List<QMITResult> qmitResults = new ArrayList<>();
new Thread(() -> {
for (Element link : links) {
try {
/* Create a list of formatted URLs to loop through */
String linkText = link.toString();
String titleText = link.text();
String formattedLink = StringUtils.substringBetween(linkText, "<a href=\"", "\"").replace("\\", "/");
System.out.println(titleText);
System.out.println(formattedLink);
/* Create Word Document for each link and parse for keyword */
QMITResult qmitResultNode = null;
try {
qmitResultNode = parseDocument(keyword, formattedLink, titleText);
} catch (Exception e) {
e.printStackTrace();
}
qmitResults.add(qmitResultNode);
dataPriority.add(qmitResultNode);
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
tableView.setItems(dataPriority);
}
The result is that while the list is being formed each TableView item is being individually published without blocking the main UI thread. They come one at a time.
I'm creating an app where I get a youtube search. It is currently working ok, I just want to show better results, by sorting them by title name.
I got a VideoListResponse with 50 items
VideoListResponse videoListResponse = null;
try {
videoListResponse = mYouTubeDataApi.videos()
.list(YOUTUBE_VIDEOS_PART)
.setFields(YOUTUBE_VIDEOS_FIELDS)
.setKey(ApiKey.YOUTUBE_API_KEY)
.setId(TextUtils.join(",", videoIds)).execute();
} catch (IOException e) {
e.printStackTrace();
}
and I want to sort them by title. Let me show an image of the item list:
Well, the YouTube API already supports ordering the results by title. You won't have to do anything on your end....
https://developers.google.com/youtube/v3/docs/search/list#parameters
You could retrieve the List within and sort that:
List<Video> items = videoListResponse.getItems();
items.sort(Comparator.comparing(e -> e.getSnippet().getTitle()));
In my endWorkout.java file, I am saving data into my Parse database using the following logic:
// Parse Storage
ParseObject testObject = new ParseObject("TestOne");
testObject.put("Device", ParseInstallation.getCurrentInstallation());
testObject.put("Reps", inputList);
testObject.saveInBackground();
Where I am first storing my Device ID for authentication purposes, and then storing inputList which is an ArrayList of integers.
In my Parse database, the data is properly saved, as shown below:
Now in my MainActivity.java, I would like to retrieve all the data in the Reps field of the Parse database for a single device. For example, the device yhmrKgokfS has 6 Arrays in the Parse database, I would like to sequentially retrieve each of them to display in a ListView on the screen.
Here is the logic I am trying to use:
List<ParseObject> importList = new ArrayList<ParseObject>();
//parse import list
ParseQuery<ParseObject> query = ParseQuery.getQuery("TestOne");
query.whereEqualTo("Device", ParseInstallation.getCurrentInstallation());
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> repList, ParseException e) {
if (e == null) {
Log.d("Reps", "Retrieved " + repList.size() + " reps");
} else {
Log.d("Reps", "Error: " + e.getMessage());
}
}
});
importList = repList;
I first want to make sure I'm importing from the current device, so I need to check if the Device field matches ParseInstallation.getCurrentInstallation(). Then I want to go ahead and get the first Reps array. However the last line importList = repList; does not work.
How can I go about achieving what I'm trying to do?
query.findInBackground works in asynchronous way. In other words, the line that you set the importList is executed after the line query.findInBackground. However, the query.findInBackground will make a network call that takes time. So if you want to use the repList when it is ready, you have to use it in done method where you are use the network call is done. Hope this helps.
Regards.
As #kinkspeech mentioned you need to move your line importList = repList; to your callback. And I suggest that you change it as follows:
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> repList, ParseException e) {
if (e == null) {
Log.d("Reps", "Retrieved " + repList.size() + " reps");
importList.addAll(replist);
} else {
Log.d("Reps", "Error: " + e.getMessage());
}
}
});