Communicating using socketio in Android - socket.emit error - java

I'm trying to communicate to my nodejs application using android as client. Currently I'm using https://github.com/Gottox/socket.io-java-client repository as reference. Tried the examples of repo but no help.
NodeJS-SocketIO Code:
socket.on('new user',function(data, callback){
if (nicknames.indexOf(data)!=-1){
callback(false);
} else{
callback(true);
socket.nickname = data;
nicknames.push(socket.nickname);
updateNicknames();
}
});
Android-Java Code:
try {
JSONObject json = new JSONObject();
json.putOpt("data", "user1");
socket.emit("new user", json);
} catch (JSONException ex) {
ex.printStackTrace();
}
However, the above code results in TypeError: undefined. Please help. Thanks in advance!

You can do away with the JSON object. You could just do:
socket.emit("new user", "user1");
Not so sure about sending a JSON over, but if you wanted to, did you try:
JSONArray array = new JSONArray();
array.put("data", "user1");
socket.emit("new user", array);
Pretty sure JSONs need to have the enclosing brackets.

Related

How to add jsonObject to an existing JSON file in the "raw" folder Android Studio? (Java)

Im trying to add jsonObject to an existing JSON file in "raw" folder.
Every time the button pressed it should add to the JSON file two new variables from the plainText input. I cant figure out how to do that because I cant properly get the path of the "raw" folder.
the code that I wrote without the "adding to JSON" part
public void submit(View view) {
EditText editAmount;
EditText editReason;
Log.d("Smth", "Submit!");
editAmount = (EditText)findViewById(R.id.editAmount);
editReason = (EditText)findViewById(R.id.editReason);
String amount = editAmount.getText().toString();
String date = "18.02.2023";
String reason = editReason.getText().toString();
Log.d("Smth", amount);
Log.d("Smth", reason);
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("amount", amount);
jsonObject.put("reason", reason);
jsonObject.put("date", "18.02.2023");
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
I have tried a lot of other solutions on StackOverFlow, but all of them give me errors.
I hope you will help me with this problem of editing JSON file) Thank you

Do different Web Hosts give different responses under same conditions?

I am working on an Android app. Therefore I'm creating a Login/Register Aktivity.I'm using JsonRequest (Volley) to get the Information stored in an SQL Data-base.Furthermore I wrote some PHP files (for Testing Purpose) to create a JSONObject as the Server Response.
Everything seems to work but only for some webhosts. What I mean by that is that the same Android Code and the same PHP Code once work fine and in the other case Output Errors.
My Test PHP Code uploaded via FileManagers
<?php
$myObj=new stdClass();
$myObj->name = "Test";
$myJSON = json_encode($myObj);
echo $myJSON;
?>
My Java Code
RequestQueue requestQueue= Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET,url,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String success=response.getString("name");
Toast.makeText(getApplicationContext(),success, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "ErrorCatch"+e.toString(), Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "ErrorResponse"+error.toString(), Toast.LENGTH_LONG).show();
}
});
requestQueue.add(jsonObjectRequest);
Using one Webhost I get the Correct Toast including the stored Information from the Server. Using another Webhost I get an Error:"Java.lang.String cannot be converted to JSONObject" which I find Odd since I'm doing the same Stuff.

Pagination example for spotify api java [spotify-web-api-java]

I'm trying to create a playlist viewer and I got stuck on paging.
I want to get all the names of current users playlists.
Any help would be appreciated.
public void getPlaylists() {
try {
SpotifyApi spotifyApi = new SpotifyApi.Builder().setAccessToken(auth.getToken()).build();
GetListOfCurrentUsersPlaylistsRequest getListOfCurrentUsersPlaylistsRequest = spotifyApi.getListOfCurrentUsersPlaylists().limit(5).offset(0).build();
Paging<PlaylistSimplified> playlistSimplifiedPaging = getListOfCurrentUsersPlaylistsRequest.execute();
} catch (IOException | SpotifyWebApiException e) {
System.out.println("Erroras: " + e.getMessage());
}
}
Okey so found out the answer myself don't know if its the correct way but it will work.
You can convert the paging object to a list :
List<PlaylistSimplified> playlists = Arrays.asList(playlistSimplifiedPaging.getItems());
And then get the info about your object normally.

How to get object out of inner class

