Access button from external class - android

In my app I have an Activity LoginUserActivity that contains a button perform a connection to a web-server using JSONObject request and Volley. If the login is successfull will be launched another activity, but if it isn't I need to re-enable the button.
LoginUserActivity
public void OnLoginUtente(View view) {
final String mail = etMail.getText().toString();
final String pw = etPassword.getText().toString();
bLogin.setEnabled(false);
DBConnection connection = new DBConnection(mail, pw, getApplicationContext());
connection.doLogin();
}
doLogin()
public void doLogin() {
JSONObject obj = new JSONObject();
try {
obj.put("type", type);
obj.put("email", email);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Toast.makeText(context, response.getString("Status"), Toast.LENGTH_SHORT).show();
if (response.getString("Esito").equals("true")) {
intent = new Intent(context, MainUtente.class);
context.startActivity(intent);
}else{
//I think I've to put something here
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
jsonObjectRequest.setShouldCache(false);
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.getCache().clear();
requestQueue.add(jsonObjectRequest);
}
I've tried different things, such as make doLogin() return a boolean and then re-enable the button from the activity or try to inflate the layout of the calling activity in the else, but neither of these worked. If possible I'd like to keep the doLogin() method void and without parameters.

LoginUserActivity
public void OnLoginUtente(View view) {
final String mail = etMail.getText().toString();
final String pw = etPassword.getText().toString();
DBConnection connection = new DBConnection(mail, pw, getApplicationContext());
connection.doLogin(this);
}
public void disableLoginButton()
{
bLogin.setEnabled(false);
}
doLogin
public void doLogin(final LoginActivity activity) {
JSONObject obj = new JSONObject();
try {
obj.put("type", type);
obj.put("email", email);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Toast.makeText(context, response.getString("Status"), Toast.LENGTH_SHORT).show();
if (response.getString("Esito").equals("true")) {
new Handler(Looper.getMainLooper()).post(new Runnable(){
public void run() {
activity.disableLoginButton();
}
);
activity.disableLoginButton();
intent = new Intent(context, MainUtente.class);
context.startActivity(intent);
}else{
//I think I've to put something here
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
jsonObjectRequest.setShouldCache(false);
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.getCache().clear();
requestQueue.add(jsonObjectRequest);
}
You may replace new Handler(Looper.getMainLooper()).post(runnable) with activity.runOnUiThread(runnable)

Related

android api json Parser

hi i have an app shows the online streamers from Twitch.tv and the data comes from request i send but i cant parse them this is my code
public ArrayList<Twitch> ParseTwitch(JSONArray object, Context context){
ArrayList<Twitch> chanels = new ArrayList<>();
try {
for (int i = 0;i<object.length();i++){
JSONObject streamObjct = object.getJSONObject(i);
JSONObject chanel = streamObjct.getJSONObject("channel");
JSONObject url= streamObjct.getJSONObject("preview");
final Twitch twitch = new Twitch();
twitch.setName(chanel.getString(CHANEL_NAME));
twitch.setStatus(chanel.getString(CHANEL_STATUS));
twitch.setGame(streamObjct.getString(GAME));
twitch.setLanguage(chanel.getString(BROADCASTER_LANGUAGE));
twitch.setViewrs(streamObjct.getInt(VIEWRS));
String imageUrl = url.getString("medium");
ImageRequest request =new ImageRequest(imageUrl, new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap response) {
twitch.setLogo(response);
}
}, 0, 0, null, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue quew = Volley.newRequestQueue(context);
quew.add(request);
chanels.add(twitch);
}
return chanels;
}catch (JSONException e){
e.printStackTrace();
}
return chanels;
}
and this my request
https://api.twitch.tv/kraken/search/streams?query=poker&client_id=gxdzx71jhztgyypn4kjemm1htovv1o
at least can anyone tell me should i work with sqlite Database or not?
where i called TwitchParcer
private void prepareData(String url, final ListView mListView) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray stream = response.getJSONArray("streams");
TwitchApiParser parser = new TwitchApiParser();
ArrayList items= parser.ParseTwitch(stream);
TwitchAdapter adapter = new TwitchAdapter(getContext(),
R.layout.activity_last_news_fragment,items);
mListView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "Ridi Bro", Toast.LENGTH_SHORT).show();
}
});
RequestQueue quew = Volley.newRequestQueue(getActivity().getApplicationContext());
quew.add(request);
}
and this is new Error
Process: app.mma.introsliderproject, PID: 11542
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at app.mma.PokerInfo.twitch.TwitchAdapter.getView(TwitchAdapter.java:39)
i solve the problem this is the complete code
public class TwitchFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.twitch_main, container, false);
String url="http://192.168.1.101/mySite/Flowers/flowers2.json";
ListView mListView = (ListView) view.findViewById(R.id.twitch_last);
prepareData(url,mListView);
return view;
}
private void prepareData(String url, final ListView mListView) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray stream = response.getJSONArray("streams");
TwitchApiParser parser = new TwitchApiParser();
ArrayList items= parser.ParseTwitch(stream,getActivity().getApplicationContext());
TwitchAdapter adapter = new TwitchAdapter(getContext(),
R.layout.twitch,items);
mListView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "Ridi Bro", Toast.LENGTH_SHORT).show();
}
});
RequestQueue quew = Volley.newRequestQueue(getActivity().getApplicationContext());
quew.add(request);
}
and the parser
public class TwitchApiParser {
private final String CHANEL_NAME="display_name";
private final String GAME="game";
private final String CHANEL_STATUS = "status";
private final String BROADCASTER_LANGUAGE = "broadcaster_language";
private final String VIEWRS = "viewers";
public ArrayList<Twitch> ParseTwitch(JSONArray object, Context context){
ArrayList<Twitch> chanels = new ArrayList<>();
try {
for (int i = 0;i<object.length();i++){
JSONObject streamObjct = object.getJSONObject(i);
JSONObject chanel = streamObjct.getJSONObject("channel");
JSONObject url= streamObjct.getJSONObject("preview");
final Twitch twitch = new Twitch();
twitch.setName(chanel.getString(CHANEL_NAME));
twitch.setStatus(chanel.getString(CHANEL_STATUS));
twitch.setGame(streamObjct.getString(GAME));
twitch.setLanguage(chanel.getString(BROADCASTER_LANGUAGE));
twitch.setViewrs(streamObjct.getInt(VIEWRS));
String imageUrl = url.getString("medium");
ImageRequest request =new ImageRequest(imageUrl, new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap response) {
twitch.setLogo(response);
}
}, 0, 0, null, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue quew = Volley.newRequestQueue(context);
quew.add(request);
chanels.add(twitch);
}
return chanels;
}catch (JSONException e){
e.printStackTrace();
}
return chanels;
}

