So I'm starting with android studio, following tutorials and all.
I'm interested in making a request to a local server, so I google up and see this.
https://developer.android.com/training/volley/simple
I follow the instructions, get stuck in a couple of places being a very new user to java and android studio, but everything works in the end.
Then, knowing the app will work, just change the "http://www.google.com" string in the example with the ip of the server. And nothing happens.
It doesn't retrieve the index page.
I try with a php script. Nothing.
Phone and server are in the same LAN.
I have tried adding "http://" to the ip, nothing.
Server just work fine in any browser, pc and phone.
I am missing something?
If the code is needed I upload it, but it's exactly the same in the example.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendRequest(){
final TextView textView = (TextView) findViewById(R.id.stringRequest);
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://192.168.1.36";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
textView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
public void onClick(View view){
sendRequest();
}
}
Logcat throws this error:
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
Also, I tried to run it on a emulator and the result is the same.
I added every network related permission, too.
If the only thing you changed is https://www.google.com to http://1.2.3.4 (note switching https to http, and leaving the protocol in the string URL), and it works fine with google there but not with your IP, then it means where-ever you're running this code (on your phone directly, or on the emulator in your dev environment) cannot reach that IP. Note that if you wait a while, the code will error out with for example a Destination Unreachable error or something else enlightening.
Related
I am trying to post an image to a server with Fast Android Networking and I can't figure out how.
The image gets uploaded from an emulator in Android Studio and put in an ImageView, how can I send that image to the server with a POST request?
The code under my starting point and is mostly from https://amitshekhar.me/Fast-Android-Networking/post_request.html if that helps.
AndroidNetworking.post("https://fierce-cove-29863.herokuapp.com/postFile")
.setContentType(file) // posting any type of file
.setTag("test")
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
// do anything with response
}
#Override
public void onError(ANError error) {
// handle error
}
});
Facebook sdk can only login either with read permission or publish permission, but what if I want both? I only need read permission when logging in to register a user or to authenticate it.
So I thought the right way was to first signIn with SignInMode.READ and then signIn again but now with SignInMode.PUBLISH
The problem is when I try to sign in the second time, it just load the accessToken, I tried to put facebook.signOut() in between but nothing...
facebook.signIn(SignInMode.READ, readPermissions, new GDXFacebookCallback<SignInResult>() {
#Override
public void onSuccess(SignInResult result) {
// Login successful
clientManager.login(result.getAccessToken().getToken());
}
#Override
public void onError(GDXFacebookError error) {
// Error handling
}
#Override
public void onCancel() {
}
#Override
public void onFail(Throwable t) {
}
});
//after the user log ins, the app ask for publish permissions, and I
// try to get it by logging in again but now wit `SignInMode.PUBLISH` like so....
facebook.signIn(SignInMode.PUBLISH, publishPermissions, new GDXFacebookCallback<SignInResult>() {
#Override
public void onSuccess(SignInResult result) {
// Login successful
clientManager.login(result.getAccessToken().getToken());
}
#Override
public void onError(GDXFacebookError error) {
// Error handling
}
#Override
public void onCancel() {
}
#Override
public void onFail(Throwable t) {
}
});
What im trying to ask here is how I get an accessToken capable of publishing after I singin with SignInMode.READ?
I am the developer of gdx-facebook extension.
You are doing it correctly, sign in with read permissions first and then follow with publish permission.
There are 2 cases:
You did not authorize the app yet or did authorize the app with less permissions than the ones you request.
-> you get a new token, which contains all existing and newly requested permissions. All existing tokens become invalid.
You already have granted all the requested permissions.
-> you get the latest token.
What im trying to ask here is how I get an accessToken capable of
publishing after I singin with SignInMode.READ?
Just request the permission you need, you get either a new upgraded token which contains old and new permissions or an old one which already contains the permissions.
It is likely that you already granted the permissions and thats why the token does not change. Look in your FB settings -> apps to see which permissions you granted.
Tokens often look similar the first 10-20 characters. Don't get confused by that.
My app crashes because the images ArrayList is empty when I set the adapter, I figured that out by putting a toast message right after I parse my JSON request, and a Toast message after I initialize my adapter, "second" gets printed first on screen and the app crashes right after, does it have to do with my internet? Or am I missing something, here's my code, thanks!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
//First Toast message inside this method
sendAPIRequest();
//after you get the images
mCustomSwipeAdapter = new CustomSwipeAdapter(this, images);
//SECOND TOAST
Toast.makeText(getApplicationContext(), "Second", Toast.LENGTH_LONG).show();
mViewPager.setAdapter(mCustomSwipeAdapter);
mCustomSwipeAdapter.notifyDataSetChanged();
}
public void sendAPIRequest(){
String requestURL = "";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, requestURL, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
parseJSONResponse(response);
//FIRST TOAST : SHOULD BE CALLED FIRST
Toast.makeText(getApplicationContext(), "First", Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(jsonObjectRequest);
}
public void parseJSONResponse(JSONObject response) {
if (response != null || response.length() != 0) {
try {
JSONObject GObject = response.getJSONObject("game");
String name = "N/A";
if (GObject.has("name") && !GObject.isNull("name")) { name = GObject.getString("name"); }
if (GObject.has("screenshots") && !GObject.isNull("screenshots")) {
JSONArray screenShotsArray = GObject.getJSONArray("screenshots");
for (int i = 0; i < screenShotsArray.length(); i++){
JSONObject screenshot = screenShotsArray.getJSONObject(i);
String screenshotURL = screenshot.getString("url");
images.add(screenshotURL);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Does it have to do with my internet? Or am I missing something ...
Both. It happens because you have a race condition.
From what I can make out, your images list is being populated asynchronously by the onResponse callback. Basically, that happens when your app gets the responses to the API requests that it is making. That is going to take at least milliseconds, and possibly seconds (or longer).
But your app is (so you say) crashing soon after the swipe adapter is registered, and the evidence is that the images list has not been populated.
There are three possibilities:
There is something wrong with the requests you are sending which is causing the API requests to not give you any response. (Hypothetically, you could have authentication wrong or something.)
The API requests are taking a long time because of internet connection speed, congestion, or the remote server being slow.
The API requests are taking a short time ... but the adapter registration is even quicker.
If (hypothetically) there is a problem with your requests you will need to fix that. But both of the other scenarios have to be fixed by:
modifying the code that uses the images to work properly if there are no images (yet), or
modifying the code to wait until the image loading has completed before registering the adapter.
Please use this code in your onResponse callback :
//after you get the images
mCustomSwipeAdapter = new CustomSwipeAdapter(this, images);
//SECOND TOAST
Toast.makeText(getApplicationContext(), "Second", Toast.LENGTH_LONG).show();
mViewPager.setAdapter(mCustomSwipeAdapter);
mCustomSwipeAdapter.notifyDataSetChanged();
Volley adds your requests in queue , so better do all the dependent tasks in Response or Error callback only.
I'm following this tutorial to try to make an andorid app with a backend on google app-engine.
I'm at the point where I want to test the connection between my app and GAE Api locally so I try to execute the following code on my Nexus 5 phone (not emulated).
MainActivity.java
public class MainActivity extends FragmentActivity {
private final String DEBUG_TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* AsyncTask for calling Mobile Assistant API for checking into a place (e.g., a store)
*/
private class CheckInTask extends AsyncTask<Void, Void, Void> {
/**
* Calls appropriate CloudEndpoint to indicate that user checked into a place.
*
* #param params the place where the user is checking in.
*/
#Override
protected Void doInBackground(Void... params) {
CheckIn checkin = new CheckIn();
// Set the ID of the store where the user is.
// This would be replaced by the actual ID in the final version of the code.
checkin.setPlaceId("StoreNo123");
Checkinendpoint.Builder builder = new Checkinendpoint.Builder(
AndroidHttp.newCompatibleTransport(), new JacksonFactory(),
null);
builder = CloudEndpointUtils.updateBuilder(builder);
Checkinendpoint endpoint = builder.build();
try {
endpoint.insertCheckIn(checkin).execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}
And I get this
Where I shouldget this
(source: google.com)
And the log shows :
java.net.SocketTimeoutException: failed to connect to /10.0.2.2 (port 8888) after 20000ms
No CheckIn is available on the "entity kind" list
I've lauched the appengine locally i get : INFOS: Dev App Server is now running
I've CloudEndPointUtils.java setting to : LOCAL_ANDROID_RUN = true; LOCAL_APP_ENGINE_SERVER_URL = "http://localhost:8888/"; and LOCAL_APP_ENGINE_SERVER_URL_FOR_ANDROID = "http://10.0.2.2:8888";
I feel like it's because I'm using a physical device for debugging...
What do you think and how to make it work ?
(I can't figure out how run an emulator of android on my computer so if there is another solution that would be great)
Edit: I've tried to deploy the app but I'm having the same issue with the same log error.
This is beacause 10.0.2.2 is the address of localhost when using the emulator. If you want to try it on your device and all your computer and device are connected to the local network, try changing the server address to http://local-network-ip:port/_ah/api. When launching the appengine application set the host address to 0.0.0.0 to make it accessible to other machines on the network.
I'm trying very simply to test the 3.0 Facebook get started guide. https://developers.facebook.com/docs/getting-started/facebook-sdk-for-android/3.0/
I have had some problems with imports and references but I don't know it that's relevant. The issue I'm having is when I try to run the test Activity ant get this error:
Could not find class 'com.test1.test2.FacebookLogin$1', referenced from method com.test1.test2.FacebookLogin.onCreate
Code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_facebook_login);
//Error occurs here when I use 'this'
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
TextView welcome = (TextView) findViewById(R.id.welcome);
welcome.setText("Hello " + user.getName() + "!");
}
}
});
}
}
});
}
How can I get a NoClassDefFoundError when I use this?
UPDATE:
After testing with the Scrumtious tutorial https://developers.facebook.com/docs/tutorials/androidsdk/3.0/scrumptious/authenticate/ as well I'm getting the same error when I call the Session.StatusCallback() method. I still don't know what my problem is though.
Thanks for the help
Maybe you updated to Android sdk tools revision 22. There is an issue there. You have to add the libraries you use in the export path. Check:
Android Sdk tools Revision 22 issue?