Want to move GET method inside POST, Volley - java

I want to move GET method inside (if) that located inside onResponse of POST request without calling URL again because once the user post edittext php file will echo json result that will show up inside listview in activity so if call URL again in other method nothing will show up, how can I do that please?
public class supportActivity extends AppCompatActivity implements View.OnClickListener{
private EditText ticketsupport;
private Button button;
private List<supportContent> con = new ArrayList<supportContent>();
private ListView supportlist;
private supportAdapter adapter;
private String ticketinput;
private String url = "http://10.0.3.2/aalm/getticket.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_support);
ticketsupport = (EditText)findViewById(R.id.insertticketnumber);
supportlist = (ListView)findViewById(R.id.supportlistview);
adapter = new supportAdapter(this, con);
supportlist.setAdapter(adapter);
button = (Button)findViewById(R.id.buttonsupprt);
button.setOnClickListener(this);
}
private void inquiry() {
ticketinput = ticketsupport.getText().toString().trim();
StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("responseticket")) {
showTicket();
} else {
Toast.makeText(supportActivity.this, "Check the number please", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(supportActivity.this, "something wrong" , Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String,String> getParams() throws AuthFailureError{
Map<String,String> map = new HashMap<String,String>();
map.put("ticknumber", ticketinput);
return map;
}
};
RequestQueue requestQueue1 = Volley.newRequestQueue(getApplicationContext());
requestQueue1.add(stringRequest1);
}
private void showTicket(){
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("responseticket");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject ticket = jsonArray.getJSONObject(i);
supportContent support = new supportContent();
support.setTicketnumber(ticket.getString("ticketnumber"));
support.setSubject(ticket.getString("subject"));
support.setResponse(ticket.getString("response"));
con.add(support);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", "Volley");
}
}
);
requestQueue2.add(jsonObjectRequest);
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public void onClick(View view){
inquiry();
}
}

Related

Volley CallBack Method not giving the response?

I'm making a app GuessTheCelebrity. So the problem is I need celebrity names and their imageUrls outside the response method so i use callback method but its not working. First i fetch data in CelebDataService class and then in Main activity i used Matcher and Pattern to get the desired response. I use Singleton Class for adding requests to requestQueue.
Here's my code:
Volley Request Class
public class CelebDataService {
Context context;
String response;
String url = "https://www.imdb.com/list/ls052283250/";
public CelebDataService(Context context) {
this.context = context;
}
public interface CallBack {
void onResponse(String response);
void onError(String error);
}
public interface MatchListAsyncResponse {
void processFinish(List<String> list);
}
public void getResponse(CallBack callBack)
{
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response);
callBack.onResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
callBack.onError(error.getMessage());
}
});
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
}
}
Main Activity Class
public class MainActivity extends AppCompatActivity {
ArrayList<String> urls = new ArrayList<>();
ArrayList<String> names = new ArrayList<>();
int cs = 0;
TextView textView;
ImageView imageView;
ImageRequest imageRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main)
textView = findViewById(R.id.textView);
imageView = findViewById(R.id.imageView);
CelebDataService celebDataService = new CelebDataService(MainActivity.this);
celebDataService.getResponse(new CelebDataService.CallBack() {
#Override
public void onResponse(String response) {
Log.i("hello", "onResponse: " + response);
String[] result = response.split("<div id=\"sidebar\">");
Pattern p = Pattern.compile("src=\"(.*?)\"");
Matcher m = p.matcher(result[0]);
while (m.find())
{
urls.add(m.group(1));
}
p = Pattern.compile("alt=\"(.*?)\"");
m = p.matcher(result[0]);
while (m.find())
{
names.add(m.group(1));
}
}
#Override
public void onError(String error) {
textView.setText(error);
}
});
Random random = new Random();
cs = random.nextInt(urls.size());
imageRequest = new ImageRequest(urls.get(cs), new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap response) {
imageView.setImageBitmap(response);
requestQueue.stop();
}
}, 0, 0, ImageView.ScaleType.CENTER_CROP,null, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textView.setText("Error");
error.printStackTrace();
}
});
MySingleton.getInstance(context).addToRequestQueue(imageRequest);
}
}
The app got crash on start because urls arraylist is empty.

Cannot fetch data from room database to Spinner