Android Session management with Spring

I need to maintain a session for below REST API call from Android app. I'm able to call these API using volley, But the session is not being maintained.
I first call validateUser API to validate the user and store his email in session.
Then I need to call getDashboardDetails to fetch user details, But email in session object is null
// Spring REST code
#RequestMapping(value = "/validateUser", method = RequestMethod.POST)
#ResponseBody
public ResponseEntity<UserVO> validateUser(#RequestBody UserVO userVO, HttpSession session, HttpServletResponse response) {
HttpStatus httpStatus = HttpStatus.OK;
validatedUserVo = userService.getUserDetails(userVO);
session.setAttribute("email", validatedUserVo.getEmail());
return new ResponseEntity<UserVO>(validatedUserVo, httpStatus);
}
#RequestMapping(value = "/getDashboardDetails", method = RequestMethod.GET)
public ResponseEntity<List<DashBoardVO>> getDashboardDetails(HttpSession session) {
List<DashBoardVO> dashBoardVOList = null;
HttpStatus httpStatus = HttpStatus.OK;
String email = (String)session.getAttribute("email");
if(email!=null){
dashBoardVOList = dashboardService.getDashboardDetails(email);
}
else{
httpStatus = HttpStatus.BAD_REQUEST;
}
return new ResponseEntity<List<DashBoardVO>> (dashBoardVOList, httpStatus);
}
// validateUser call in LoginActivity
json.put("email",username1.getText().toString());
json.put("password",password1.getText().toString());
JsonObjectRequest login_data = new
JsonObjectRequest(Request.Method.POST, url, json,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
StringBuffer s = null;
tv.setText(response.toString());
edit.putBoolean("login_success",true);
edit.commit();
Intent i = new Intent(LoginActivity.this,DashboardActivity.class);
try {
i.putExtra("name",response.getString("name"));
i.putExtra("role",response.getString("role"));
} catch (JSONException e) {
e.printStackTrace();
}
startActivity(i);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
tv.setText(error.toString());
}
});
RequestQueue rq = Volley.newRequestQueue(this);
rq.add(login_data)
//sharedPreferences in LoginActivity
boolean b = sharedPreferences.getBoolean("login_success",false);
if(b){
Intent i = new
Intent(LoginActivity.this,DashboardActivity.class);
startActivity(i);
}
// getDashboardDetails call in DashboardActivity
JsonArrayRequest j1 = new JsonArrayRequest(Request.Method.GET, url,
null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONObject temp = response.getJSONObject(1);
tv.setText(temp.getString("id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
tv.setText(error.toString());
}
});
RequestQueue rq = Volley.newRequestQueue(this);
rq.add(j1);
How do I use/maintain session between different api calls? in android app

