Trying to get data for POST method Retrofit - android

Im trying to get username when I try to login to wev service.I need this username to check did I this right or no.But have NPE when try to get data,but when I just make Toast without data,it works!onResponse work,but I must to get code of this operation to build logic of my app.For example if my code==200,build new activity,else-build alertdialog or something else.
What I did wrong?
myFragment:
public class FeedFragment extends Fragment {
EditText username;
EditText password;
Button btnLogin;
public List<SignInResult> signInResult;
public static final String ROOT_URL = "https://api.vid.me/";
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_feed, container, false);
username = (EditText) rootView.findViewById(R.id.user_name_field);
password = (EditText) rootView.findViewById(R.id.password_field);
btnLogin = (Button)rootView.findViewById(R.id.button_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Authorize();
}
});
return rootView;
}
public void Authorize(){
Retrofit retrofitAdapter = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(ROOT_URL)
.build();
final VideoApi videoApi = retrofitAdapter.create(VideoApi.class);
String username_value = username.getText().toString();
String password_value = password.getText().toString();
Call<SignInResults> call = videoApi.insertUser(username_value,password_value);
call.enqueue(new Callback<SignInResults>() {
#Override
public void onResponse(Call<SignInResults> call, Response<SignInResults> response) {
Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT).show();
String response_value = response.body().signInResults.get(0).getUsername();
Log.d("FeedFragment",response_value);
}
#Override
public void onFailure(Call<SignInResults> call, Throwable t) {
}
});
}
}
my interface API:
public interface VideoApi {
#GET("/videos/featured")
Call<Videos> getFeaturedVideo();
#GET("/videos/new")
Call<Videos> getNewVideo();
#FormUrlEncoded
#POST("/auth/create")
Call<SignInResults>insertUser(#Field("username") String username,
#Field("password") String password
);
}
and error:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.vid_me_app.FeedFragment$2.onResponse(FeedFragment.java:59)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5751)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
at dalvik.system.NativeStart.main(Native Method)

SignInResults.java // Model class
clas SignInResults {
public Boolean status;
public Auth auth;
public User user;
}
User.java //User Model
public class User {
public String userId;
public String username;
public String avatar;
}
checkout this code in onResponse function
if (response.isSuccess()) {
SignInResults results = response.body();
if(results != null) {
String userName = results.user.username;
Log.d("User Name ==>> ", userName);
}
} else {
// Do whatever you want if API is unsuccessful.
}

Related

Sending a text with an editText is received in white in a TextView