I am trying to make this application in Android, I am getting data from foursquare's API in JSON format and I need to Parse it to present it in another intent.
I am using Android's volley library to get the JSON but the problem is the onResponse() function of JsonObjectRequest has no return parameter.so I cannot get the JSON object gotten from url outside of the the onResponse.
I haven't worked with volley before and hence don't know much about it, any help is appreciated. Here is the code that I am trying to make it work.
Edit: The main problem I'm facing is that I cannot assign a value to global variable in this case myPlaces inside the JsonObjectRequest's onResponse method. Or to be exact, the variable assigned inside means nothing outside, thus in the last line
Toast.makeText(MainActivity.this, myPlaces[2].getName(), Toast.LENGTH_LONG).show();
when I try to access the myPlaces[2] it gives me an null pointer exception.
Thanks.
public void onClick(View v) {
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(urlString, null, new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject meta = response.getJSONObject("meta");
String status = meta.getString("code");
Toast.makeText(MainActivity.this, status, Toast.LENGTH_SHORT).show();
if(status.equals("200"))
{
JSONObject responseJson = response.getJSONObject("response");
JSONArray venues = responseJson.getJSONArray("venues");
Places[] tempPlaces = new Places[venues.length()];
for (int i = 0 ; i < venues.length(); i++)
{
Places place = new Places();
JSONObject venueObject = venues.getJSONObject(i);
place.setName(venueObject.getString("name"));
JSONObject locatVenue = venueObject.getJSONObject("location");
place.setLat(locatVenue.getDouble("lat"));
place.setLon(locatVenue.getDouble("lng"));
tempPlaces[i] = place;
}
Toast.makeText(MainActivity.this, tempPlaces[2].getName(), Toast.LENGTH_LONG).show();
myPlaces = tempPlaces;
}
else
{
Toast.makeText(MainActivity.this, "No response from API", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "There is some error here", Toast.LENGTH_LONG).show();
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "There has been some error", Toast.LENGTH_LONG).show();
}
});
requestQueue.add(jsonObjectRequest);
Toast.makeText(MainActivity.this, myPlaces[2].getName(), Toast.LENGTH_LONG).show();
Volley itself isn't an inner class; the response is an anonymous class.
You don't need a return in Volley, you just use the variables already defined in your class.
I'm assuming myPlaces is a field in your class? Otherwise, I'm not sure where it is declared outside the onClick..
This line assigns myPlaces and looks like it would work fine
myPlaces = tempPlaces;
You could define a method in your class to parse the whole JSONObject instead of needing to return from Volley. This just passes the logic to another method, so you don't need to think about "returning" inside Volley.
public void parseJSON(JsonObject object)
And pass the response from volley into that and do your normal parsing and variable assignment and you can Toast myPlaces inside that method.
Also, note that Volley is asynchronous, meaning you aren't guaranteed an immediate result, so
Toast.makeText(MainActivity.this, myPlaces[2].getName(), Toast.LENGTH_LONG).show();
Would likely have thrown either a NullPointerException or IndexOutOfBoundsException because myPlaces was either undeclared or empty before the Volley request. I say that because it does not appear to be assigned before the Volley request.

Java / Android: Get Facebook User Info From Graph Api, Display in TextView

I'm trying to learn Java right now and I've jumped in the deep end by starting with the Android Faceobok API. Right now, I'm trying to get some information from my graph data (a friend in this case) and display it in a text view. This seems rather trivial but it has been anything but.
JSONObject json_data = null;
try
{
JSONObject response = Util.parseJson(facebook.request("/me/friends", mBundle, "GET")); // Get a friend information from facebook
JSONArray jArray = response.getJSONArray("data");
json_data = jArray.getJSONObject(0);
String name = json_data.getString("name");
mText.setText(name);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (FacebookError e)
{
e.printStackTrace();
}
The TextView doesn't change when I do this and I'm not exactly sure where I've gone wrong.
As an aside, there is a shortage of good Android Facebook API tutorials out there. Most are hundreds of lines of code; I don't have the energy or patience to consume all of that.
I have a feeling your initial request isnt working properly. you should try this line instead:
JSONObject response = Util.parseJson(facebook.request("me/friends"));
Firstly I think in your initial request, it should be "me/friends" rather than "/me/friends". Secondly you dont necessarily need the mBundleor "GET" parameters in what you're trying to achieve. Have you even defined parameters in mBundle? You're also getting information from the request method, so the "GET" parameter isn't necessary.
Try the line i just wrote, as it is simpler and will get your friends information. The rest of your code is fine.
Your assertion about being "trivial" is essentially true, but generally speaking "jumping into the deep end" rarely results in anything other than a drowning.
I'm going to be "that guy" and recommend you actually get to the point of having a general understanding and minimal competency in Java before tackling someone else's API. Once you know how Java works - the "PME" ... properties, methods, and events - learning anyone's API becomes just a question of following the proper steps.
Besides that little bit of PS, answer the following:
1) received data from your source?
2) what thread are you invoking this on?
3) any of the objects null?
4) any exceptions being thrown when you look in the Console or Log (print those out to the Log versus your current implementation)?
And, not for nothing, but if you don't have the time or patience to learn the "how's and why's" of an API or software dev in general then this will be a long exercise for you if the work ever becomes non-trivial.
Just one man's opinion who also has attempted to drink from fire hose before.
Update: Here's all of my code:
public class FriendsActivity extends Activity {
/** Called when the activity is first created. */
Facebook facebook = new Facebook("194653157245506");
TextView mText;
Bundle mBundle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mText = (TextView) this.findViewById(R.id.text);
facebook.authorize(this, new String[] {"offline_access", "user_interests", "friends_interests"},
new DialogListener() {
#Override
public void onComplete(Bundle values) {}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
JSONObject json_data = null;
try
{
JSONObject response = Util.parseJson(facebook.request("/me/friends", mBundle, "GET")); // Get a friend information from facebook
JSONArray jArray = response.getJSONArray("data");
json_data = jArray.getJSONObject(0);
String name = json_data.getString("name");
Log.i("friend is", name);
mText.setText(name);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (FacebookError e)
{
e.printStackTrace();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
}
I may be a little off key. but I have done facebook api development in C#, and i am wondering if you have had the client login.
Facebook works with OAuth to allow you to authorize through them for a client. (Even your own account as the client) therefore you may need to login.
Another thing to look at is, do you have the TextView that is in the Activity that is being displayed..
Try putting in a breakpoint and looking over the code as it is executing, Debug View is great for that.
see if your response is being populated.
make sure you have the Text from the Activity.
mText = (TextView)findViewById(R.id.TextView1); //or whatever you named it.
Also the LogCat should show you the stack trace for any errors that occur, maybe posting some of the output would help

Categories

Resources