How to handle if response from server is null in android?

I am sending server request to handle response and error i have implemented interface. I just want to know how to handle if "mResultCallBack ==null" without editing condition if(mResultCallBack!=null). code are as follow:-
public Context mContext;
private IResult mResultCallBack;
public CServerRequest(IResult mResultCallBack, Context context) {
this.mContext = context;
this.mResultCallBack = mResultCallBack;
}
public void postWalletRequest(final String requestType, String url, JSONObject jsonObject) {
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mResultCallBack.notifySuccess(requestType, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mResultCallBack.notifyError(requestType, error);
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObjectRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
}
and code for interface
public void notifySuccess(String requestType,JSONObject response);
public void notifyError(String requestType,VolleyError error);
AsyncTask.execute(new Runnable() {
#Override
public void run() {
if (loginSessionManager.isLogin()){
cServerRequest = new CServerRequest(mResultcallBack,mContext);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.put(CRequestKey.AGENT_CODE, m_szMobileNumber.trim());// sending mobile no.(static right know becuse of ser side data on other is null
jsonObject.put(CRequestKey.PIN, m_szEncryptedPassword.trim());// same here as said above
Log.e(TAG,"Request::"+jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
final String s_szWalletURL = CAPIStorage.IREWARDS_URL + CAPIStorage.WALLET_BALANCE_URL;
cServerRequest.postWalletRequest("POST",s_szWalletURL,jsonObject);
}else {
Log.e(TAG,"Not loggedin");
}
}
});
public Context mContext;
private IResult mResultCallBack;
public CServerRequest(IResult mResultCallBack, Context context) {
this.mContext = context;
this.mResultCallBack = mResultCallBack;
}
public void postWalletRequest(final String requestType, String url, JSONObject jsonObject) {
try {
if(jsonObject.getJSONArray.length() == 0) {
System.out.println("JSONArray is null");
}
else{
System.out.println("JSONArray is not null");
//parse your string here
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
mResultCallBack.notifySuccess(requestType, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mResultCallBack.notifyError(requestType, error);
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObjectRequest);
}
} catch (Exception e) {
e.printStackTrace();
}
}

Volley Post Request in Android

I am using Volley to post some data in a server.
private void checkLeague(final String username, final String password) {
String tag_json_obj = "json_obj_req";
final HashMap<String, String> postParams = new HashMap<String, String>();
postParams.put("username", username);
postParams.put("password", password);
Response.Listener<JSONObject> listener;
Response.ErrorListener errorListener;
final JSONObject jsonObject = new JSONObject(postParams);
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(AppConfig.URL_CHECK_LEAGUE, jsonObject,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (response.getString("status").equals("fail")) {
checkLeader(username,password);
} else if (response.getString("status").equals("success")) {
deleteSharedPreferences();
text.setText("");
//timer.setText("League starts in:");
leagueCreation.setVisibility(View.GONE);
leagueInvitation.setVisibility(View.VISIBLE);
listView.setVisibility(View.VISIBLE);
readCheckLeagueSuccessfullData(response);
compareLeader();
dateFormatter();
setLeagueName();
getLeagueMembers(leagueId, username, password);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Bundle b = new Bundle();
b.putString("team_name", teamName);
b.putString("team_leader", teamLeader);
Intent intent = new Intent(League.this, UserDetails.class);
intent.putExtra("players_bundle", b);
startActivity(intent);
}
});
leagueInvitation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(League.this, LeagueInvitation.class);
i.putExtra("leagueId", leagueId);
i.putExtra("leagueName", leagueNameDb);
startActivity(i);
}
});
CounterClass counter = new CounterClass(leagueStartDiff, 1000);
counterTwoWeeks = new CounterClass1(leagueTwoWeeks, 1000);
counter.start();
}
} catch (JSONException e) {
Log.e("TAG", e.toString());
}
//pDialog.dismiss();
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d("TAG", "Error: " + error.getMessage());
//pDialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq,
tag_json_obj);
VolleySingleton.getInstance(getApplicationContext()).
addToRequestQueue(jsonObjRequest);
}
I put a breakpoint in this line
final JsonObjectRequest jsonObjReq = ...
to check if the data username,password in this case are basically going to the server. The problem is that I get this response which I don't like it very much.
[ ] http://.../..._..._check.php 0x8237d9fb NORMAL null
I should had got something like this from the debugger for the post request.
{
"username":"...",
"password":"..."
}
But I don't know why I get the null thing in my json request! It was working fine before. Maybe the link is broken?
Thank you.