This app is to fetch data from api.github.com/users and reflect on spinner
I am getting data in logs on Splash.java but unable to reflect data on Home.java
MyAppDatabase.java
#Database(entities = {Users.class}, version = 1, exportSchema = false)
public abstract class MyAppDatabase extends RoomDatabase {
public abstract MyDao myDao();
}
MyDao.java
#Dao
public interface MyDao {
#Insert(onConflict = OnConflictStrategy.REPLACE)
void addUsers(Users users);
#Query("SELECT * FROM Users")
List<Users> getUsers();
#Query("SELECT node_id FROM Users")
List<String> getNodeId();
}
getData() on Splash.java
public class Splash extends AppCompatActivity {
MyAppDatabase myAppDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
myAppDatabase = Room.databaseBuilder(getApplicationContext(), MyAppDatabase.class, "MyDao").allowMainThreadQueries().build();
//get data from webservice and store locally
getData();
}
}, 500);
}
private void getData() {
//Creating a string request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("response", response.toString());
response.length();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Users users = new Users();
//Set fields in Users object.
users.setLogin(jsonObject.getString(Config.TAG_Login));
users.setId(jsonObject.getString(Config.TAG_Id));
users.setNode_id(jsonObject.getString(Config.TAG_Node));
users.setAvatar_url(jsonObject.getString(Config.TAG_Avatar));
users.setGravatar_id(jsonObject.getString(Config.TAG_Gravatar_id));
users.setUrl(jsonObject.getString(Config.TAG_url));
users.setHtml_url(jsonObject.getString(Config.TAG_htmi_url));
users.setFollowers_url(jsonObject.getString(Config.TAG_Followers_url));
users.setFollowing_url(jsonObject.getString(Config.TAG_Following_url));
users.setGists_url(jsonObject.getString(Config.TAG_Gists_url));
users.setStarred_url(jsonObject.getString(Config.TAG_Starred_url));
users.setSubscriptions_url(jsonObject.getString(Config.TAG_Subscriptions_url));
users.setOrganizations_url(jsonObject.getString(Config.TAG_Organizations_url));
users.setRepos_url(jsonObject.getString(Config.TAG_Repos_url));
users.setReceived_events_url(jsonObject.getString(Config.TAG_Received_events_url));
users.setType(jsonObject.getString(Config.TAG_Type));
users.setSite_admin(jsonObject.getString(Config.TAG_Site_admin));
users.setEvents_url(jsonObject.getString(Config.TAG_events_url));
myAppDatabase.myDao().addUsers(users);
} catch (JSONException e) {
e.printStackTrace();
}
}
Intent intent = new Intent(Splash.this, Home.class);
// intent.putExtra("remember", "true");
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(
10000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonArrayRequest);
}
}
putData() on Home.java
public class Home extends AppCompatActivity {
MyAppDatabase myAppDatabase;
//To add into spinner
private ArrayList<String> userType;
//List of users from Db
List<Users> users;
private Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
userType = new ArrayList<>();
spinner = findViewById(R.id.sp_user_type);
myAppDatabase = Room.databaseBuilder(getApplicationContext(), MyAppDatabase.class,"UsersDb").allowMainThreadQueries().build();
//get data from Db and put into arrayList for spinner
putData();
}
private void putData() {
users =myAppDatabase.myDao().getUsers();
userType.add("Select UserType"); //Dummy addition
for(int i = 0; i < users.size(); i++){
userType.add(users.get(i).getType());
Log.e("DistNames",users.get(i).getType());
}
users.size();
spinner.setAdapter(new ArrayAdapter<>(Home.this, android.R.layout.simple_spinner_dropdown_item, userType));
}
}
Because you are starting activity in the loop itself, which should be actually outside the loop.
Actually, the mistake that you are doing is it will launch Home activity in the first iteration itself and so you are not getting all the data from the API response. To solve this, let the loop iterates through each entry and add into the database, and start the activity when it completes and so outside the loop.
Wrong:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("response", response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Users users = new Users();
//Set fields in Users object.
users.setLogin(jsonObject.getString(Config.TAG_Login));
users.setId(jsonObject.getString(Config.TAG_Id));
users.setNode_id(jsonObject.getString(Config.TAG_Node));
users.setAvatar_url(jsonObject.getString(Config.TAG_Avatar));
users.setGravatar_id(jsonObject.getString(Config.TAG_Gravatar_id));
users.setUrl(jsonObject.getString(Config.TAG_url));
users.setHtml_url(jsonObject.getString(Config.TAG_htmi_url));
users.setFollowers_url(jsonObject.getString(Config.TAG_Followers_url));
users.setFollowing_url(jsonObject.getString(Config.TAG_Following_url));
users.setGists_url(jsonObject.getString(Config.TAG_Gists_url));
users.setStarred_url(jsonObject.getString(Config.TAG_Starred_url));
users.setSubscriptions_url(jsonObject.getString(Config.TAG_Subscriptions_url));
users.setOrganizations_url(jsonObject.getString(Config.TAG_Organizations_url));
users.setRepos_url(jsonObject.getString(Config.TAG_Repos_url));
users.setReceived_events_url(jsonObject.getString(Config.TAG_Received_events_url));
users.setType(jsonObject.getString(Config.TAG_Type));
users.setSite_admin(jsonObject.getString(Config.TAG_Site_admin));
users.setEvents_url(jsonObject.getString(Config.TAG_events_url));
myAppDatabase.myDao().addUsers(users);
Intent intent = new Intent(Splash.this, Home.class);
// intent.putExtra("remember", "true");
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
Correct:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("response", response.toString());
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
Users users = new Users();
//Set fields in Users object.
users.setLogin(jsonObject.getString(Config.TAG_Login));
users.setId(jsonObject.getString(Config.TAG_Id));
users.setNode_id(jsonObject.getString(Config.TAG_Node));
users.setAvatar_url(jsonObject.getString(Config.TAG_Avatar));
users.setGravatar_id(jsonObject.getString(Config.TAG_Gravatar_id));
users.setUrl(jsonObject.getString(Config.TAG_url));
users.setHtml_url(jsonObject.getString(Config.TAG_htmi_url));
users.setFollowers_url(jsonObject.getString(Config.TAG_Followers_url));
users.setFollowing_url(jsonObject.getString(Config.TAG_Following_url));
users.setGists_url(jsonObject.getString(Config.TAG_Gists_url));
users.setStarred_url(jsonObject.getString(Config.TAG_Starred_url));
users.setSubscriptions_url(jsonObject.getString(Config.TAG_Subscriptions_url));
users.setOrganizations_url(jsonObject.getString(Config.TAG_Organizations_url));
users.setRepos_url(jsonObject.getString(Config.TAG_Repos_url));
users.setReceived_events_url(jsonObject.getString(Config.TAG_Received_events_url));
users.setType(jsonObject.getString(Config.TAG_Type));
users.setSite_admin(jsonObject.getString(Config.TAG_Site_admin));
users.setEvents_url(jsonObject.getString(Config.TAG_events_url));
myAppDatabase.myDao().addUsers(users);
} catch (JSONException e) {
e.printStackTrace();
}
}
Intent intent = new Intent(Splash.this, Home.class);
// intent.putExtra("remember", "true");
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});

