Hello me and my group from university decide to create an app, that a client of a gym can see his/her exercise list and we are using retrofit to get a json. Early this code was working very well, but suddenly stopped to work, and now I'm getting null response and status 200 from callback.
image with the log.d 200 and null response
Sorry for my english.
My JSON
{
"0":{
"id":"1",
"nome":"Fernanda Kondrat",
"peso":"67.4",
"altura":"172",
"imc":"22.8",
"login":"fefe",
"senha":"1234"},
"lista_exercicios":[
{
"id":"1",
"id_aluno":"1",
"nome":"supino reto",
"num_serie":"3",
"num_repeticao":"10"
},
{
"id":"2",
"id_aluno":"1",
"nome":"agachamento hack",
"num_serie":"3",
"num_repeticao":"10"
},
{
"id":"3",
"id_aluno":"1",
"nome":"barra fixa",
"num_serie":"3",
"num_repeticao":"10"
},
{
"id":"4",
"id_aluno":"1",
"nome":"leg press",
"num_serie":"4",
"num_repeticao":"10"
}
]
}
And now my MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.u9.fabapp.virtualgym.APIClient;
import com.u9.fabapp.virtualgym.RespostaLogin;
import com.u9.fabapp.virtualgym.Resposta;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class MainActivity extends AppCompatActivity {
Button btn_login;
EditText edt_login;
EditText edt_senha;
private Callback<RespostaLogin> respostaCallback;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_login = findViewById(R.id.btn_login);
edt_login = findViewById(R.id.edt_Login);
edt_senha= findViewById(R.id.edt_Senha);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Log.d(TAG, "onClick: ");
//Intent i = new Intent(MainActivity.this, ProfileActivity.class);
//startActivity(i);
String login = edt_login.getText().toString();
String senha = edt_senha.getText().toString();
if(TextUtils.isEmpty(login)|| TextUtils.isEmpty(senha)) {
Toast.makeText(MainActivity.this, "Campos vazios", Toast.LENGTH_SHORT).show();
} else {
configurarCallback();
//new APIClient().getRestService().setUsuarioLoginDTO(login, senha, respostaCallback);
new APIClient().getRestService().setUsuarioLoginDTO(login, senha, respostaCallback);
}
}
});
}
private void configurarCallback() {
respostaCallback = new Callback<RespostaLogin>() {
#Override
public void success(RespostaLogin resposta, Response response) {
Log.d(TAG, "Funcionou: "+ response.getStatus());
Log.d(TAG, "Funcionou: " + resposta.getRETORNO());
/*if (resposta.getRETORNO().equals("SUCESSO")){
Intent intent1 = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(intent1);
}else{
Toast.makeText(MainActivity.this, resposta.getRETORNO() +" ,Verifique usuário e senha" , Toast.LENGTH_SHORT).show();
}*/
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(MainActivity.this, "Deu Ruim: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
};
}
}
APIClient.java
import com.u9.fabapp.virtualgym.Resposta;
import com.u9.fabapp.virtualgym.RespostaLogin;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
import retrofit.http.GET;
import retrofit.http.Query;
import retrofit.http.Path;
public class APIClient {
private static RestAdapter REST_ADAPTER;
public APIClient(){
createAdapterIfNeeded();
}
private static void createAdapterIfNeeded() {
if(REST_ADAPTER == null){
REST_ADAPTER = new RestAdapter
.Builder()
.setEndpoint("http://golfetto.16mb.com/virtual-fit/home/")
.setLogLevel(RestAdapter.LogLevel.FULL)
.setClient(new OkClient())
.build();
}
}
public RestServices getRestService(){
return REST_ADAPTER.create(RestServices.class);
}
public interface RestServices{
#GET("/getExercicios.php")
void setUsuarioLoginDTO(
#Query("LOGIN") String login,
#Query("SENHA") String senha,
Callback<RespostaLogin> callbackResposta
);
}
}
In interface "RestService", change at:
#GET("/getExercicios.php")
Modify it as:
#GET("getExercicios.php")
Remove "/" because it is being already being appended.
Thanks and happy coding
The full URL of your service will be
BASE_URL (defined at the time of createing retrofit object) + END_POINT_URL (defined in the interface)
You have added "http://golfetto.16mb.com/virtual-fit/home/" as base URL and in the interface you have define the endpoint as "/getExercicios.php" so the full URL will be
"http://golfetto.16mb.com/virtual-fit/home//getExercicios.php"
which is not a valid URL. So you have to remove '/' from the interface
The interface will be
public interface RestServices{
#GET("getExercicios.php")
void setUsuarioLoginDTO(
#Query("LOGIN") String login,
#Query("SENHA") String senha,
Callback<RespostaLogin> callbackResposta
);
}
Related
Hi I'm following this video tutorial https://www.youtube.com/watch?v=wQN2eCO-M_Q&t=7717s (the part I suppose create this issue can be found at time 2:01:17)and I managed to make this code work without implementing the notifications, but it only works on the simulator.
When I try to debug it with my phone it gives me the following error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.chat, PID: 7894
java.lang.RuntimeException: Could not deserialize object. Failed to convert value of type java.lang.Long to Timestamp (found in field 'timestamp')
On others real devices it works properly but on my real me 8 pro it does not
here is some code from my android studio:
ChatModel.java
package com.example.chat.model;
import com.google.firebase.Timestamp;
import java.sql.Time;
import java.util.Date;
public class ChatModel {
String message;
String user_name;
String messageID;
String user_image_url;
String chat_image;
Timestamp timestamp;
public ChatModel() {
}
public ChatModel(String message, String user_name, String messageID, String user_image_url, String chat_image, Timestamp timestamp) {
this.message = message;
this.user_name = user_name;
this.messageID = messageID;
this.user_image_url = user_image_url;
this.chat_image = chat_image;
this.timestamp = timestamp;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getMessageID() {
return messageID;
}
public void setMessageID(String messageID) {
this.messageID = messageID;
}
public String getUser_image_url() {
return user_image_url;
}
public void setUser_image_url(String user_image_url) {
this.user_image_url = user_image_url;
}
public String getChat_image() {
return chat_image;
}
public void setChat_image(String chat_image) {
this.chat_image = chat_image;
}
public Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
}
i have tried to change Timestamp with: long, Long, Date and Number.
But i wouldn't work anyways
MainActivity.java
package com.example.chat;
import static com.example.chat.cords.FirebaseCords.MAIN_CHAT_DATABASE;
import static com.example.chat.cords.FirebaseCords.mAuth;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.chat.adapter.ChatAdapter;
import com.example.chat.cords.FirebaseCords;
import com.example.chat.model.ChatModel;
import com.example.chat.model.SaveState;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.Query;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Queue;
public class MainActivity extends AppCompatActivity {
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null) {
startActivity(new Intent(this, LoginActivity.class));
finish();
}
chatAdapter.startListening();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.chat_room, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.logout:
mAuth.signOut();
startActivity((new Intent(this, LoginActivity.class)));
break;
}
return super.onOptionsItemSelected(item);
}
EditText chat_box;
RecyclerView chat_list;
ChatAdapter chatAdapter;
Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chat_box = findViewById(R.id.chat_box);
chat_list = findViewById(R.id.chat_list);
initChatList();
}
private void initChatList() {
chat_list.setHasFixedSize(true);
chat_list.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true));
Query query = MAIN_CHAT_DATABASE.orderBy("timestamp", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<ChatModel> option = new FirestoreRecyclerOptions.Builder<ChatModel>()
.setQuery(query, ChatModel.class)
.build();
chatAdapter = new ChatAdapter(option);
chat_list.setAdapter(chatAdapter);
chatAdapter.startListening();
}
public void addMessage(View view) {
String message = chat_box.getText().toString();
FirebaseUser user = mAuth.getCurrentUser();
if (!TextUtils.isEmpty(message)) {
/*Generate messageID using the current date. */
Date today = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String messageID = format.format(today);
/*Getting user image from Google account*/
String user_image_url = "";
Uri photoUrl = user.getPhotoUrl();
String originalUrl = "s96-c/photo.jpg";
String resizeImageUrl = "s400-c/photo.jpg";
if (photoUrl!=null) {
String photoPath = photoUrl.toString();
user_image_url = photoPath.replace(originalUrl,resizeImageUrl);
}
HashMap<String, Object> messageObj = new HashMap<>();
messageObj.put("message", message);
messageObj.put("user_name", user.getDisplayName());
messageObj.put("timestamp",FieldValue.serverTimestamp());
messageObj.put("messageID", messageID);
messageObj.put("chat_image","");
messageObj.put("user_image_url", user_image_url);
MAIN_CHAT_DATABASE.document(messageID).set(messageObj).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Message send", Toast.LENGTH_SHORT).show();
chat_box.setText("");
} else {
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
public void OpenExplorer(View view) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_GRANTED) {
ChoseImage();
} else {
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 20);
} else {
Toast.makeText(this, "Storage Permission Needed", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 20);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 20) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
ChoseImage();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
private void ChoseImage(){
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(MainActivity.this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,#Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
Log.d("TAG", "onActivityResult:"+result);
if (resultCode == RESULT_OK) {
imageUri = result.getUri();
Log.d("TAG", "onActivityResult:"+imageUri);
startActivity(new Intent(MainActivity.this, ImageUploadPreview.class)
.putExtra("image_uri", imageUri.toString()));
} else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(this, result.getError().getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
public void Finish(View view) {
long currentTime = new Date().getTime();
new SaveState(this).setClickTime(currentTime);
finish();
}
}
ChatAdapter.java
package com.example.chat.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.chat.R;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.example.chat.model.ChatModel;
import org.w3c.dom.Text;
import de.hdodenhof.circleimageview.CircleImageView;
public class ChatAdapter extends FirestoreRecyclerAdapter<ChatModel, ChatAdapter.ChatViewHolder> {
public ChatAdapter (#NonNull FirestoreRecyclerOptions <ChatModel> options) {
super(options);
}
#Override
protected void onBindViewHolder (#NonNull ChatViewHolder chatViewHolder, int i, #NonNull ChatModel chatModel) {
chatViewHolder.message.setText(chatModel.getMessage());
Glide.with(chatViewHolder.user_image.getContext().getApplicationContext())
.load(chatModel.getUser_image_url())
.into(chatViewHolder.user_image);
if(!chatModel.getChat_image().equals("")){
Glide.with(chatViewHolder.chat_image.getContext().getApplicationContext())
.load(chatModel.getChat_image())
.into(chatViewHolder.chat_image);
chatViewHolder.chat_image.setVisibility(View.VISIBLE);
}else{
chatViewHolder.chat_image.setVisibility(View.GONE);
}
}
#NonNull
#Override
public ChatViewHolder onCreateViewHolder (#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_item,parent,false);
return new ChatViewHolder(v);
}
class ChatViewHolder extends RecyclerView.ViewHolder {
TextView message;
CircleImageView user_image;
ImageView chat_image;
public ChatViewHolder(#NonNull View itemView) {
super(itemView);
message = itemView.findViewById(R.id.message);
user_image = itemView.findViewById(R.id.user_image);
chat_image = itemView.findViewById(R.id.chat_image);
}
}
}
Screenshoot of thedatabase structure:
here
I have no idea how to solve that error can someone help me?
If you need any more information comment i will add it as soon as i see the message thanks in advance.
I am developing Login on android via connection with php (web).
Code
package com.example.salmakhalil.myapplication;
import android.content.Intent;
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.ProgressBar;
import android.widget.TextView;
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.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class LoginActivity extends AppCompatActivity {
private EditText email,password;
private Button btn_login;
private TextView link_regist;
private ProgressBar loading;
private static String URL_LOGIN="http://192.168.8.101/android_register_login/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loading=findViewById(R.id.loading);
email=findViewById(R.id.email);
password=findViewById(R.id.password);
btn_login=findViewById(R.id.btn_login);
link_regist=findViewById(R.id.link_regist);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail=email.getText().toString().trim();
String mPass=password.getText().toString().trim();
if (!mEmail.isEmpty() || !mPass.isEmpty()){
Login(mEmail,mPass);
}
else {
email.setError("Please insert email");
password.setError("Please insert Password");
}
}
});
link_regist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
}
});
}
private void Login(String email, String password){
loading.setVisibility(View.VISIBLE);
btn_login.setVisibility(View.GONE);
//I think here facing a problem
StringRequest stringRequest=new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray=jsonObject.getJSONArray("login");
if (success.equals("1")) {
for (int i=0; i<jsonArray.length();i++){
JSONObject object = jsonArray.getJSONObject(i);
String name = object.getString("name").trim();
String email=object.getString( "email").trim();
Toast.makeText(LoginActivity.this,
"Success Login. \nYour Name : "
+name+"\nYour Email : "
+email, Toast.LENGTH_SHORT)
.show();
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(LoginActivity.this, "Error!!! " +e.toString(),
Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Error!! " +error.toString(),
Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
When I click on the login Button, its showing thee error
org.json.JSONException: No value for success.
I'm all the day trying to fix it. I have read other posts on Stack, no one helped me. I hope you can help me. Thanks.
Apparently the jsonObject your receive in onResponse() does not have a value for entry "success"
You should use the method jsonObject.optString("success"); instead of jsonObject.getString("success");
optString("success") returns the empty string ("") if the key "success" doesn't exist. getString("success") on the other hand throws a JSONException.
Can you share the response that is supposed to get. I think the response doesn't contain any field name "success". Query on postman to get response otherwise talk to your back end developer.
So I'm a beginner in developing android application i wanna know how do you implement websocket to my android application so that i can get the data's from our server
I have tried deserialization the data from json to java so that they'll be able to communicate once the connection is established
package com.example.app;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import java.net.URI;
import java.net.URISyntaxException;
public class MainActivity extends Activity {
private WebSocketClient mWebSocketClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectWebSocket();
}
private void connectWebSocket() {
URI uri;
try {
uri = new URI("ws://10.24.204.215:9090");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
#Override
public void onOpen(ServerHandshake handshakedata) {
Log.i("Websocket", "Opened");
mWebSocketClient.send("Hello from" + Build.MANUFACTURER + " " + Build.MODEL );
}
#Override
public void onMessage(String s) {
final String uiview = s;
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView textView = (TextView)findViewById(R.id.uiview);
textView.setText(textView.getText() + "\n" + uiview);
}
});
}
#Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed" + s);
}
#Override
public void onError(Exception e) {
Log.i("Websocket", "Error" + e.getMessage());
}
};
mWebSocketClient.connect();
}
IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
public void sendMessage(View view) {
EditText editText = (EditText) findViewById(R.id.edittxt);
String mWebSocketClient = editText.getText().toString();
editText.setText("");
}
}
It wont let me display gather the data's from the WS to display it to my mobile screen.
I am using com.paypal.android.MEP.PayPalActivity library. I want to edit layout but I can't access it. How can I edit default layout of this library. I am trying to transfer money from an account to another account. It works correctly but user interface seems bad
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalActivity;
import com.paypal.android.MEP.PayPalAdvancedPayment;
import com.paypal.android.MEP.PayPalPayment;
import com.paypal.android.MEP.PayPalReceiverDetails;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import project.com.holobech.MainActivity;
import project.com.holobech.R;
import project.com.holobech.app.AppConfig;
import project.com.holobech.app.AppController;
import project.com.holobech.model.UserList;
import project.com.holobech.util.PaypalUtil;
public class PaypalActivity extends ActionBarActivity {
// LogCat tag
private static final String TAG = PaypalActivity.class.getSimpleName();
public final int PAYPAL_RESPONSE = 100;
TextView txtOdullendirEmail;
TextView txtOdullendirAmount;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paypal);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
txtOdullendirEmail = (TextView) findViewById(R.id.txt_odullendir_email);
txtOdullendirEmail.setText("Ödüllendirilecek E-Posta : " + ProfileFragment.email);
txtOdullendirAmount= (TextView) findViewById(R.id.txt_odullendir_amount);
txtOdullendirAmount.setText("Ödüllendirilecek Miktar : 1$");
Button paypal_button = (Button) findViewById(R.id.paypal_button);
initLibrary();
paypal_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// pay integration here
PayPalButtonClick(ProfileFragment.email, "1");
}
});
}
public void initLibrary() {
PayPal pp = PayPal.getInstance();
if (pp == null) {
pp = PayPal.initWithAppID(this, PaypalUtil.paypal_liv_id,
PayPal.ENV_LIVE);
}
}
public void PayPalButtonClick(String primary_id, String primary_amount) {
// Create a basic PayPal payment
// PayPalPayment newPayment = new PayPalPayment();
// newPayment.setSubtotal(new BigDecimal("1.0"));
// newPayment.setCurrencyType("USD");
// newPayment.setRecipient("npavankumar34#gmail.com");
// newPayment.setMerchantName("My Company");
// Log.d("pavan", "calling intent");
// if( PayPal.getInstance()!=null){
// Log.d("pavan", "in if");
// Intent paypalIntent = PayPal.getInstance().checkout(newPayment,
// this);
// startActivityForResult(paypalIntent, 1);
//
// config reciever1
PayPalReceiverDetails receiver0;
receiver0 = new PayPalReceiverDetails();
receiver0.setRecipient(primary_id);
receiver0.setSubtotal(new BigDecimal(primary_amount));
// adding payment type
PayPalAdvancedPayment advPayment = new PayPalAdvancedPayment();
advPayment.setCurrencyType("TRY");
advPayment.getReceivers().add(receiver0);
Intent paypalIntent = PayPal.getInstance().checkout(advPayment, this);
this.startActivityForResult(paypalIntent, PAYPAL_RESPONSE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("pavan", "response");
if (requestCode == PAYPAL_RESPONSE) {
switch(resultCode) {
case Activity.RESULT_OK:
//The payment succeeded
String payKey =
data.getStringExtra(PayPalActivity.EXTRA_PAY_KEY);
Log.d("pavan", "success "+payKey);
Toast.makeText(getApplicationContext(), "Payment done succesfully ", Toast.LENGTH_LONG).show();
setMoneyTransfer();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getApplicationContext(), "Payment Canceled , Try again ", Toast.LENGTH_LONG).show();
break;
case PayPalActivity.RESULT_FAILURE:
Toast.makeText(getApplicationContext(), "Payment failed , Try again ", Toast.LENGTH_LONG).show();
break;
}
}
}
private void setMoneyTransfer() {
// istek iptali için tag
String tag_string_req = "req_money_transfer";
pDialog.setMessage("Lütfen bekleyin...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.URL_CONTEST, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Para transferi yanıtı : " + response.toString());
hideDialog();
try{
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// json hatası kontrolü
if (!error) {
// başarılı
Log.d("Response", response.toString());
} else {
// başarısız
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON hatası
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Para transferi Hatası: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// login urle bilgileri gönder
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "money_transfer");
params.put("sender", MainActivity.PROFILE_EMAIL);
params.put("receiver", ProfileFragment.email);
return params;
}
};
// istek kuyruğuna isteği ekle
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
This checkout page layout is default and there is no way you can edit the layout.
Below I've listed my activity code, call out to the web service, and the json parsing class I created to parse the web service results. I'm trying to pass a user object back to the activity to determine what they can/can't do, however, I'm not getting past the "after execute" log statement. onRequestFinished never gets called which is where I would have expected it to end up. Any help would be greatly appreciated as there doesn't seem to be much activity with DataDroid...
LoginActivity.java
package com.motosho.ui;
import com.foxykeep.datadroid.requestmanager.Request;
import com.foxykeep.datadroid.requestmanager.RequestManager.RequestListener;
import com.motosho.R;
import com.motosho.data.model.User;
import com.motosho.data.requestmanager.RequestFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.content.Intent;
public final class LoginActivity extends DataDroidActivity implements RequestListener,
OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
bindViews();
}
protected void onResume() {
super.onResume();
for(int i=0; i < mRequestList.size(); i++) {
Request request = mRequestList.get(i);
if(mRequestManager.isRequestInProgress(request)) {
mRequestManager.addRequestListener(this, request);
setProgressBarIndeterminateVisibility(true);
} else {
mRequestManager.callListenerWithCachedData(this, request);
i--;
mRequestList.remove(request);
}
}
}
protected void onPause() {
super.onPause();
if(!mRequestList.isEmpty()) {
mRequestManager.removeRequestListener(this);
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
private void bindViews() {
((Button) findViewById(R.id.sign_in_button)).setOnClickListener(this);
}
private void callLoginWS(String username, String pin, String eventId) {
Log.i("LOGIN", "in callLoginWS - username=" + username + ", pin=" + pin + ", eventid=" + eventId);
setProgressBarIndeterminateVisibility(true);
Request request = RequestFactory.getLoginRequest(username, pin, eventId);
mRequestManager.execute(request, this);
Log.i("LOGIN", "after execute");
mRequestList.add(request);
}
public void onClick(View view) {
switch(view.getId()) {
case R.id.sign_in_button:
EditText emailText = (EditText) findViewById(R.id.email);
EditText pinText = (EditText) findViewById(R.id.pin);
Log.i("LOGIN","set email and pin text");
callLoginWS(emailText.getText().toString(), pinText.getText().toString(),"9");
break;
}
}
#Override
public void onRequestFinished(Request request, Bundle resultData) {
Log.i("LOGIN", "inside onRequestFinished");
if(mRequestList.contains(request)) {
setProgressBarIndeterminateVisibility(false);
Log.i("LOGIN", "request found");
mRequestList.remove(request);
Toast toast = Toast.makeText(this, "request finished", Toast.LENGTH_SHORT);
toast.show();
User user = resultData.getParcelable("user");
if(user != null) {
startActivity(new Intent(this, MainActivity.class).putExtras(resultData));
}
}
}
#Override
public void onRequestConnectionError(Request request, int statusCode) {
Log.i("LOGIN", "onRequestConnectionError");
if(mRequestList.contains(request)) {
setProgressBarIndeterminateVisibility(false);
//show error
Toast toast = Toast.makeText(this, "connection error", Toast.LENGTH_SHORT);
toast.show();
mRequestList.remove(request);
}
}
#Override
public void onRequestDataError(Request request) {
Log.i("LOGIN", "onRequestDataError");
if(mRequestList.contains(request)) {
setProgressBarIndeterminateVisibility(false);
mRequestList.remove(request);
//show error
Toast toast = Toast.makeText(this, "data error", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onRequestCustomError(Request request, Bundle resultData) {
// Never called
}
public void connectionErrorDialogRetry(Request request) {
Log.i("LOGIN", "connectionErrorDialogRetry");
String username = request.getString("username");
String pin = request.getString("pin");
String eventId = request.getString("eventid");
callLoginWS(username,pin,eventId);
}
}
LoginOperation.java
package com.motosho.data.operation;
import java.util.HashMap;
import android.content.Context;
import android.os.Bundle;
import com.foxykeep.datadroid.exception.ConnectionException;
import com.foxykeep.datadroid.exception.CustomRequestException;
import com.foxykeep.datadroid.exception.DataException;
import com.foxykeep.datadroid.network.NetworkConnection;
import com.foxykeep.datadroid.network.NetworkConnection.ConnectionResult;
import com.foxykeep.datadroid.network.NetworkConnection.Method;
import com.foxykeep.datadroid.requestmanager.Request;
import com.foxykeep.datadroid.service.RequestService.Operation;
import com.motosho.config.WSConfig;
import com.motosho.data.factory.LoginJsonFactory;
public final class LoginOperation implements Operation {
#Override
public Bundle execute(Context context, Request request)
throws ConnectionException, DataException, CustomRequestException {
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", request.getString("username"));
params.put("pin", request.getString("pin"));
params.put("eventid", request.getString("eventid"));
NetworkConnection networkConnection = new NetworkConnection(context, WSConfig.WS_LOGIN_URL);
networkConnection.setMethod(Method.POST);
networkConnection.setParameters(params);
ConnectionResult result = networkConnection.execute();
return LoginJsonFactory.parseResult(result.body);
}
}
LoginJsonFactory.java
package com.motosho.data.factory;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.util.Log;
import com.foxykeep.datadroid.exception.DataException;
import com.motosho.config.JSONTag;
import com.motosho.data.model.User;
public final class LoginJsonFactory {
private static final String TAG = LoginJsonFactory.class.getName();
private LoginJsonFactory() { }
#SuppressWarnings("null")
public static Bundle parseResult(String wsResponse) throws DataException {
User user = new User();
try {
JSONObject parser = new JSONObject(wsResponse);
JSONObject jsonRoot = parser.getJSONObject(JSONTag.USER_ELEM);
user.firstName = jsonRoot.getString(JSONTag.USER_ELEM_FIRST_NAME);
user.lastName = jsonRoot.getString(JSONTag.USER_ELEM_LAST_NAME);
user.phoneNumber = jsonRoot.getString(JSONTag.USER_ELEM_PHONE_NUMBER);
user.role = jsonRoot.getString(JSONTag.USER_ELEM_ROLE);
JSONArray jsonPositionsArray = jsonRoot.getJSONArray(JSONTag.USER_ELEM_LIST_POSITIONS);
int size = jsonPositionsArray.length();
List<String> tempPositionsArray = null;
for (int i=0; i < size; i++) {
tempPositionsArray.add(jsonPositionsArray.getString(i));
}
user.positions = tempPositionsArray;
JSONArray jsonCapabilitiesArray = jsonRoot.getJSONArray(JSONTag.USER_ELEM_LIST_CAPABILITIES);
size = jsonCapabilitiesArray.length();
List<String> tempCapabilitiesArray = null;
for(int i=0; i < size; i++) {
tempCapabilitiesArray.add(jsonCapabilitiesArray.getString(i));
}
user.capabilities = tempCapabilitiesArray;
} catch (JSONException e) {
Log.e(TAG, "JSONException", e);
throw new DataException(e);
}
Bundle bundle = new Bundle();
bundle.putParcelable("user", user);
return bundle;
}
}