Android Volley multiple Requests

I try to execute a new volley request in the current volley request, but when the new request is called it don't step into the onrespond method.
The new request should be executed before the first ends. (Last in, first out)
How can I execute the new request succesfully ?
private void makeJsonObjectRequest() {
ac = new AppController();
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("test", response.toString());
try {
// Parsing json object response
// response will be a json object
JSONArray name = response.getJSONArray("data");
for (int i = 0; i < name.length(); i++) {
JSONObject post = (JSONObject) name.getJSONObject(i);
try {
objectid = post.getString("object_id");
newRequest(objectid);
}
catch (Exception e) {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("test", "Error: " + error.getMessage());
}
});
// Adding request to request queue
ac.getInstance().addToRequestQueue(jsonObjReq);
}
Try it Work 100%
public class Utility {
String result = "";
String tag_string_req = "string_raq";
private Activity activity;
Context context;
private LinearLayout mLinear;
private ProgressDialog pDialog;
public Utility(Context context) {
this.context = context;
}
public String getString(String url, final VolleyCallback callback) {
showpDialog();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
result = response;
hideDialog();
callback.onSuccess(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
callback.onRequestError(error);
hideDialog();
/*LayoutInflater inflater = ((Activity) context).getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, null);
((Activity) context).setContentView(layout);*/
}
});
VolleySingleton.getInstance().addToRequestQueue(stringRequest, tag_string_req);
stringRequest.setRetryPolicy(
new DefaultRetryPolicy(1 * 1000, 1, 1.0f));
return result;
}
public interface VolleyCallback {
void onSuccess(String result);
void onRequestError(VolleyError errorMessage);
//void onJsonInvoke(String url, final VolleyCallback callback);
}
public boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
private void showpDialog() {
onProgress();
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
public void onProgress() {
pDialog = new ProgressDialog(context);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
}
}
Call Fragment
Utility utility = new Utility(getContext());
utility.getString(urls, new Utility.VolleyCallback() {
#Override
public void onSuccess(String result) {
try {
JSONObject toplinks = new JSONObject(result);
JSONObject data = toplinks.getJSONObject("toplinks");
M.i("============LS", "" + data);
} catch (JSONException e) {
e.printStackTrace();
}
finally {
}
}
#Override
public void onRequestError(VolleyError errorMessage) {
errorJson.setVisibility(View.VISIBLE);
String msg = VolleyException.getErrorMessageFromVolleyError(errorMessage);
errorJson.setText(msg);
}
});
all this about
Request Prioritization
Networking calls is real time operation so let consider we have multi request like in your case , Volley processes the requests from higher priorities to lower priorities , in first-in-first-out order.
So all you need change priority (set Priority.HIGH) to request you want process first.
here is a piece of code
public class CustomPriorityRequest extends JsonObjectRequest {
// default value
Priority mPriority = Priority.HIGH;
public CustomPriorityRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
}
public CustomPriorityRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(url, jsonRequest, listener, errorListener);
}
#Override
public Priority getPriority() {
return mPriority;
}
public void setPriority(Priority p){
mPriority = p;
}
}
As others mentioned one way is to put a high priority on the request.
Another option as it seems you have the first request depending on the inner one wrapped in the try-catch block which seems to me you want to achieve a synchronous/blocking behavior for this specific case. then you can use RequestFuture :
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest request = newRequest(objectid, future);
requestQueue.add(request);
String result = future.get();

Categories

Resources