How to create a single volley webservice class to use across the android app?

My android application uses multiple network calls in a single activity and i have several of these activities where i have to use both post and get requests. I want to create a single "VolleyWebservice" class and call the same in multiple activities instead of writing the complete volley code. I am relatively new to android development and i don't understand where i am going wrong.
public class VolleyWebService {
public JSONObject result;
public JSONObject getResponse(String url, Context mContext) {
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
result = response;
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
mQueue.add(request);
return result;
}
}
The method in My activity where i am calling this class
private void callFunctionGetDist() {
ProgressDialog progressDialog;
progressDialog = ProgressDialog.show(recorddata.this, "", "Please Wait...", true);
JSONObject response = new VolleyWebService().getResponse(urlConfigClass.GET_DISTRICT, this);
try {
if(response.toString().contains("Status:Success,Details")){
arrDistName.clear();
arrDistCode.clear();
arrDistName.add("Select District Name");
arrDistCode.add("Select District Code");
JSONArray jsonArray = response.getJSONArray("Status:Success,Details");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jobJ = jsonArray.getJSONObject(i);
String scheName = jobJ.getString("post");
JSONObject jobJDist = new JSONObject(scheName);
String distname = jobJDist.getString("District");
String distcode = jobJDist.getString("DistrictCode");
arrDistName.add(distname);
arrDistCode.add(distcode);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(recorddata.this,
R.layout.custom_textview_to_spinner, arrDistName);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
district.setAdapter(dataAdapter);
progressDialog.dismiss();
}else{
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Response is null or empty", Toast.LENGTH_LONG).show();
}
} catch (Exception volleyError) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
}
I tried creating the same class but i am not able to get the response to other activities. Although i am getting the correct response in the Volley jsonbject response, the response return null in other activities.
I want to have the result object return the response in my recorddata activity
This is what i have tried so far, no luck though!
public void postResponse (String url, Context mContext, final VolleyResponseListener listener) {
try {
String encodedUrl = url.replace(" ", "%20") + "";
if (encodedUrl.contains("("))
encodedUrl = encodedUrl.replace("(", "%28");
if (encodedUrl.contains(")"))
encodedUrl = encodedUrl.replace(")", "%29");
encodedUrl = encodedUrl.replace(" ", "%20");
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POst, encodedUrl, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
listener.onSuccess(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error);
}
}) {
#Override
protected Map<String, String> getParams() {
return new HashMap<>();
}
};
mQueue.add(request);
} catch (Exception e) {
e.printStackTrace();
}
}
For the sake of achieving your goal, (without taking in to consideration architecture and coding principles), you can pass a callback:
public class VolleyWebService {
public interface VolleyResponseListener {
void onSuccess(JSONObject response);
void onError(VolleyError error);
}
public JSONObject result;
public JSONObject getResponse(String url, Context mContext, VolleyResponseListener listener) {
RequestQueue mQueue = Volley.newRequestQueue(mContext);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e(TAG, "Anshuman" + response.toString());
listener.onSuccess(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onError(error);
}
});
mQueue.add(request);
return result;
}
}
To use it:
volleyWebService.getResponse("your url", context, new VolleyResponseListener() {
#Override
void onSuccess(JSONObject response) {
//do what you want on success
}
#Override
void onError(VolleyError error) {
//do what you want on error
}
});

