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.
Related
Hello stackoverflow community!!
How do I access a JSON array
in this URL "https://api.json-generator.com/templates/z0aMAeTBHKq3/data"
token is "2oof0bzpgllll2a8k2fmmh6aaykeu8yptztdzke7"
but when I display the data in an Activity, it just displays blank and exits the app. But When I change the URL without an auth/bearer token I can see the displayed data in the URL.
So my question: is how do I put the token in header so that I can have access and see the data displayed in the mobile phone?
I know it is simple but i am having a hard time.
This is my MainActivity.java
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RequestQueue requestQueue;
private List<Movie> movieList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
requestQueue = VolleySingleton.getmInstance(this).getRequestQueue();
movieList = new ArrayList<>();
fetchMovies();
}
private void fetchMovies() {
//Url with auth
String url = "https://api.json-generator.com/templates/z0aMAeTBHKq3/data";
//URL without auth
//String url = "https://jsonplaceholder.typicode.com/posts";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0 ; i < response.length() ; i ++){
try {
JSONObject jsonObject = response.getJSONObject(i);
String userId = jsonObject.getString("userId");
String id = jsonObject.getString("id");
String title = jsonObject.getString("title");
String body = jsonObject.getString("body");
Movie movie = new Movie(title , userId , id , body);
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
MovieAdapter adapter = new MovieAdapter(MainActivity.this , movieList);
recyclerView.setAdapter(adapter);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
HashMap headers = new HashMap();
String authValue = "Bearer " +
"2oof0bzpgllll2a8k2fmmh6aaykeu8yptztdzke7";
headers.put("Authorization", authValue);
headers.put("Accept", "application/json; charset=UTF-8");
headers.put("Content-Type", "application/json; charset=UTF-8");
requestQueue.add(jsonArrayRequest);
}
}
this is my Movie.java
public class Movie {
private String userId , id , title, body;
public Movie(String userId , String id , String title , String body){
this.title = title;
this.userId = userId;
this.id = id;
this.body = body;
}
public String getTitle() {
return title;
}
public String getUserId() {
return userId;
}
public String getId() {
return id;
}
public String getBody() {
return body;
}
}
this is my MovieAdapter.java
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MovieHolder> {
private Context context;
private List<Movie> movieList;
public MovieAdapter(Context context , List<Movie> movies){
this.context = context;
movieList = movies;
}
#NonNull
#Override
public MovieHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item , parent , false);
return new MovieHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MovieHolder holder, int position) {
Movie movie = movieList.get(position);
holder.userId.setText(movie.getUserId().toString());
holder.id.setText(movie.getId());
holder.title.setText(movie.getTitle());
holder.body.setText(movie.getBody());
holder.constraintLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context , DetailActivity.class);
Bundle bundle = new Bundle();
bundle.putString("userId" , movie.getUserId());
bundle.putString("id" , movie.getId());
bundle.putString("title" , movie.getTitle());
bundle.putString("body" , movie.getBody());
intent.putExtras(bundle);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return movieList.size();
}
public class MovieHolder extends RecyclerView.ViewHolder{
TextView title , userId , id, body;
ConstraintLayout constraintLayout;
public MovieHolder(#NonNull View itemView) {
super(itemView);
userId = itemView.findViewById(R.id.userid_tv);
title = itemView.findViewById(R.id.title_tv);
id = itemView.findViewById(R.id.id_tv);
body = itemView.findViewById(R.id.id_tv);
constraintLayout = itemView.findViewById(R.id.main_layout);
}
}
}
This is my VolleySingleton.java
public class VolleySingleton {
private RequestQueue requestQueue;
private static VolleySingleton mInstance;
private VolleySingleton(Context context){
requestQueue = Volley.newRequestQueue(context.getApplicationContext());
}
public static synchronized VolleySingleton getmInstance(Context context){
if (mInstance == null){
mInstance = new VolleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue(){return requestQueue;}
}
Try This
Change
private void fetchMovies() {
//Url with auth
String url = "https://api.json-generator.com/templates/z0aMAeTBHKq3/data";
//URL without auth
//String url = "https://jsonplaceholder.typicode.com/posts";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0 ; i < response.length() ; i ++){
try {
JSONObject jsonObject = response.getJSONObject(i);
String userId = jsonObject.getString("userId");
String id = jsonObject.getString("id");
String title = jsonObject.getString("title");
String body = jsonObject.getString("body");
Movie movie = new Movie(title , userId , id , body);
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
MovieAdapter adapter = new MovieAdapter(MainActivity.this , movieList);
recyclerView.setAdapter(adapter);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
HashMap headers = new HashMap();
String authValue = "Bearer " +
"2oof0bzpgllll2a8k2fmmh6aaykeu8yptztdzke7";
headers.put("Authorization", authValue);
headers.put("Accept", "application/json; charset=UTF-8");
headers.put("Content-Type", "application/json; charset=UTF-8");
requestQueue.add(jsonArrayRequest);
}
To
private void fetchMovies() {
// Url with auth
String url = "https://api.json-generator.com/templates/z0aMAeTBHKq3/data";
// URL without auth
// String url = "https://jsonplaceholder.typicode.com/posts";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0 ; i < response.length() ; i ++){
try {
JSONObject jsonObject = response.getJSONObject(i);
String userId = jsonObject.getString("userId");
String id = jsonObject.getString("id");
String title = jsonObject.getString("title");
String body = jsonObject.getString("body");
Movie movie = new Movie(title , userId , id , body);
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
MovieAdapter adapter = new MovieAdapter(MainActivity.this , movieList);
recyclerView.setAdapter(adapter);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
String authValue = "Bearer " + "2oof0bzpgllll2a8k2fmmh6aaykeu8yptztdzke7";
headers.put("Authorization", authValue);
headers.put("Accept", "application/json; charset=UTF-8");
headers.put("Content-Type", "application/json; charset=UTF-8");
return headers;
}
};
requestQueue.add(jsonArrayRequest);
}
put your headers code inside getHeaders() #Overtide method
I have problem with data = new BarData(names, yAxis);
Cannot resolve constructor 'BarData(java.lang.String[], java.util.ArrayList)
I uses com.github.PhilJay:MPAndroidChart:v2.2.5
I'm new to this programming language, and I'm writing a diploma, but I ran into such a problem, I need to insert graphics into the program, help please.
private ProgressDialog pd;
ArrayList<BarDataSet> yAxis;
ArrayList<BarEntry> yValues;
ArrayList<String> xAxis1;
BarEntry values ;
BarChart chart;
BarData data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.graph_temp);
pd = new ProgressDialog(intoGraph.this);
pd.setMessage("load");
// Log.d("array",Arrays.toString(fullData));
chart = (BarChart) findViewById(R.id.chart);
load_data_from_server();
}
public void load_data_from_server() {
pd.show();
String url = "http://192.168.0.3/temp2.php";
xAxis1 = new ArrayList<>();
yAxis = null;
yValues = new ArrayList<>();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("string",response);
try {
JSONArray jsonarray = new JSONArray(response);
for(int i=0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String temperature = jsonobject.getString("temperature").trim();
String date = jsonobject.getString("date").trim();
xAxis1.add(date);
values = new BarEntry(Float.valueOf(temperature),i);
yValues.add(values);
}
} catch (JSONException e) {
e.printStackTrace();
}
BarDataSet barDataSet1 = new BarDataSet(yValues, "temper");
barDataSet1.setColor(Color.rgb(0, 82, 159));
yAxis = new ArrayList<>();
yAxis.add(barDataSet1);
String names[]= xAxis1.toArray(new String[xAxis1.size()]);
data = new BarData(names, yAxis);
chart.setData(data);
chart.setDescription("");
chart.animateXY(2000, 2000);
chart.invalidate();
pd.hide();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(error != null){
Toast.makeText(getApplicationContext(), "err...", Toast.LENGTH_LONG).show();
pd.hide();
}
}
}
);
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
}
I'm trying to make an app . I struggling to get some data of one of my table in my database . I know how to get everything from my table , but now i need only few lines of this table. So I have to pass an ID .
The problem is that i cant add any param in JsonArrayRequest.
You can see my php file and my class where I'm calling JsonArrayRequest:
php
<?php
include 'dbconfig.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user_id = $_POST["user_id"]; // this is what Im trying to fix
$sql = "SELECT * FROM plans WHERE user_id=?"; // and pass the information in ?
$result = $conn->query($sql);
if ($result->num_rows >0) {
// output data of each row
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "0 results";
}
echo $json;
$conn->close();
?>
java class:
public class PlansActivity extends AppCompatActivity {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
ProgressBar progressBar;
String GET_JSON_DATA_HTTP_URL = "http://travelb.000webhostapp.com/jsonData.php";
String JSON_ID = "user_id";
String JSON_NAME = "destination";
String JSON_SUBJECT = "date";
String JSON_PHONE_NUMBER = "plan_id";
Button button;
PostJsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plans);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
button = (Button)findViewById(R.id.button) ;
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
final Intent intent = getIntent();
final int id = intent.getIntExtra("user_id", -1);
/* button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
JSON_DATA_WEB_CALL();
}
});*/
JSON_DATA_WEB_CALL();
}
public void JSON_DATA_WEB_CALL(){
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.GONE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setId(json.getInt(JSON_ID));
GetDataAdapter2.setName(json.getString(JSON_NAME));
GetDataAdapter2.setSubject(json.getString(JSON_SUBJECT));
GetDataAdapter2.setPhone_number(json.getString(JSON_PHONE_NUMBER));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
I read lot of thing but all different . Im new on androidstudio and php .
I hope someone can help me , because Im tryin to do that for 2weeks now .
You should extends JsonArrayRequest in your custom Request like this:
public class MyJsonArrayRequest extends JsonArrayRequest {
private Map<String, String> mPostParams;
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return mPostParams;
}
public MyJsonArrayRequest(String url, Map<String, String> postParams, Response.Listener<JSONArray> listener, Response.ErrorListener errorListener) {
super(url, listener, errorListener);
this.mPostParams = postParams;
}
}
with getParams() method you will able to pass POST parameters.
Map<String, String> params = new HashMap<>();
params.put("ID", id);
params.put("USER_ID", userId);
MyJsonArrayRequest jsonArrayRequest = new MyJsonArrayRequest(GET_JSON_DATA_HTTP_URL, params,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.GONE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Another way is to pass parameters via GET request in URL.
You can send parameters with jsonArrayRequest like this by overriding getParam method
JsonArrayRequest request = new JsonArrayRequest(method, url, null, responseListener, errorListener) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
try {
params.put("paramOne", "hello");
} catch (JSONException e) {
e.printStackTrace();
}
return params;
}
};
addToRequestQueue(request);
#mcatta
I want to do something like I did in my others acticity :
ProfileRequest profilRequest = new ProfileRequest(id, responseListener);
RequestQueue queue = Volley.newRequestQueue(UserAreaActivity.this);
queue.add(profilRequest);
and
public class ProfileRequest extends StringRequest {
private static final String PROFIL_REQUEST_URL = "http://travelb.000webhostapp.com/Profil.php ";
private Map<String, String> params;
public ProfileRequest(int user_id, Response.Listener<String> listener){
super(Request.Method.POST, PROFIL_REQUEST_URL, listener, null);
params= new HashMap<>();
params.put("user_id", user_id+"");
}
#Override
public Map<String, String> getParams() {
return params;
}
}
so the id in profilerequest is a final int variable.
this one was easy to do .
Im still confused with jsonarrayrequest
Its been a long time but,
someone can find it useful
and the following code works .
public class Activity extends AppCompatActivity {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
ProgressBar progressBar;
String GET_JSON_DATA_HTTP_URL = "API here";
//String JSON_ID = "id";
//we have intilize here with json names and database column name also should be kept here
String JSON_FNAME = "contact_fname";
String JSON_LNAME = "contact_lname";
RequestQueue requestQueue ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
//json web call from web
JSON_DATA_WEB_CALL();
}
public void JSON_DATA_WEB_CALL(){
String uid ="value"//Or you can use your value to pass
StringRequest strrequest = new StringRequest(Request.Method.POST,GET_JSON_DATA_HTTP_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressBar.setVisibility(View.GONE);
try {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("userid", uid);//userid to send to php
return params;
}
};
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(strrequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(String array) throws JSONException {
JSONArray jarr = new JSONArray(array);
for(int i = 0; i<jarr.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();//adapter class
//JSONObject json;
try {
JSONObject json = jarr.getJSONObject(i);
// JSONObject json = (JSONObject) array.get(String.valueOf(i));
//set and get methods should declare here with database colmun names and json names
GetDataAdapter2.setcontact_fname(json.getString(JSON_FNAME));
GetDataAdapter2.setcontact_lname(json.getString(JSON_LNAME));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
**
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.
I have php file when user post existing ticknumber the php will echo JSON code for one array of that was posted, I linked it with Activity that will do same job of php file but when I click on button I get toast message "please check the number" like php page echo " error " but it's not true because I tried by postman and it's work
<?php
if ($_SERVER ['REQUEST_METHOD']=='POST') {
$ticketnumber = $_POST['ticketnumber'];
require_once('config.php');
$con->set_charset('utf8');
$sql = " SELECT * FROM contact WHERE ticketnumber = '$ticketnumber' ";
$res = mysqli_query($con, $sql);
$result = array();
while($get = mysqli_fetch_array($res))
{
array_push($result,array('ticketnumber' =>$get[5], 'subject' =>$get[4],'response' =>$get[6]));
}
if(!empty($result)){
echo json_encode(array("responseticket"=>$result));
} else {
echo " error";
}
}
?>
supportActivity.java
public class supportActivity extends Fragment 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://abvb.com/aaa/getticket.php";
private RequestQueue requestQueue1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_support, container, false);
getActivity().setTitle("Get Ticket");
ticketsupport = (EditText)view.findViewById(R.id.insertticketnumber);
supportlist = (ListView)view.findViewById(R.id.supportlistview);
adapter = new supportAdapter(getActivity(), con);
supportlist.setAdapter(adapter);
button = (Button)view.findViewById(R.id.buttonsupprt);
button.setOnClickListener(this);
return view;
}
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("error")) {
Toast.makeText(getActivity(), "please check the number", Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = jsonObject.getJSONArray("responseticket");
JSONObject jTicket = jsonArray.getJSONObject(0);
String Ticketnumber = jTicket.getString("ticketnumber");
String Subject = jTicket.getString("subject");
String Response = jTicket.getString("response");
supportContent support = new supportContent();
support.setTicketnumber(Ticketnumber);
support.setSubject(Subject);
support.setResponse(Response);
con.add(support);
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "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;
}
};
requestQueue1 = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue1.add(stringRequest1);
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public void onClick(View view){
inquiry();
}
}
when ticketnumber existed then php will echo JSON like this
{"responseticket":[{"ticketnumber":"285","subject":"\u0627\u062d\u0628\u0643\u0645 \u0643\u0644\u0643\u0645","response":"vcvc"}]}
Your PHP expects "ticketnumber" in POST arguments:
$ticketnumber = $_POST['ticketnumber'];
Change your android code from:
#Override
protected Map<String,String> getParams() throws AuthFailureError{
Map<String,String> map = new HashMap<String,String>();
map.put("ticknumber", ticketinput);
return map;
}
to:
#Override
protected Map<String,String> getParams() throws AuthFailureError{
Map<String,String> map = new HashMap<String,String>();
map.put("ticketnumber", ticketinput);
return map;
}