You can see what i am talking about in this picture
I have an array called "statusLikers" under a class called "Status". I am trying to create a facebook/instagram like/unlike functionality on button click.
Now, before i move on from where i am, i am trying to figure out how to remove users from the array.
I know how to add to th array but i dont know how to delete from it.
The way i am going about it is like this
List<Object> likesPpl = status.getList("statusLikers");
JSONObject myObject = new JSONObject();
try {
myObject.put("statusLikers", currUser.getUsername());
} catch (JSONException e1) {
e1.printStackTrace();
}
likesPpl.removeAll(Arrays.asList(myObject));
but it does not seem to work, first i want to learn to remove items from the array before i create the if statements.
to remove data from an array of a Parse Tab
List<String> ary_users = new ArrayList<String>();
ParseQuery<ParseObject> queryPart1 = ParseQuery.getQuery("Channel");
queryPart1.whereEqualTo("objectId",channel_id);
queryPart1.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e==null) {
if (list.size()>0) {
ParseObject p = list.get(0);
if (p.getList("usersArray")!=null) {
ary_users = p.getList("usersArray");
}
else
{
ary_users = null;
}
if (ary_users!=null) {
if (ary_users.contains(frnd_objid)) {
ary_users.remove(frnd_objid);
p.put("usersArray",ary_users);
p.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException arg0) {
Toast.makeText(activity,frnd_name+ "is successfully removed in the channel"+channel_name,Toast.LENGTH_LONG).show();
}
});
}
}
}
}
}
});
}
Here "usersArray" is an Array of table "Channel" .And I am removing "frnd_objid" from the "usersArray"
Related
The answer to the following described issue may be as simple as that I am not using SortedSet correctly, but I wouldn't know if that is the case.
void SQLRankGuildsByPoints(final CallbackReturnIntegerStringSortedSet callback)
{
java.sql.Connection cn = null;
try {
cn = DataSource.getConnection();
if(cn != null)
{
PreparedStatement query = cn.prepareStatement("SELECT GuildName, TotalActivityPoints FROM Guilds");
ResultSet result = query.executeQuery();
SortedSet<Pair_IntString> GuildsRanking = new TreeSet(new ComparatorGuildsRanking());
while(result.next())
{
int resultInt = result.getInt("TotalActivityPoints");
String resultString = result.getString("GuildName");
GuildsRanking.add(new Pair_IntString(resultInt, resultString));
}
Bukkit.getScheduler().runTask(MainClassAccess, new Runnable() { //Callback to main thread
#Override
public void run() {
callback.onDone(GuildsRanking);
}
});
}
} catch (SQLException e) {
System.err.print(e);
} finally {
try {
cn.close();
} catch (SQLException e) {
System.err.print(e);
}
}
}
All 8 results from the Guilds table are present in "result" ResultSet.
GuildsRanking.add() isn't adding the new custom Pair_IntString object constructed with the query results, specifically for guilds "test" and "lilo" in Guilds table.
SQLRankGuildsByPoints method finishes it's execution, calling back the GuildsRanking SortedSet without 2 of the iterated results.
This behaviour is unintended and I can't find an explanation for it.
The comparator used for TreeSet:
public class ComparatorGuildsRanking implements Comparator<Pair_IntString> {
#Override
public int compare(Pair_IntString intStr1, Pair_IntString intStr2) {
return intStr2.integer.compareTo(intStr1.integer);
}
}
Custom Pair_IntString class:
public class Pair_IntString {
public Integer integer;
public String string;
Pair_IntString(Integer i, String s)
{
integer = i;
string = s;
}
}
No error messages with the skipped add iterations.
This is a reoccurring issues that I keep getting in Android Studio. I will go to use the JSONArray class, and it will tell me that "Call Requires API Level 19(current min is 15)". The weird thing is that I am able to use JSONArray in other spots in the same class.
Some things that I've tried are cleaning and building the project (does nothing), restarting Android Studio (also does nothing for the issue), and rewriting the method that uses JSONArray, or move it (This will sometimes work)
Here is an example where I don't get the issue
private void makeApiCall(String text) {
APICall.make(context, text, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
List<Employee> employees = new ArrayList<>();
try {
JSONArray array = new JSONArray(response);
employees = new APIHelper().populateEmployeetList(array);
} catch (Exception e) {
e.printStackTrace();
}
autoAdapter.setData(employees);
autoAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
And here is an example where I get the Error
private void getJobs(String text){
APICall.getJobsByPartial(context, text, new Response.Listener() {
#Override
public void onResponse(Object response) {
try{
List<Function> functions = new ArrayList<>();
JSONArray jobs = new JSONArray(response);
functions = new APIHelper().populateFunctionList(jobs);
jobAdapter.setData(functions);
jobAdapter.notifyDataSetChanged();
}
catch (JSONException ex){
ex.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
In your first code snippet, response is a String. The JSONArray constructor that takes a String has been around since API Level 1.
In your second code snippet, response is an Object. The JSONArray constructor that takes an Object has only been around since API Level 19.
In your second code snippet, APICall.getJobsByPartial() should be giving your callback something more specific than an Object.
I'm new on Android development and I'm learning how to use MVP pattern correctly in recently.
Now I'm facing a tricky problem, hope can get some helpful suggestion or solution from here.
First, here is my presenter
public class MVPPresenter {
private MVPView mvpView;
public MVPPresenter(MVPView mvpView) {
this.mvpView = mvpView;
}
public void loadData() {
mvpView.startLoading();
final List<MVPModel> list = new ArrayList<>();
//the part that I trying to extract starts here.
Call call = DataRetriever.getDataByGet(URLCombiner.GET_FRONT_PAGE_ITEMS);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
mvpView.errorLoading();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
try {
JSONObject result = new JSONObject(response.body().string());
int errorCode = result.getInt("ErrorCode");
if (errorCode == 0) {
JSONArray value = result.getJSONObject("Value").getJSONArray("hot");
for (int i = 0; i < value.length(); i++) {
MVPModel mvpModel = new MVPModel();
String name = null;
String image = null;
try {
name = value.getJSONObject(i).getString("title");
image = URLCombiner.IP + value.getJSONObject(i).getString("pic");
} catch (JSONException e) {
e.printStackTrace();
}
mvpModel.setName(name);
mvpModel.setImage(image);
list.add(mvpModel);
}
if (list.size() > 0) {
mvpView.successLoading(list);
mvpView.finishLoading();
} else {
mvpView.errorLoading();
}
} else {
mvpView.errorLoading();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
mvpView.errorLoading();
}
}
});
//the part that I trying to extract ends here.
}
}
As you can see, I'm trying to extract the part which is using OKHttp libs into a class (I call it data manager) which I hope it can handle every task between server and client. But here's the thing, when I trying to pass the result from the data manager to presenter, I got NullPointException because of the async mechanism.
I would like to know how to passing the data, which is come from server in async, to the presenter when the data has finish downloading.
And here's my ideal data manager, I know this might looks stupid but I think this can make my problem more clearly.
public class LoadServerData {
private static JSONArray arrayData = new JSONArray();
public static JSONArray getServerData() {
Call call = DataRetriever.getDataByGet(URLCombiner.GET_FRONT_PAGE_ITEMS);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
try {
JSONObject result = new JSONObject(response.body().string());
int errorCode = result.getInt("ErrorCode");
if (errorCode == 0) {
arrayData = result.getJSONObject("Value").getJSONArray("hot"); //the data I would like to return.
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
return arrayData; //this is gonna be an empty data.
}
}
I've reading some article that might can solve my problem, but still not getting any fine answer. Perhaps I've using wrong keyword I think. Hopes you guys can give me some ideas or solutions to help me or inspire me.
P.S. version of OKhttp libs is 3.7.0
Create a simple Listener so it can be called whenever the server call finishes:
public class LoadServerData {
public static interface Listener {
public void onSuccess(JSONArray data);
public void onError(Exception error);
}
public static void getServerData(Listener listener) {
Call call = DataRetriever.getDataByGet(URLCombiner.GET_FRONT_PAGE_ITEMS);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
listener.onError(e);
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
try {
JSONObject result = new JSONObject(response.body().string());
int errorCode = result.getInt("ErrorCode");
if (errorCode == 0) {
JSONArray arrayData = result.getJSONObject("Value").getJSONArray("hot"); //the data I would like to return.
listener.onSuccess(arrayData);
} else {
listener.onError(...);
}
} catch (JSONException e) {
e.printStackTrace();
listener.onError(e);
}
} else {
listener.onError(...);
}
}
});
}
}
I really hate to do this, but I have two questions: can Jackson 2.7.3 parse the following url and can do I have to parse every part of the JSON?
Here is the code I am working with so far:
public class Song {
private String tracks;
private String album;
private String images;
public void setTracks(String tracks){
this.tracks=tracks;
}
public void setAlbum(String album){
this.album= album;
}
public void setImages (String images){
this.images= images;
}
}
And
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
ObjectMapper mapper = new ObjectMapper();
Document doc = Jsoup.connect("http://api.spotify.com/v1/search?q=track:" + finalSong + "%20artist:" + finalArtist+"%20" + "&type=track").ignoreContentType(true).get();
String title = String.valueOf(doc.body().text());
Song obj = mapper.readValue(String.valueOf(title), Song.class);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
return null;
}
All I need is the "preview_url" and one of the "images" url towards the top
the JSON is located at https://api.spotify.com/v1/search?q=track:Ready%20To%20Fall%20artist:rise%20against%20&type=track.
Do you necessary need to map your Json response into a class?
If not you can get your desired values as following e.g. for preview_url
You can use readTree to map the json result into a tree of nodes.
There after you can use findPath to search for the property you looking for.
In the case of image it contains an array. Thus if you want to select a specific item from that list you get use get to select the specific item you want.
example
JsonNode readTree = mapper.readTree(body);
for (JsonNode node : readTree.findPath("items")) {
System.out.println(node.findPath("images").get(2));
System.out.println(node.findPath("preview_url"));
}
I have logs in the form of string. I want to send these logs form my application to influx Database. So, i have written these functions.
private String formatAsJsonArrayString(List<String> logs) {
Gson gson = new Gson();
return gson.toJson(logs);
}
public void startFlushToInfluxDbThread() {
Thread flushToInfluxDbThread = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
Thread.sleep(influxPostWaitTime);
List<String> logs = extractNEntries(queue, 1000);
String dataToPost = formatAsJsonArrayString(logs);
postToInfluxDB(dataToPost);
} catch (Exception e) {
e.printStackTrace();
}
}
}
but now i am unable to think how to write postToInfluxDB() function. Can somebody guide me to do this? I mean to say, how connection will be made and all that related stuff.