Actually i want to post on my page as a page not as a user using facebook sdk in android app but the problem is page "AccessToken" which i retrieve from graph request is in String and now i cannot use it in an other graph request. it says String cannot converted to AccessToken.
Here is my code.
package com.mak.masimmak.pageshare;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import org.json.JSONException;
import org.json.JSONObject;
public class sharePage extends AppCompatActivity {
Button shareButton;
public String PageId;
String PageAccessToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share_page);
shareButton = (Button) findViewById(R.id.shareButton);
shareButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
if(getIntent().getExtras() != null) {
Bundle extras = getIntent().getExtras();
PageId = extras.getString("PageId");
/* make the API call */
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/"+PageId+"?fields=access_token",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
try {
JSONObject data = response.getJSONObject();
PageAccessToken = data.getString("access_token");
PostOnPage();
} catch (JSONException e) {
Toast.makeText(sharePage.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
).executeAsync();
}
}
});
}
public void PostOnPage(){
Bundle params = new Bundle();
params.putString("message", "This is a test message");
/* make the API call */
new GraphRequest(
/* Problem is here the PageAccessToken is in String How to use this string token here? */
(AccessToken) PageAccessToken,
"/"+PageId+"/feed",
params,
HttpMethod.POST,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
}
}
).executeAsync();
}
}
I search the problem in google and i found something..
public AccessToken(String accessToken, String applicationId, String userId, Collection permissions, Collection declinedPermissions, AccessTokenSource accessTokenSource, Date expirationTime, Date lastRefreshTime)
But i don't know how use this or implement this in my code.
I found the solution of my own question.
You can convert AccessToken from String format to Facebook AccessToken format using this line of code.
AccessToken PageAT = new AccessToken(PageAccessToken, AccessToken.getCurrentAccessToken().getApplicationId(), AccessToken.getCurrentAccessToken().getUserId(), AccessToken.getCurrentAccessToken().getPermissions(), null, AccessTokenSource.FACEBOOK_APPLICATION_NATIVE, AccessToken.getCurrentAccessToken().getExpires(), null);
Then this PageAT will work fine in your new Graph Request..
Related
I am new to Android and Java Development and I am trying to figure out a way to retrieve the current users Profile posts and save it in a Text File on my smart phone for further processes.
I am able to retrieve User Name, Email, Gender, Age Range and Birthday. so far everything works fine and the text file is being written when Facebook is connected with my Application.
Below class is how its coded in order to retrieve the mentioned Data, If anyone does know of how to retrieve posts as well via this method, please suggest?
Thanks!
package com.example.daunte_pc.anique;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
public class SocialActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private static final String TAG = "SocialActivity";
LoginButton loginButton;
CallbackManager callbackManager;
ProgressDialog progressDialog;
URL profile_pic;
String id;
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_social);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open,R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
NavigationView navigationView = (NavigationView)findViewById(R.id.navigation);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView.setNavigationItemSelectedListener(this);
FacebookSdk.sdkInitialize(getApplicationContext());
loginButton = (LoginButton)findViewById(R.id.login_button);
callbackManager = CallbackManager.Factory.create();
loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday", "user_status","user_posts"));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
progressDialog = new ProgressDialog(SocialActivity.this);
progressDialog.setMessage("Please Wait! Anique_Profile's being processed!");
progressDialog.show();
String accessToken = loginResult.getAccessToken().getToken();
Log.i("accessToken",accessToken);
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.i("Test",response.toString());
Bundle bFacebookData = getFacebookData(object);
String name = bFacebookData.getString( "name");
String email = bFacebookData.getString( "email");
String gender = bFacebookData.getString( "gender");
String profilepic = bFacebookData.getString( "profile_pic");
String age_range = bFacebookData.getString( "age_range");
String birthday = bFacebookData.getString( "birthday");
String posts = bFacebookData.getString( "posts{message}");
Intent in = new Intent(SocialActivity.this, Facebook_Profile.class);
in.putExtra("name", name);
in.putExtra("email", email);
in.putExtra("gender", gender);
in.putExtra("Image", profilepic);
in.putExtra("posts", posts);
startActivity(in);
try{
File root = new File(Environment.getExternalStorageDirectory(),"Anique Text Files");
if (! root.exists()){
root.mkdir();
}
File filePath = new File(root, "myFile.txt");
FileWriter writer = new FileWriter(filePath);
writer.append("Name : "+ name+"\n");
writer.append("\n");
writer.append("Email : "+ email+"\n");
writer.append("\n");
writer.append("Gender : "+ gender+"\n");
writer.append("\n");
writer.append("Age : "+ age_range+"\n");
writer.append("\n");
writer.append("Birthday : "+ birthday+"\n");
writer.append("\n");
writer.append("Posts : "+ posts+"\n");
writer.append("\n");
writer.flush();
writer.close();
Toast.makeText(SocialActivity.this,"Success!! Logged into Anique_Profile as per given user information. ",Toast.LENGTH_LONG).show();
Toast.makeText(SocialActivity.this, "Data is Written!", Toast.LENGTH_LONG).show();
}catch (Exception ex){
ex.printStackTrace();
}
progressDialog.hide();
finish();
}
});
Bundle params = new Bundle();
params.putString("fields", "id, name, email, gender, age_range, birthday, posts, feed");
request.setParameters(params);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
}
private Bundle getFacebookData(JSONObject object) {
Bundle bundle = new Bundle();
try{
id = object.getString("id");
profile_pic = new URL("https://graph.facebook.com/" + id + "/picture?width=200&height=200");
Log.i("profile_pic", profile_pic +"");
bundle.putString("profile_pic",profile_pic.toString());
}catch (JSONException ex){
ex.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
bundle.putString("idFacebook",id);
if(object.has("name")){
try{
bundle.putString("name", object.getString("name"));
}catch (JSONException ex){
ex.printStackTrace();
}
}
if(object.has("email")){
try{
bundle.putString("email", object.getString("email"));
}catch (JSONException ex){
ex.printStackTrace();
}
}
if(object.has("gender")){
try{
bundle.putString("gender", object.getString("gender"));
}catch (JSONException ex){
ex.printStackTrace();
}
}
if(object.has("age_range")){
try{
bundle.putString("age_range", object.getString("age_range"));
}catch (JSONException ex){
ex.printStackTrace();
}
}
if(object.has("birthday")){
try{
bundle.putString("birthday", object.getString("birthday"));
}catch (JSONException ex){
ex.printStackTrace();
}
}
if(object.has("posts")){
try{
bundle.putString("posts", object.getString("posts"));
}catch (JSONException ex){
ex.printStackTrace();
}
}
return bundle;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
I want to get current users profile statuses for catching particular key words to predict something. There is no objection in showing the posts to user on my App. But that doesn't seem inappropriate since prediction is involved here.
You need to do something with the data that more or less directly benefits the user’s “in-app experience” to begin with ... Facebook will not approve this in review, if the sole purpose is background analysis of the data that has no direct connection to the user experience.
The permission necessary to read a user’s posts would be user_posts, but documentation lists this as one of the non-applicable use cases:
Non-visible use of this data such as sentiment analysis or guarding against spam bots.
https://developers.facebook.com/docs/facebook-login/permissions/v3.0#reference-user_posts
So i´m trying to login on my app and when i click the login button after inserting the username and password this error shows up in the android studio at the run tab on the bottom toolbar in the left corner:
E/Volley: [11996] BasicNetwork.performRequest: Unexpected response code 301 "MYURL"
with my site link and nothing more.
you can learn more about the error HTTP 301 here!
Here is my code:
login.java
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class login extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mView = inflater.inflate(R.layout.login, container, false);
final EditText etUtilizador = mView.findViewById(R.id.etUtilizador);
final EditText etPassword = mView.findViewById(R.id.etPassword);
final Button btLogin = mView.findViewById(R.id.btLogin);
Button btlink = mView.findViewById(R.id.btlink);
btlink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(getActivity(), registar.class);
getActivity().startActivity(registerIntent);
}
});
btLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = etUtilizador.getText().toString();
final String password = etPassword.getText().toString();
Response.Listener<String> responselistener=new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jsonResponse= null;
try {
jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String name = jsonResponse.getString("name");
int age = jsonResponse.getInt("age");
Intent intent;
intent = new Intent(getContext(), utilizador.class);
intent.putExtra("name", name);
intent.putExtra("age", age);
intent.putExtra("username", username);
login.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
loginrequest loginRequest = new loginrequest(username, password, responselistener);
RequestQueue queue = Volley.newRequestQueue(getActivity());
queue.add(loginRequest);
}
});
return mView;
}
}
loginrequest.java
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
public class loginrequest extends StringRequest {
private static final String LOGIN_REQUEST_URL = "http://elabora.pt/login.php";
private Map<String, String> params;
public loginrequest(String username, String password, Response.Listener<String> listener) {
super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("username", username);
params.put("password", password);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
If you need more classes or the android manifest comment below and i edit the post.
I already have the login.php to connect to the database at the file manager and everything.
If you can help me understanding why this error is showing up i would be gratefull.
HTTP code 301 means "moved permanently". This means the URL you're trying to reach is no longer there. I had the same problem when my site implemented SSL. They redirected all request from http:// to https:// using an .htaccess file in the server, so the address in the Android app had to be changed accordingly, since it's not going to accept the redirection. You should change your LOGIN_REQUEST_URL variable to:
private static final String LOGIN_REQUEST_URL = "https://elabora.pt/login.php";
Hope this helps (it did solve my problem, though)
I had the same problem. Unexpected response code 301
I was using https://example.com but it was redirecting to https://www.example.com via .htaccess
Changing to https://www.example.com in the app code solved my problem.
Try to open the url in the browser here you can see the exactly redirected URL copy this to your code.
You can specify a http folder in your host or sever instead of auto redirect to https when you use volley.
It seems Volley can not handle https request.
How can we pass params from editText to url using request.GET method.
Actually I am trying to pass an email address as parameter to a api which should b attached to api-url .
I came to know from here that getParams() is not called on the GET method, so it seems you'll have to add it to the URL before you send the request.
suggest me any solution to achieve the task ..
when i pass REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser?email=ameer#novatoresols.com";
it return success=true response as expected because is registered user
but if i set REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser and pass the params (get value from edittext and use params.put in getparams() method ).response is always success=false i.e params is not attached to url
here is my code.
package com.example.mts3.hammadnewsapp;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.provider.SyncStateContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class RegisterActivity extends AppCompatActivity {
Button btn_verf;
EditText et_Email;
String u_emails,stat;
AlertDialog.Builder alertDialog;
private static final String TAG = "LoginActivity";
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Context context;
// public static String firstname, lastname, useremail, userphone, userpass;
// String REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser?email=ameer#novatoresols.com";
String REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
btn_verf=findViewById(R.id.btn_reg_send_vf_code);
et_Email=findViewById(R.id.et_reg_email);
alertDialog =new AlertDialog.Builder(RegisterActivity.this);
// u_emails=et_Email.getText().toString().trim();
btn_verf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callApi();
}
});
}
private void callApi() {
// Log.e(TAG, "onClick: ");
/*if (!utility.isInternetConnected()) {
Toast.makeText(LoginActivity.this, "Please check your internet connection.", Toast.LENGTH_SHORT).show();
return;
}*/
// dialog = utility.showProgressDialog(LoginActivity.this, "Please wait");
final String email = et_Email.getText().toString().trim();
// Log.e(TAG, "onClick: email = " + email );
// JSONObject params = new JSONObject();
/*
HashMap<String,String> params=new HashMap<>();
params.put("email",email);*/
/*try {
// params.getString("email");
params.put("email",email);
Log.e(TAG, "getParams: param = " + "try of put prams");
} catch (JSONException e){
Log.e(TAG, "getParams: param = " + "catch of put prams");
e.printStackTrace();
}*/
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, REG_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(RegisterActivity.this, "REsponse: " + response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> params=new HashMap<>();
// params.put("email",email);
params.put("email",email);
return params;
}
}; queue.add(stringRequest);
}
}
As suggested by #Puneet worked for me which is as :
getParams is only called for POST requests. GET requests don't have a body and hence, getParams is never called. For a simple request like yours just add the parameters to your URL and use that constructed URL to make that request to your server (REG_URL + "?email=" + email).
To pass the parameters, you need to create a class for the key-value pairs.
1) Create a class KeyValuePair with two fields key and value with appropriate constructor and getter-setter methods.
2) Now, for each parameter, you need to create an object of this class, i.e., for a key username with value user#gmail.com, the object would be new KeyValuePair("username", "user#gmail.com").
3) Now, you need to create a List to store these parameters and pass this list to the below method with your base url,
public static String generateUrl(String baseUrl, List<KeyValuePair> params) {
if (params.size() > 0) {
for (KeyValuePair parameter: params) {
if (parameter.getKey().trim().length() > 0)
baseUrl += "&" + parameter.getKey() + "=" + parameter.getValue();
}
}
return baseUrl;
}
4) Pass this baseUrl to your Request.
I was able to implement a Facebook login for a social networking app i am developing for android. I used Facebook's android sdk to do so, as well as getting first/last name, gender and age and displaying it on a profile page. Now i want to know how i can store this information on a database in order to display it to other users who visit the profile. Thanks in advance! Here is the code i am using for the profile page.
import android.content.Intent;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.widget.ImageView;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.squareup.picasso.Picasso;
import org.json.JSONObject;
public class ProfileActivity extends AppCompatActivity {
private Profile profile = Profile.getCurrentProfile();
public ImageView profileActivityPicture;
public TextView nameFirst, nameLast, age, gend, user_location;
private String userID, email, gender, picture, birthday, name, city;
private String profilePicUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("My Profile");
}
nameFirst = (TextView) findViewById(R.id.profileActivityFirstName);
nameLast = (TextView) findViewById(R.id.profileActivityLastName);
age = (TextView) findViewById(R.id.profileActivityAge);
gend = (TextView) findViewById(R.id.profileActivityGender);
profileActivityPicture = (ImageView) findViewById(R.id.profileActivityPic);
user_location = (TextView) findViewById(R.id.profileActivityCity);
if(profile != null) {
nameFirst.setText(getString(R.string.hello_user, profile.getFirstName()));
nameLast.setText(getString(R.string.hello_user, profile.getLastName()));
}
nameFirst.setTextSize(TypedValue.COMPLEX_UNIT_SP,20);
nameFirst.setTypeface(null, Typeface.BOLD);
nameLast.setTextSize(TypedValue.COMPLEX_UNIT_SP,20);
nameLast.setTypeface(null, Typeface.BOLD);
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject data,
GraphResponse response) {
try {
data = response.getJSONObject();
if (data.has("id"))
userID = data.getString("id");
if (data.has("name"))
name = data.getString("name");
if (data.has("location"))
city = data.getJSONObject("location").getString("name");
user_location.setText(city);
user_location.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
if (data.has("picture"))
Picasso.with(ProfileActivity.this).load("https://graph.facebook.com/" + userID+ "/picture?width=3000&height=4000").into(profileActivityPicture);
if (data.has("birthday"))
birthday = data.getString("birthday");
age.setText(birthday);
age.setTextSize(TypedValue.COMPLEX_UNIT_SP,20);
age.setTypeface(null, Typeface.BOLD);
if (data.has("gender"))
gender = data.getString("gender");
gend.setText(gender);
gend.setTextSize(TypedValue.COMPLEX_UNIT_SP,18);
} catch(Exception e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,cover,picture.type(large),location");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#Override
public void onBackPressed() {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
#Override
public void onDestroy(){
super.onDestroy();
}
}
When you get response in completed callback simply Parse like this
JSONObject jobj = response.getJSONObject();
if (jobj != null) {
try {
ProfileBean profileBean = new ProfileBean();
profileBean.id = jobj.getString("id");
profileBean.name = jobj.getString("name");
profileBean.email = jobj.getString("email");
profileBean.link = jobj.getString("link");
profileBean.last_name = jobj.getString("last_name");
profileBean.first_name = jobj.getString("first_name");
profileBean.gender = jobj.getString("gender");
JSONObject pic = jobj.getJSONObject("picture");
JSONObject data = pic.getJSONObject("data");
profileBean.profile_pic = data.getString("url");
} catch (Exception e) {
// print exception
}
}
here you FB data are stored in a profileBean so like this you can get your data..
I'm currently try to implement a two factor authentication system on a project i'm working on using twilio as a sms gateway service to request a random login token and then send it to the user as a text message. I followed the tutorial found here "https://www.twilio.com/blog/2016/05/how-to-send-an-sms-from-android.html" to test the service out. Following the tutorial I hosted the backend on Heroku. The app works just fine and says that the sms has been sent. However I never receive it. Any help would great.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.content.Context;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private EditText mTo;
private EditText mBody;
private Button mSend;
private OkHttpClient mClient = new OkHttpClient();
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTo = (EditText) findViewById(R.id.txtNumber);
mBody = (EditText) findViewById(R.id.txtMessage);
mSend = (Button) findViewById(R.id.btnSend);
mSend.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
try {
post(" https://cryptic-shore-79857.herokuapp.com", new
Callback(){
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response)
throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
mTo.setText("");
mBody.setText("");
Toast.makeText(getApplicationContext(),"SMS Sent!",Toast.LENGTH_SHORT).show();
}
});
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});
mContext = getApplicationContext();
}
Call post(String url, Callback callback) throws IOException {
RequestBody formBody = new FormBody.Builder()
.add("To", mTo.getText().toString())
.add("Body", mBody.getText().toString())
.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Call response = mClient.newCall(request);
response.enqueue(callback);
return response;
}
}
I'm thinking the URL that connects to Heroku is incorrect but I have no idea what it should be.
Twilio developer evangelist here.
You're POSTing your request to the wrong URL. Currently your code does:
try {
post("https://cryptic-shore-79857.herokuapp.com", new
Callback(){
But the path for the action that sends the SMS should be:
try {
post("https://cryptic-shore-79857.herokuapp.com/sms", new
Callback(){
Note, the /sms path.
Let me know if that helps at all.