Show function data without blinking with Volley in Android Studio

Recently I am working on Android project with Volley for registration and for further operation, I can make function for insertion and other one is for retrieval data. When insert button click 'Insert' function called and data has been inserted to database through volley, and at the same time retrieval function also called. But when USER clicked the button and function called then data showed(database inserted data) with blinking effect, look like loading.
I want to get rid of that effect. I want to show data smoothly without any blinking effect. I do searching but can not find any solution. Please suggest me solution I'am newbie so kindly short and efficient required.
package com.darkcoderz.parsejson;
public class MainActivity extends AppCompatActivity {
private Context mContext;
private Activity mActivity;
//private CoordinatorLayout mCLayout;
private TextView mTextView;
private String mJSONURLString = "http://192.168.10.4/volley/api.php";
String url = "http://192.168.10.4/volley/register.php";
private EditText sms;
private Button sendsms;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the application context
//mContext = getApplicationContext();
//mActivity = MainActivity.this;
// Get the widget reference from XML layout
//mCLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
mTextView = (TextView) findViewById(R.id.tv);
sms = (EditText) findViewById(R.id.sms);
sendsms = (Button) findViewById(R.id.sendsms);
final Handler firesms = new Handler();
firesms.post(new Runnable() {
#Override
public void run() {
getdata();
firesms.postDelayed(this, 100);
}
});
sendsms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
reg();
}
});
getdata();
}
// insert
public void reg()
{
final String msg = sms.getText().toString();
StringRequest stringreq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success"))
{
Toast.makeText(MainActivity.this, "Registration Successfull!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Username Already Exist!", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Great Error "+error.toString(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("sms",msg);
return params;
}
};
RequestQueue reqest = Volley.newRequestQueue(MainActivity.this);
reqest.add(stringreq);
}
private void getdata() {
// Empty the TextView
mTextView.setText("");
// Initialize a new RequestQueue instance
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
// Initialize a new JsonArrayRequest instance
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, mJSONURLString, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
// Do something with response
//mTextView.setText(response.toString());
// Process the JSON
try{
// Loop through the array elements
for(int i=0;i<response.length();i++){
// Get current json object
JSONObject student = response.getJSONObject(i);
// Get the current student (json object) data
// String firstName = student.getString("fname");
// String lastName = student.getString("lname");
String age = student.getString("email");
// Display the formatted json data in text view
mTextView.append("SMS : " + age);
mTextView.append("\n\n");
}
}catch (JSONException e){
e.printStackTrace();
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
// Do something when error occurred
Toast.makeText(mContext, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
}
);
// Add JsonArrayRequest to the RequestQueue
requestQueue.add(jsonArrayRequest);
}
}
private void getdata() {
// Empty the TextView
mTextView.setText("");
// Initialize a new RequestQueue instance
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
// Initialize a new JsonArrayRequest instance
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, mJSONURLString, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//before parsing check your response is in JSONArray Format or JSONObject format
// Process the JSON
try{
}catch (JSONException e){
e.printStackTrace();
//print here to know JSONException if exists
Toast.makeText(mContext, "Exception"+e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
// Do something when error occurred
Toast.makeText(mContext, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
}
);
// Add JsonArrayRequest to the RequestQueue
requestQueue.add(jsonArrayRequest);
}

Volley Request from another class not activity

I am making a volley String request from a separate class and return the result to main activity
public class FetchFlages {
Context context;
String
placeurl="https://maps.googleapis.com/maps/api/place/textsearch/json
query=";
String myapi = "&key=AIzaSyBuI5wpF733jBS8s7HzjybE1rYAp1hA5tA";
RequestQueue requestQueue;
String abc=null;
public FetchFlages(Context context) {
this.context = context;
requestQueue = Volley.newRequestQueue(context);
}
public String getPhotoReference(){
String url = placeurl +"China"+myapi;
StringRequest objectRequest = new StringRequest(Request.Method.GET, url,
new Listener<String>() {
#Override
public void onResponse(String response) {
abc = response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volly Error",error.toString());
}
});
requestQueue.add(objectRequest);
return abc;
}
}
and in main Class
FetchFlages fetchFlages = new FetchFlages(this);
flag = fetchFlages.getPhotoReference();
String g = flag;
But i can't get any value from that...the value of abc always return null
and
When i run debugger then debugger not comes neither on Volley on Response Listener method and nor on Error Listener Method...Please help me..
This is because as soon as getPhotoReference() is called, its returning the value. The network call is still running. Create a listener and call the listener method on onRespose
Sample pseudo code:
CustomListener.java
public interface CustomListener{
void onVolleyResponse(String response);
}
FetchFlages.java
public class FetchFlages {
Context context;
String placeurl="https://maps.googleapis.com/maps/api/place/textsearch/jsonquery=";
String myapi = "&key=AIzaSyBuI5wpF733jBS8s7HzjybE1rYAp1hA5tA";
RequestQueue requestQueue;
CustomListener listener = null; //Your listener instance
public FetchFlages(Context context, CustomListener listener) {
this.context = context;
this.listener = listener;
requestQueue = Volley.newRequestQueue(context);
}
public void getPhotoReference(){
String url = placeurl +"China"+myapi;
StringRequest objectRequest = new StringRequest(Request.Method.GET, url,
new Listener<String>() {
#Override
public void onResponse(String response) {
listener.onVolleyResponse(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volly Error",error.toString());
}
});
requestQueue.add(objectRequest);
}
}
Now in your main activity,
FetchFlages fetchFlages = new FetchFlages(this, new CustomListener() {
#Override
public void onVolleyResponse(String response) {
//response is your response
}
});
fetchFlages.getPhotoReference()
Use interface Method like:
public class FetchFlages {
Context context;
String placeurl = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=";
String myapi = "&key=AIzaSyBuI5wpF733jBS8s7HzjybE1rYAp1hA5tA";
RequestQueue requestQueue;
IResult result;
public FetchFlages(Context context, IResult result) {
this.context = context;
requestQueue = Volley.newRequestQueue(context);
this.result = result;
}
public void getPhotoReference() {
String url = placeurl + "China" + myapi;
StringRequest objectRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
result.notifySuccess(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volly Error", error.toString());
result.notifyError(error);
}
});
requestQueue.add(objectRequest);
}
public interface IResult {
public void notifySuccess(String response);
public void notifyError(VolleyError error);
}
and call it:
FetchFlages fetchFlages = new FetchFlages(this, new IResult() {
#Override
public void notifySuccess(String response) {
//response here
Log.e("responce",response);
}
#Override
public void notifyError(VolleyError error) {
//error here
}
});
fetchFlages.getPhotoReference()

Categories

Resources