I am new to android development and I need help. I want to set response result to resultDomain object and return . but it returns as initiated.
how to solve this ? thanks in advance.
public class NetworkController {
public static Context context = null;
static UserDomain resultDomain = null;
public UserDomain login( UserDomain userDomain, Context context) {
resultDomain = new UserDomain();
this.context = context;
JSONObject jsonObject = null;
try {
Gson gson = new Gson();
jsonObject = new JSONObject(gson.toJson(userDomain));
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectRequest =
new JsonObjectRequest(Request.Method.POST, Constant.SERVER_URL + Constant.LOGIN, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Gson gson = new Gson();
resultDomain = gson.fromJson(jsonObject.toString(), UserDomain.class);
Log.v("Here is Value ", resultDomain.getMessage());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
resultDomain = null;
}
});
requestQueue.add(jsonObjectRequest);
return resultDomain;
}
}
public class NetworkController {
public static Context context = null;
static UserDomain resultDomain = null;
public void login( UserDomain userDomain, Context context,Response.Listener<JSONObject> l1, Response.ErrorListener l2) {
resultDomain = new UserDomain();
this.context = context;
JSONObject jsonObject = null;
try {
Gson gson = new Gson();
jsonObject = new JSONObject(gson.toJson(userDomain));
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectRequest =
new JsonObjectRequest(Request.Method.POST, Constant.SERVER_URL + Constant.LOGIN, jsonObject,
l1,l2);
requestQueue.add(jsonObjectRequest);
}
NetworkController .login(user,context,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Gson gson = new Gson();
resultDomain = gson.fromJson(jsonObject.toString(), UserDomain.class);
Log.v("Here is Value ", resultDomain.getMessage());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
resultDomain = null;
}
});
or use Handler
Related
I want to send data to the server from my android app I searched about volley and wrote the code below but it does not work properly can you give me a hand to fix it?
I use a map for getting data then I extract the keys and put them to a string array:
keys=new String[data.size()];
data.keySet().toArray(keys);
after that i make my request like this:
for (int i=0;i<data.size();i++) {
requestJsonObject.put(keys[i], data.get(keys[i]));
}
Here is the complete code:
public class ApiPostData {
private static final String TAG = "PostData";
private String url;
private HashMap<String,String> data=new HashMap<>();
String[] keys;
public String getUrl() {
return url;
}
public ApiPostData setData(HashMap<String, String> data) {
this.data = data;
return this;
}
public ApiPostData setUrl(String url) {
this.url = url;
return this;
}
public void PostData(final OnSetSettingComplete onSetSettingComplete) {
JSONObject requestJsonObject = new JSONObject();
try {
keys=new String[data.size()];
data.keySet().toArray(keys);
for (int i=0;i < data.size(); i++) {
requestJsonObject.put(keys[i], data.get(keys[i]));
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, requestJsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
int success = response.getInt("statusCode");
onSetSettingComplete.onResponse(success);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
request.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Volley.newRequestQueue(G.context).add(request);
} catch (JSONException e) {
Log.e(TAG, "EpostData: " + e.toString());
}
}
public interface OnSetSettingComplete {
void onResponse(int success);
}
}
suggest using okhttp
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormEncodingBuilder().add("key1","value1").add("key1","value2").add("key3","valu e3").build();
Request request = new Request.Builder()
.url("URL HERE")
.addHeader("Some Headers Here", "Header Values Here")
.addHeader("Some Headers Here", "Header Values Here")
.post(body)
.build();
Response response = client.newCall(request).execute();
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;
}
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();
}
}
I am trying to get posts from server based on a parameter i.e. email address. How do I send parameters in JSONArrayRequest so that only those posts are retrieved which are matched with the given parameter? Here is my code:
JsonArrayRequest:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for(int i= 0; i<response.length(); i++){
try {
JSONObject object = response.getJSONObject(i);
Post post = new Post();
post.setContent(object.getString("Content"));
post.setDate(object.getString("PostDate"));
post.setTime(object.getString("PostTime"));
postArray.add(post);
PostList.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getmInstance().addToRequestQueue(jsonArrayRequest);
And this is the AppController.Java class:
public class AppController extends Application {
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
public static final String TAG = AppController.class.getSimpleName();
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getmInstance() {
return mInstance;
}
public RequestQueue getmRequestQueue()
{
if(mRequestQueue == null){
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getmImageLoader(){
getmRequestQueue();
if(mImageLoader == null){
mImageLoader = new ImageLoader(this.mRequestQueue, new BitmapCache());
}
return mImageLoader;
}
public <T> void addToRequestQueue(Request<T> request, String tag ){
request.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getmRequestQueue(). add(request);
}
public <T> void addToRequestQueue(Request<T> request ){
request.setTag(TAG);
getmRequestQueue(). add(request);
}
public void cancelPendingRequest(Object tag){
if(mRequestQueue != null){
mRequestQueue.cancelAll(tag);
}
}
}
void MakePostRequest() {
StringRequest postRequest = new StringRequest(Request.Method.POST, EndPoints.BASE_URL_ADS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
value1= jsonResponse.getString("Your ID1");
value2= jsonResponse.getString("Your ID2");
} catch (JSONException e) {
e.printStackTrace();
banner_id = null;
full_id = null;
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
value1= null;
value2= null;
}
}
) {
// here is params will add to your url using post method
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("app", getString(R.string.app_name));
//params.put("2ndParamName","valueoF2ndParam");
return params;
}
};
Volley.newRequestQueue(this).add(postRequest);
}
this post request is using this compile 'com.mcxiaoke.volley:library:1.0.19' volley version.
i am just adding app name as parameter.you can add more params.
Hello i am posting data to server in json format,
but it returns volley server error in error response`
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject jobj=new JSONObject();
try {
jobj.put("id",”123”);
jobj.put("session","new");
JSONArray array = null;
array = new JSONArray();
for (int i = 0;i<3;i++){
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","test");
jsonObject.put("content","test");
jsonObject.put("time"," 2016-04-07T11:44:22.407Z ");
array.put(jsonObject);
}
Log.e(" array "," arrr"+array.toString());
jobj.put("data",array);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("jsondata",jobj.toString());
JsonObjectRequest sr= new JsonObjectRequest(post_url, jobj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#OveRequestQueue queue = Volley.newRequestQueue(this);
JSONObject jobj=new JSONObject();
try {
jobj.put("id",”123”);
jobj.put("session","new");
JSONArray array = null;
array = new JSONArray();
for (int i = 0;i<3;i++){
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","test");
jsonObject.put("content","test");
jsonObject.put("time"," 2016-04-07T11:44:22.407Z ");
array.put(jsonObject);
}
Log.e(" array "," arrr"+array.toString());
jobj.put("data",array);
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("jsondata",jobj.toString());
JsonObjectRequest sr= new JsonObjectRequest(post_url, jobj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}rride
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/json");
return params;
}
};
queue.add(sr);`
Have a singleton which handles the request queue.
public class VolleySingleton {
// Singleton object...
private static VolleySingleton instance;
final private RequestQueue requestQueue;
private static ImageLoader imageLoader;
//Constructor...
private VolleySingleton(Context context) {
requestQueue = Volley.newRequestQueue(context);
imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruCache<>(100000000);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
// Singleton method...
public static VolleySingleton getInstance(Context context) {
if (instance == null) {
instance = new VolleySingleton(context);
}
return instance;
}
public RequestQueue getRequestQueue(Context context) {
if (requestQueue != null) {
return requestQueue;
} else {
getInstance(context);
return requestQueue;
}
}
private RequestQueue getRequestQueue() {
return requestQueue;
}
public static ImageLoader getImageLoader(Context context) {
if (imageLoader != null) {
return imageLoader;
} else {
getInstance(context);
return imageLoader;
}
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag("App");
getRequestQueue().add(req);
}
}
Then using the below method you can send the request.
public void postVolley(final Context context, String url, JSONObject jsonObject) {
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject responseJson) {
Log.e("success", "" + responseJson.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", "" + error);
}
}) {
/**
* Setting the content type
*/
#Override
public String getBodyContentType() {
return "application/json;charset=UTF-8";
}
};
VolleySingleton.getInstance(context).addToRequestQueue(jsonObjReq);
}
This works fine for me.