I'm making an app but in this I need to put a username everything is fine, it does not give me any error but in the activity of "register user name" is just fine but in the following activity to save the text of that EditText does not go where it should, it goes blank I do not know what's happening
This is the class, to register the username
public class UsernameRegiserActivity extends AppCompatActivity {
private Button buttonRegisterAnonymous, buttonRegisterAUsername;
private EditText getAUsernameToRegister;
private User mUser;
private Post mPost;
private PostMemes mPostMemes;
private PostCreativo mPostCreativo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_username_regiser);
init();
}
private void init() {
buttonRegisterAnonymous = (Button) findViewById(R.id.buttonRegisterAsAnonymous);
buttonRegisterAUsername = (Button) findViewById(R.id.buttonRegister_aUsername);
getAUsernameToRegister = (EditText) findViewById(R.id.editText_registerUsername);
//==============================================================================
mUser = new User();
buttonRegisterAUsername.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nombre = getAUsernameToRegister.getText().toString();
mUser.setUsername(FirebaseUtils.getCurrentUser().getEmail().replaceAll(FirebaseUtils.getCurrentUser().getEmail(), nombre));
mUser.setUser(FirebaseUtils.getCurrentUser().getEmail().replaceAll(FirebaseUtils.getCurrentUser().getEmail(), nombre));
startActivity(new Intent(UsernameRegiserActivity.this, LogInActivity.class));
}
});
}
And in this fragment receives the name that has been placed in the editText
the relevant code:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mRootView = inflater.inflate(R.layout.fragment_post, container, false);
FloatingActionButton fab = (FloatingActionButton)
mRootView.findViewById(R.id.fabM);
mUser = new User();
return mRootView;
}
PopulateViewHolder...
viewHolder.postOwnerUsernameTextView.setText(mUser.getUser());
if(viewHolder.postOwnerUsernameTextView == null){
viewHolder.postOwnerUsernameTextView.setText("Anonymous");
}
the model class:
public class User implements Serializable{
private String user;
private String email;
private String Uid;
private String username;
public User() {
}
public User(String user) {
this.user = user;
}
public User(String user, String email, String uid, String username) {
this.user = user;
this.email = email;
Uid = uid;
this.username = username;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUid() {
return Uid;
}
public void setUid(String uid) {
Uid = uid;
}
}
and the utils that i use
public static DatabaseReference getUserRef(String email) {
return FirebaseDatabase.getInstance()
.getReference(Constants.USERS_KEYS)
.child(email);
}
public static FirebaseUser getCurrentUser() {
return FirebaseAuth.getInstance().getCurrentUser();
}
the user is created with this method
auth.createUserWithEmailAndPassword(email, password)
Sorry for my spelling and thanks for your attention.
In your Another Activity you create a new model class once again. That's why your editTank gone Blank. Let try this solution to transfer data between 2 class
make new interface class call TransferData
public interface TransferData{
void onTransferDataListener(String text);
}
Inside your activity let initial TransferData
public TransferData mTransferDataListener;
public void setTransferData(TransferData listener) {
this.mTransferDataListener= listener;
}
//whenever your make a new String from EditText, put it in this function
mTransferDataListener.onTransferDataListener(yourText);
Finally, in your class that you want to get Data, you just need to implement TransferData class, don't forget add this function to initial the receiver
//I call this function from my activity
mActivity.setTransferData(this);
after implement TransferData class, android studio will automatically add this override to receive the data
#Override
public void onTransferDataListener(String text) {
//do what ever you want with your String text here
}
Let's say I'm in my activity, it's a dialog which sends the strings to a fragment
In that dialogue could do this?
UsernameRegisterClass:
Public class UsernameRegister
TransferData mTransferData;
EditText mEditText;
Public void setmTransferData (TransferData lisenter) { This.mTransferData = lisenter;}
OnCreate (
  MTransferData.onTransferDataLisenter (mEditText.getText.toString ());
Dialog class:
DialogClass.setTransferData (this); #Override Public void onTransferDataListener (String text) { MPost.setUsermae (text) // I think I get the text here}
Private void sendPost () {
MPost.getUsername ();
// is the code okay?
}
 

Retrofit not getting data from api

I have some api that contains JSON with partner names.
I've set up interface and pojo model. I'll post below my code.
Here is my POJO model Partner:
public class Partner {
#SerializedName("name")
#Expose
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now here is my interface:
public interface APIService {
#GET("Partner")
Call<List<Partner>> getPartners();
}
And here is my APIHelper:
public class APIHelper {
public static final String PARTNERS_URL = "https://part-of-url.herokuapp.com/partners.json/";
public static APIService apiService;
public static APIService getApiService() {
if (apiService == null) {
Retrofit retrofit = new Retrofit.Builder().baseUrl(PARTNERS_URL)
.addConverterFactory(GsonConverterFactory.create()).build();
apiService = retrofit.create(APIService.class);
}
return apiService;
}
}
And this is Fragment which contains Button where onClick method needs to get data from web.
public class DownloadMain extends Fragment implements Callback<Partner> {
private static final String TAG = DownloadMain.class.getSimpleName();
private Button dloadPartners;
private Call callPartners;
public DownloadMain() {}
public DownloadMain newInstance() { return new DownloadMain(); }
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.download_main, container, false);
dloadPartners = (Button) view.findViewById(R.id.downloadPartners);
dloadPartners.setOnClickListener(btnListener);
callPartners = APIHelper.getApiService().getPartners();
return view;
}
Button.OnClickListener btnListener = (new Button.OnClickListener() {
#Override
public void onClick(View v) {
callPartners.clone().enqueue(DownloadMain.this);
}
});
#Override
public void onResponse(Call call, Response response) {
if(response.body() == null) {
try {
response.errorBody().string();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getActivity(), "No Partners!", Toast.LENGTH_SHORT).show();
} else {
List<String> partners = (List<String>) response.body();
Log.d(TAG, "Number of partners received: " + partners.size());
Toast.makeText(getActivity(), "Partners downloaded!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call call, Throwable t) {
}
}
This is all my code for getting Partners from web.
I'm getting this error on server side and can't resolve it:
No route matches [GET] "/partners.json/Partner"
QUESTION: Can someone look at this code and say what is wrong and why I'm not getting data from web and also how should I resolve this no route error?
change your get path like so
public interface APIService {
#GET("partners.json")
Call<List<Partner>> getPartners();
}
and remove that path from your base url.
public class APIHelper {
public static final String PARTNERS_URL = "https://part-of-url.herokuapp.com/";
public static APIService apiService;
public static APIService getApiService() {
if (apiService == null) {
Retrofit retrofit = new Retrofit.Builder().baseUrl(PARTNERS_URL)
.addConverterFactory(GsonConverterFactory.create()).build();
apiService = retrofit.create(APIService.class);
}
return apiService;
}
}

NPE in onResponse method using Retrofit

Im trying to get data from onResponse method through Retrofit library.But now I have that respone==0.I neew to get code of my request,to build logic in my app.For example if code==200,start new activity is something else build error message.
I'm trying to build right POST method to vid.me servise.That service have open API,method what I need:
https://docs.vid.me/#api-Auth-Create
myFragment:
public class FeedFragment extends Fragment {
EditText username;
EditText password;
Button btnLogin;
public List<SignInResult> signInResult;
String username_value,password_value;
public static final String ROOT_URL = "https://api.vid.me/";
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_feed, container, false);
username = (EditText) rootView.findViewById(R.id.user_name_field);
password = (EditText) rootView.findViewById(R.id.password_field);
btnLogin = (Button) rootView.findViewById(R.id.button_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Authorize();
}
});
return rootView;
}
public void Authorize() {
Retrofit retrofitAdapter = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(ROOT_URL)
.build();
final VideoApi videoApi = retrofitAdapter.create(VideoApi.class);
username_value = username.getText().toString();
password_value = password.getText().toString();
Call<SignInResults> call = videoApi.insertUser(username_value,password_value);
call.enqueue(new Callback<SignInResults>() {
#Override
public void onResponse(Call<SignInResults> call, Response<SignInResults> response) {
SignInResults results = response.body();
Log.d("Response ==>> ", new GsonBuilder().setPrettyPrinting().create().toJson(results));
}
#Override
public void onFailure(Call<SignInResults> call, Throwable t) {
}
});
}
}
API interface:
public interface VideoApi {
#GET("/videos/featured")
Call<Videos> getFeaturedVideo();
#GET("/videos/new")
Call<Videos> getNewVideo();
#Headers("Content-Type:application/x-www-form-urlencoded")
#FormUrlEncoded
#POST("/auth/create")
Call<SignInResults>insertUser(#Field("email") String username,
#Field("password") String password
);
}
SignInResult class:
public class SignInResult {
public String getAuthorization() {
return authorization;
}
public void setAuthorization(String authorization) {
this.authorization = authorization;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
#SerializedName("authorization")
#Expose
private String authorization;
#SerializedName("code")
#Expose
private String code;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#SerializedName("username")
#Expose
private String username;
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
#SerializedName("user_id")
#Expose
private String user_id;
}
SignInResults class:
public class SignInResults {
public SignInResult signInResult;
public List<SignInResult> getSignInResults() {
return signInResults;
}
List<SignInResult> signInResults;
}
You have to change this code to handle results properly
Call<SignInResults> call = videoApi.insertUser(username_value,password_value);
call.enqueue(new Callback<SignInResults>() {
#Override
public void onResponse(Call<SignInResults> call, Response<SignInResults> response) {
if(response.isSuccessful()) {
SignInResults results = response.body();
Log.d("Response ==>> ", new GsonBuilder().setPrettyPrinting().create().toJson(results));
}
else {
// handle error
}
}
#Override
public void onFailure(Call<SignInResults> call, Throwable t) {
}
});

NPE try to login at web service [duplicate]

I want to login in some service called vid.me,https://api.vid.me/oauth/authorize with POST.But when I try to get data from log I have NullPointerException.I tryed to make Toast and have this error too.I'm trying to get response code to see I did this right or no.
my API class:
public interface VideoApi {
#GET("/videos/featured")
Call<Videos> getFeaturedVideo();
#GET("/videos/new")
Call<Videos> getNewVideo();
#FormUrlEncoded
#POST("oauth/authorize")
Call<SignInResults>insertUser(#Field("name") String name,
#Field("password") String password
);
}
my fragment:
public class FeedFragment extends Fragment {
EditText username;
EditText password;
Button btnLogin;
public List<SignInResult> signInResult;
public static final String ROOT_URL = "https://api.vid.me/";
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_feed, container, false);
username = (EditText) rootView.findViewById(R.id.user_name_field);
password = (EditText) rootView.findViewById(R.id.password_field);
btnLogin = (Button)rootView.findViewById(R.id.button_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Authorize();
}
});
return rootView;
}
public void Authorize(){
Retrofit retrofitAdapter = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(ROOT_URL)
.build();
final VideoApi videoApi = retrofitAdapter.create(VideoApi.class);
Call<SignInResults> call = videoApi.insertUser(username.getText().toString(),password.getText().toString());
call.enqueue(new Callback<SignInResults>() {
#Override
public void onResponse(Call<SignInResults> call, Response<SignInResults> response) {
Log.d("FeedFragment", "Status Code = " + response.body().signInResults.get(0).getCode());
}
#Override
public void onFailure(Call<SignInResults> call, Throwable t) {
}
});
}
}
Call<SignInResponse> call = videoApi.insertUser(username_value, password_value);
call.enqueue(new Callback<SignInResponse>() {
#Override
public void onResponse(Call<SignInResponse> call, Response<SignInResponse> response) {
SignInResponse results = response.body();
Log.d("Response ==>> ", new GsonBuilder().setPrettyPrinting().create().toJson(results));
}
#Override
public void onFailure(Call<SignInResponse> call, Throwable t) {
}
});
#Headers("Content-Type:application/x-www-form-urlencoded")
#FormUrlEncoded
#POST("/auth/create")
Call<SignInResponse> insertUser(#Field("email") String username,
#Field("password") String password
);

Login Using Retrofit not working

I m creating user login with retrofit but i can't get username and password from the server()mysql ..I don't know what i m doing wrong.
Interface
public interface LoginApi {
#FormUrlEncoded
#POST("/zaala/retrofitlogin.php")
public void getlogin(
#Field("username") String username,
#Field("password")String password,
Callback response
);
MainActivity
private static final String ROOT_LOGIN = "http://xxxxx.com";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editTextUsername = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
buttonlogin = (Button) findViewById(R.id.buttonlogin);
buttonlogin.setOnClickListener(this);
restAdapter = new RestAdapter.Builder().setEndpoint(ROOT_LOGIN).build();
restAdapter.setLogLevel(RestAdapter.LogLevel.FULL);
loginApi = restAdapter.create(LoginApi.class);
}
#Override
public void onClick(View v) {
loginApi.getlogin(editTextUsername.getText().toString(), editTextPassword.getText().toString(), new Callback<String>() {
#Override
public void success(String s, Response response) {
Toast.makeText(LoginActivity.this,"Logged in",Toast.LENGTH_LONG).show();
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(LoginActivity.this,"Logged Failed",Toast.LENGTH_LONG).show();
}
});
}
Help--- i m using php code

Categories

Resources