I'm trying is to display strings item_1 and item_2 in the text view 1 and text view 2 not displayed.
With the help of some experts I created the code below.
How can I display string item_1 and item_2 in the text view 1 and text view 2?
My Java code:
public class Prices extends AppCompatActivity {
TextView item_1 , item_2 ,a3 ,a4 ,a5 ,a6;
String url = "https://000000/app/almaraa/show.php";
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prices);
TextView item_1 = (TextView) findViewById(R.id.item_1);
TextView item_2 = (TextView) findViewById(R.id.item_2);
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
final Globalv globalv = (Globalv) getApplicationContext();
try {
JSONArray jsonArray = response.getJSONArray("allmess");
for (int i = 0; i < response.length(); i++) {
JSONObject respons = jsonArray.getJSONObject(i);
String id = respons.getString("id");
String item_1 = respons.getString("item_1");
String item_2 = respons.getString("item_2");
}
JSONObject respons2 = jsonArray.getJSONObject(0);
String id = respons2.getString("id");
globalv.setTotal_threads(Integer.parseInt(String.valueOf(id)));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
}
}
You have to use the method setText(Charsequence) and run the code on UI thread.
But before, you have to rename Strings item_1 and item_2 because your TextViews have the same names. Below the code with String values renamed:
//......... inside your jsonObjectRequest
//rename item_1 and item_2
String myItem_1 = respons.getString("item_1");
String myItem_2 = respons.getString("item_2");
Prices.this.runOnUiThread(new Runnable() {
public void run() {
item_1.setText(myItem_1);
item_2.setText(myItem_2);
}
});
Related
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
List<news_Objects> newsList = new ArrayList<>();
//url for News API
String url="https://newsapi.org/v2/everything?q=apple&from=2021-08-31&to=2021-08-31&sortBy=popularity&apiKey=ca3d6c89eff24db2a8ef78868f0af555";
//making json object request
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArr = response.getJSONArray("articles");
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject newsDetail = jsonArr.getJSONObject(i);
//class name news_Objects created
news_Objects news = new news_Objects();
String imtUrl = newsDetail.getString("urlToImage");
String title = newsDetail.getString("title");
String detail = newsDetail.getString("description");
String newsUrl = newsDetail.getString("url");
String content = newsDetail.getString("content");
news.setNewsImageUrl(imtUrl);
news.setNewsTitle(title);
news.setNewsDetail(detail);
news.setNewsUrl(newsUrl);
news.setContent(content);
newsList.add(news);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("fine", "Something Wrong"+error);
Toast.makeText(MainActivity.this, "Something Wrong "+error, Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
requestQueue.add(request);
}
}
Your API Key is Invalid please check your API key. Getting this response:
{"status":"error","code":"apiKeyInvalid","message":"Your API key is invalid or incorrect. Check your key, or go to https://newsapi.org to create a free API key."}
Maybe Your API key is not live, please check your API key status than again hit the api.
I'm try to using the class Fragment all working well, but when try to use variable get from te server, the fragment dont update the values.
This is my code:
public class report_fragment extends Fragment {
private BarChart barChart;
private ListView list;
public RequestQueue queue;
private Float ris;
String cu;
Button bSave;
private String userID,email,name,surname,age,privilegi;
TextView tExer, tRis;
String risultato, disciplina;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//just change the fragment_dashboard
//with the fragment you want to inflate
//like if the class is HomeFragment it should have R.layout.home_fragment
//if it is DashboardFragment it should have R.layout.fragment_dashboard
final View view = inflater.inflate(R.layout.fragment_report_fragment, container, false);
barChart = (BarChart) view.findViewById(R.id.bargraph);
tExer = (TextView) view.findViewById(R.id.tExerc);
tRis = (TextView) view.findViewById(R.id.tRis);
Bundle b = this.getArguments();
if (b != null) {
name = b.getString("name");
surname = b.getString("surname");
age = b.getString("age");
privilegi = b.getString("privilegi");
userID = b.getString("user");
}
Log.d("iduser2", "" + userID);
graficaDati(userID);
Last(userID);
tExer.setText(disciplina);
tRis.setText(risultato);
return view;
}
private void graficaDati(final String ID) {
//final TextView gTextView = (TextView) findViewById(R.id.graph);
// gTextView.append(" entrato in Data");
String url = "https://anto-mc.000webhostapp.com/atleti_statistiche2.php";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
final ArrayList<BarEntry> barEntries = new ArrayList<>();
ArrayList<String> theDates = new ArrayList<>();
JSONArray jsonArray = new JSONArray(response);
for (int i = 0 ; i < jsonArray.length(); i++) {
JSONObject out = jsonArray.getJSONObject(i);
String meteo = out.getString("meteo");
String dataa = out.getString("data");
String risultato = out.getString("risultato");
String score = out.getString("punteggio");
String tot= out.getString("tot");
Log.d("quiqui", ""+tot);
barEntries.add(new BarEntry(i, Float.parseFloat(tot)));
theDates.add(dataa+"-"+meteo);
}
BarDataSet set1;
set1 = new BarDataSet(barEntries, "Your score");
set1.setColors(new int[]{Color.parseColor("#ffffff")});
ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
dataSets.add(set1);
BarData data = new BarData(dataSets);
XAxis xAxis = barChart.getXAxis();
xAxis.setValueFormatter(new MyCustomXAxisValueFormatter(theDates));
xAxis.setGranularity(1f);
data.setValueTextSize(10f);
data.setBarWidth(0.9f);
barChart.setData(data);
barChart.getAxisRight().setEnabled(false);
barChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
barChart.invalidate();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("userID", ID);
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(getActivity());
queue.add(postRequest);
}
private void Last(final String ID) {
//final TextView gTextView = (TextView) findViewById(R.id.graph);
// gTextView.append(" entrato in Data");
Log.d("ciaoo","sei qui");
String url = "https://anto-mc.000webhostapp.com/last.php";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
final ArrayList<BarEntry> barEntries = new ArrayList<>();
ArrayList<String> theDates = new ArrayList<>();
Log.d("ciaoo","sei qui2");
JSONArray jsonArray = new JSONArray(response);
for (int i = 0 ; i < jsonArray.length(); i++) {
JSONObject out = jsonArray.getJSONObject(i);
Log.d("ciaoo","sei qui2" +""+out);
String meteo = out.getString("meteo");
disciplina = out.getString("disciplina");
risultato = out.getString("risultato");
String score = out.getString("punteggio");
String tot= out.getString("tot");
Log.d("queryris",""+disciplina + " "+ risultato);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("userID", ID);
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(getActivity());
queue.add(postRequest);
}
}
I received the variables "risultato and disciplina" and I see the correct value just after navigating in this fragment at the second time.
Frist time I see the null variable.
I tried to use a refresh of the fragment but it doesn't work.
The bargraph working correctly, but the setText doesn't work. I tried to do the same like a bargraph I have a failure.
Does someone have a suggestion? Thanks.
You need to set the text inside your onResponse function. The values are not available until the network call is finished. So the onResponse function inside your Last function should look like this.
private void Last(final String ID) {
//final TextView gTextView = (TextView) findViewById(R.id.graph);
// gTextView.append(" entrato in Data");
Log.d("ciaoo","sei qui");
String url = "https://anto-mc.000webhostapp.com/last.php";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
final ArrayList<BarEntry> barEntries = new ArrayList<>();
ArrayList<String> theDates = new ArrayList<>();
Log.d("ciaoo","sei qui2");
JSONArray jsonArray = new JSONArray(response);
for (int i = 0 ; i < jsonArray.length(); i++) {
JSONObject out = jsonArray.getJSONObject(i);
Log.d("ciaoo","sei qui2" +""+out);
String meteo = out.getString("meteo");
disciplina = out.getString("disciplina");
risultato = out.getString("risultato");
String score = out.getString("punteggio");
String tot= out.getString("tot");
Log.d("queryris",""+disciplina + " "+ risultato);
}
// Set the text here when it is available
tExer.setText(disciplina);
tRis.setText(risultato);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("userID", ID);
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(getActivity());
queue.add(postRequest);
}
The key idea is to set the text after the values are available after your API call is returning with some values in it. When you are calling a server API, it is being executed in another thread other than the UI thread. It does not halt its execution inside the onCreateView function as you are expecting I think.
Hope that helps.
The code is working fine when testing in emulator-Android 7.1, API 25 but when I test same code in Real Device-Android 4.4.4, API 19 spinner is not showing. And there is no error message even
Config.java
public class Config {
public static String mLocation ="http://towncitycards.com/webservice_action.php?action=";
//http://towncitycards.com/webservice_action.php?action=filter_location
public static final String DATA_URL = mLocation+"filter_location";
//Tags used in the JSON String
public static final String TAG_USERNAME = "name";
public static final String TAG_NAME = "slug";
public static final String TAG_COURSE = "name";
public static final String TAG_SESSION = "slug";
//JSON array name
public static final String JSON_ARRAY = "location";
}
DemoSpinner.java
public class DemoSpinner extends AppCompatActivity implements Spinner.OnItemSelectedListener{
//Declaring an Spinner
private Spinner spinner;
//An ArrayList for Spinner Items
private ArrayList<String> students;
//JSON Array
private JSONArray result;
//TextViews to display details
private TextView textViewName;
private TextView textViewCourse;
private TextView textViewSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
//Initializing the ArrayList
students = new ArrayList<String>();
//Initializing Spinner
spinner = (Spinner) findViewById(R.id.spinner);
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
spinner.setOnItemSelectedListener(this);
//Initializing TextViews
textViewName = (TextView) findViewById(R.id.textViewName);
textViewCourse = (TextView) findViewById(R.id.textViewCourse);
textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
getData();
}
private void getData(){
//Creating a string request
StringRequest stringRequest = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getStudents(JSONArray j){
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
students.add(json.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, students));
}
//Method to get student name of a particular position
private String getName(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(Config.TAG_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
//Doing the same with this method as we did with getName()
private String getCourse(int position){
String course="";
try {
JSONObject json = result.getJSONObject(position);
course = json.getString(Config.TAG_COURSE);
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}
//Doing the same with this method as we did with getName()
private String getSession(int position){
String session="";
try {
JSONObject json = result.getJSONObject(position);
session = json.getString(Config.TAG_SESSION);
} catch (JSONException e) {
e.printStackTrace();
}
return session;
}
//this method will execute when we pic an item from the spinner
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Setting the values to textviews for a selected item
textViewName.setText(getName(position));
textViewCourse.setText(getCourse(position));
textViewSession.setText(getSession(position));
}
//When no item is selected this method would execute
#Override
public void onNothingSelected(AdapterView<?> parent) {
textViewName.setText("");
textViewCourse.setText("");
textViewSession.setText("");
}
}
Please use this edited code this will work for you:
public class DemoSpinner extends AppCompatActivity implements Spinner.OnItemSelectedListener{
//Declaring an Spinner
private Spinner spinner;
//An ArrayList for Spinner Items
private ArrayList<String> students;
//JSON Array
private JSONArray result;
//TextViews to display details
private TextView textViewName;
private TextView textViewCourse;
private TextView textViewSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
//Initializing the ArrayList
students = new ArrayList<String>();
//Initializing Spinner
spinner = (Spinner) findViewById(R.id.spinner);
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
spinner.setOnItemSelectedListener(this);
//Initializing TextViews
textViewName = (TextView) findViewById(R.id.textViewName);
textViewCourse = (TextView) findViewById(R.id.textViewCourse);
textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
getData();
}
private void getData(){
//Creating a request queue
JsonObjectRequest StringRequest = new JsonObjectRequest(Request.Method.GET, Config.DATA_URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (response != null) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = response;
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Volly error is this >>" + error);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(StringRequest);
}
private void getStudents(JSONArray j){
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
students.add(json.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.e("student >>",students.toString());
//Setting adapter to show the items in the spinner
spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, students));
}
//Method to get student name of a particular position
private String getName(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(Config.TAG_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
//Doing the same with this method as we did with getName()
private String getCourse(int position){
String course="";
try {
JSONObject json = result.getJSONObject(position);
course = json.getString(Config.TAG_COURSE);
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}
//Doing the same with this method as we did with getName()
private String getSession(int position){
String session="";
try {
JSONObject json = result.getJSONObject(position);
session = json.getString(Config.TAG_SESSION);
} catch (JSONException e) {
e.printStackTrace();
}
return session;
}
//this method will execute when we pic an item from the spinner
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Setting the values to textviews for a selected item
textViewName.setText(getName(position));
textViewCourse.setText(getCourse(position));
textViewSession.setText(getSession(position));
}
//When no item is selected this method would execute
#Override
public void onNothingSelected(AdapterView<?> parent) {
textViewName.setText("");
textViewCourse.setText("");
textViewSession.setText("");
}
}
StringRequest stringRequest = new StringRequest(Request. Method.GET,Config.DATA_URL, new Response.Listener()
Use it in getData(). Because you wasn't specified Request.Method.GET
::OR::
You can use same like this:
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "filter_location");
return params;
}
};
Then remove the parameter "action=filter_location" from url.
**
the parameters of volley (company_id && branch_id)
equal null although I got its real data before via MyRequestQueue_Company so it causes volley response is nullpointer exception
Why do company_id and branch_id equal null in MyRequestQueue_Drivers? How can I solve this?
public class CheckinActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
String company_id, branch_id;
Spinner driver_name_spinner;
private String User_URL = "http://example.com/api/user?token=";
private String Drivers_URL = "http://example.com/api/getDrivers?company_id=1&branch_id=15";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkin);
driver_name_spinner = (Spinner) findViewById(R.id.driver_name_spinner);
next = (Button) findViewById(R.id.next);
SharedPreferences sharedPref = getSharedPreferences("userinfo", getApplicationContext().MODE_PRIVATE);
final String token = sharedPref.getString("token", "");
final RequestQueue MyRequestQueue_Company = Volley.newRequestQueue(this);
// GET COMPANY_ID AND BRANCH_ID FORM API
StringRequest MyStringRequest_Company = new StringRequest(Request.Method.GET, User_URL + token, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
try {
JSONObject jsono = null;
jsono = new JSONObject(response);
JSONObject jarray = jsono.getJSONObject("user");
company_id = jarray.getString("company_id");
branch_id = jarray.getString("branch_id");
Log.d("User Data", "company_id " + company_id + "\tbranch_id " + branch_id);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
});
MyRequestQueue_Company.add(MyStringRequest_Company);
// CALL ANOTHER WEBSERVICES TO GET DRIVERS DATA
RequestQueue MyRequestQueue_Drivers = Volley.newRequestQueue(getApplicationContext());
StringRequest MyStringRequest_Drivers = new StringRequest(Request.Method.POST, Drivers_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Drivers Response", response);
try {
JSONObject jsono = null;
jsono = new JSONObject(response);
JSONArray jarray = jsono.getJSONArray("Drivers");
List<String> drivers;
drivers = new ArrayList<String>();
for (int i = 0; i < jarray.length(); i++) {
JSONObject newobject = jarray.getJSONObject(i);
driver_name_txt = newobject.getString("name");
Log.d("Driver Name", driver_name_txt);
drivers.add(driver_name_txt);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_item, drivers);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
driver_name_spinner.setAdapter(dataAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Drivers Error",error.toString());
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
// BRANCH_ID AND COMPANY_ID ARE EQUAL NULL !?
MyData.put("branch_id", branch_id);
MyData.put("company_id", company_id);
Log.d("Last User Data", "company_id " + company_id + "\tbranch_id " + branch_id);
return MyData;
}
};
MyRequestQueue_Drivers.add(MyStringRequest_Drivers);
driver_name_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
TextView tmpView = (TextView) driver_name_spinner.getSelectedView().findViewById(android.R.id.text1);
tmpView.setTextColor(Color.WHITE);
driver_name_txt = parent.getItemAtPosition(position).toString();
Log.d("driver_name_original", driver_name_txt);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
If you want to use getParams function, than I would suggest to define a flag and modify your function like:
#Override
public void onResponse(String response) {
Log.d("response", response);
try {
JSONObject jsono = null;
jsono = new JSONObject(response);
JSONObject jarray = jsono.getJSONObject("user");
company_id = jarray.getString("company_id");
branch_id = jarray.getString("branch_id");
Log.d("User Data", "company_id " + company_id + "\tbranch_id " + branch_id);
requestFinished = true;
} catch (JSONException e) {
e.printStackTrace();
}
}
And your getParams would look like :
protected Map<String, String> getParams() {
if(!requestFinished) return null;
Map<String, String> MyData = new HashMap<String, String>();
// BRANCH_ID AND COMPANY_ID ARE EQUAL NULL !?
MyData.put("branch_id", branch_id);
MyData.put("company_id", company_id);
Log.d("Last User Data", "company_id " + company_id + "\tbranch_id " + branch_id);
return MyData;
But I would suggest to you to use the Observer pattern instead.
Im using volley to get and handle the Json object into the activity
and here are the classes and the following :
The problem is when im trying to get the Address ,Phones, Emails as sorting for each line from the object it show up like this first it get the address with the first line then it jumps to line 5 to get id then line 8 to get twitterUrl.
Inside the APP Data
web Service reponse on the postman
[
{
"address": "adddress1",
"emails": "ggggdjd#ttttt.com",
"facebookUrl": "ddddd",
"googlePlus": "ddddddd",
"id": 1,
"instagramUrl": "ddddd",
"phones": "0100098763 - 82726353",
"twitterUrl": "ddddd",
"youtubeUrl": "dddd"
}
]
Content Volley.java
extends BaseVolley {
// base url for srever
String TAG = "sjnsn";
private final String url = url ;
protected enum ActionType implements BaseVolley.ActionType {
appcontactus
}
public ContentVolley(String TAG, Context context) {
super(TAG, VolleySingleton.getInstance(context));
}
// method created as an example for post request for a certain api
public void getAboutUs() {
params = new HashMap<>();
actionType = ActionType.appcontactus;
requestAction(Request.Method.GET, url + ((Enum) actionType).name(), true);
}
#Override
protected void onPreExecute(BaseVolley.ActionType actionType) {
ActionType action = (ActionType) actionType;
onPreExecute(action);
}
#Override
protected void getResponseParameters(String response) throws JSONException {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
String message = "";
try {
jsonArray = new JSONArray(response);
Log.d(TAG, "getResponseParameters: "+response);
} catch (JSONException e) {
jsonObject = new JSONObject(response);
message = jsonObject.optString("msg");
}
ActionType action = (ActionType) actionType;
switch (action) {
case appcontactus:
ArrayList<ContactUsItem> contactUsList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
String address = jsonObject.optString("address");
String emails = jsonObject.optString("emails");
String phones = jsonObject.optString("phones");
String facebookUrl = jsonObject.optString("facebookUrl");
String googlePlus = jsonObject.optString("googlePlus");
String instagramUrl = jsonObject.optString("instagramUrl");
String twitterUrl = jsonObject.optString("twitterUrl");
String youtubeUrl = jsonObject.optString("youtubeUrl");
String id = jsonObject.optString("id");
ContactUsItem contactUsItem = new ContactUsItem(id, address, emails, phones, facebookUrl,googlePlus,instagramUrl
,twitterUrl,youtubeUrl);
contactUsList.add(contactUsItem);
}
onPostExecuteAboutUs(true, message,contactUsList) ;
break;
}
}
#Override
protected void onPostExecuteError(boolean success, String message, BaseVolley.ActionType actionType) {
ActionType action = (ActionType) actionType;
switch (action) {
case appcontactus:
onPostExecuteAboutUs(false, message, null);
break;
}
}
protected abstract void onPreExecute(ActionType actionType);
protected void onPostExecuteAboutUs(boolean success, String message,ArrayList<ContactUsItem> contactUsList) {
}
protected void onPostExecuteappnews(boolean success, String message, Object result) {
}
}
AboutUsFragment.java
public class AboutusFragment extends Fragment {
private final String TAG = AboutusFragment.class.getSimpleName();
private RelativeLayout relativeLayoutLoading;
private TextView email;
private TextView phone;
private TextView addres;
private ImageView imageViewFacebook, imageViewInstagram, imageViewTwitter;
public AboutusFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_about_us, container, false);
relativeLayoutLoading = (RelativeLayout) rootView.findViewById(R.id.relativeLayoutLoading);
email = (TextView) rootView.findViewById(R.id.textViewEmail);
phone = (TextView) rootView.findViewById(R.id.textViewPhone);
addres = (TextView) rootView.findViewById(R.id.textViewAddress);
imageViewFacebook = (ImageView) rootView.findViewById(R.id.imageViewFacebook);
imageViewInstagram = (ImageView) rootView.findViewById(R.id.imageViewInstagram);
imageViewTwitter = (ImageView) rootView.findViewById(R.id.imageViewTwitter);
Content content = new Content();
content.getAboutUs();
return rootView;
}
private class Content extends ContentVolley {
public Content() {
super(TAG, getContext());
}
#Override
protected void onPreExecute(ActionType actionType) {
}
protected void onPostExecuteAboutUs(boolean success, String message, ArrayList<ContactUsItem> contactUsList) {
if (success) {
for (int i = 0; i < contactUsList.size(); i++) {
ContactUsItem contactUsItem = contactUsList.get(i);
email.setText(contactUsItem.getEmail());
phone.setText(contactUsItem.getPhone());
addres.setText(contactUsItem.getAddress());
}
} else {
Toast.makeText(getContext(), "Failed: " + message, Toast.LENGTH_LONG).show();
}
}
}
}