Hey i'm creating Android application which connect with my database MySQL. I created an ArrayList with categories and added it to Adapter and then to Spinner. I see Spinner items but after onClick nothing happens and when I try to check what is in my ArrayList I see that it is empty.Data downloaded.
After click in Spinner nothing change
Here is my code:
public class InsertProductActivity extends AppCompatActivity {
Spinner categories;
String categoriesURL = "myURL";
ArrayList<String> downloadedCategories = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_product);
categories = findViewById(R.id.categories);
getCategories();
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item,downloadedCategories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
categories.setAdapter(adapter);
}
protected void getCategories(){
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, categoriesURL
, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("categories");
for(int i=0;i<jsonArray.length();i++){
downloadedCategories.add(jsonArray.getJSONObject(i).getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
}
try this one.
protected void getCategories(){
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, categoriesURL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("categories");
downloadedCategories = new ArrayList<>(); // try to add your instantiation of your arrayList here.
for(int i=0;i<jsonArray.length();i++) {
downloadedCategories.add(jsonArray.getJSONObject(i).getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//this block of code will prompt after your downloadedCategories finish storing your objects to your arrayList because if you put this in onCreate this wil call before your getCategories process not finish yet. So much better its much safer here.
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,android.R.layout.simple_spinner_item,downloadedCategories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
categories.setAdapter(adapter);
requestQueue.add(jsonObjectRequest);
}
Related
I know this is common to ask but I've already trying clear() the items since before initiate the function, but it seems it always duplicate the items, This date is comes from my MySql database but I've check my SQL but it does not duplicate names and I think the problems is in code in java which rendered ArratList but I've tried countryList.clear(); but nothings happens,need help. I have two Spinner/dropdown the second spinner depends on the first spinner list
//First Dropdown Country
public void CountryListDropdown(){
countryList.clear();
String url = "http://192.168.254.103/csu_clinic/populate_country.php";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("countries");
for(int i=0; i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String countryName = jsonObject.optString("country_name");
countryList.add(countryName);
countryAdapter = new ArrayAdapter<>(SignUp.this,
android.R.layout.simple_spinner_item, countryList);
// countryAdapter.clear();
countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCountry.setAdapter(countryAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
spinnerCountry.setOnItemSelectedListener(this);
}
//Second Dropdown that depends on dropdown 1 populate list depends from dropdown one
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(adapterView.getId() == R.id.spinnerCountry){
cityList.clear();
String selectedCountry = adapterView.getSelectedItem().toString();
String url = "http://10.0.2.2/android/populate_city.php?country_name="+selectedCountry;
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("cities");
for(int i=0; i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String cityName = jsonObject.optString("city_name");
cityList.add(cityName);
cityAdapter = new ArrayAdapter<>(SignUp.this,
android.R.layout.simple_spinner_item, cityList);
cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCity.setAdapter(cityAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
Try changing your code like this.
public void CountryListDropdown() {
String url = "http://192.168.254.103/csu_clinic/populate_country.php";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("countries");
countryList.clear();
for(int i=0; i<jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String countryName = jsonObject.optString("country_name");
countryList.add(countryName);
}
countryAdapter = new ArrayAdapter<>(SignUp.this,android.R.layout.simple_spinner_item, countryList);
countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCountry.setAdapter(countryAdapter);
spinnerCountry.setOnItemSelectedListener(this);
} catch (JSONException e) {
e.printStackTrace();
}
}}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {}
});
requestQueue.add(jsonObjectRequest);
}
Using Volley, I was able to make a asynchronous HTTP GET call to my API that i wanted to hit. But it is taking 15 to 20 seconds to fetch the data and populate it on the UI, Staggered Grid Layout using Recycler View.
For every search call I make, it roughly takes that much time which is bad. How do I reduce this latency? I also added the RequestQueue but no luck.
I'm initializing the Adapter after the search call is made. Is it a good approach to do it there? Or would you recommend doing it in onCreate method of activity. Could anyone please guide what's the cause for this latency?
Here's the excerpt from the code
public class StaggeredSearchActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private StaggeredGridLayoutManager staggeredGridLayoutManager;
private StaggeredGridAdapter staggeredGridAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_staggered_search);
Intent intent = getIntent();
String searchText = intent.getStringExtra("searchText");
getSearchData(searchText);
recyclerView = findViewById(R.id.staggered_recycler_view);
staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
}
private void getSearchData(String searchText) {
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
String url = "https://my-json-server.typicode.com/typicode/demo/comments";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
ArrayList<StaggeredCustomCard> dataset = new ArrayList<>();
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array = response.getJSONArray("tweets");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String body = jsonObject.getString("body");
String postId = jsonObject.getString("postId");
dataset.add(new StaggeredCustomCard(body, postId);
}
staggeredGridAdapter = new StaggeredGridAdapter(StaggeredSearchActivity.this, dataset);
recyclerView.setAdapter(staggeredGridAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO: Handle error
...
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(50000, 5, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjectRequest);
}
}
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);
}
Hello guys i have now searched for the error or how to do it correct for some time and yes alot of questions in here have helped me closer i think.
but i got an API where i get a JSONArray and i want to show this data in a listview. So far i get my data in my log, and now i just try to show the name from each object to start with(then i can add the rest of data later) but im not sure if im on the right spot maybe someone can help me out here and show what im doing wrong?
Thanks alot
Listview name: AllBirds
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_observation);
mAuth = FirebaseAuth.getInstance();
String URL="myAPI";
RequestQueue requestQueue= Volley.newRequestQueue(this);
JsonArrayRequest objectRequest = new JsonArrayRequest (Request.Method.GET, URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("Rest Response",response.toString());
try{
for(int i=0; i<response.length();i++){
JSONObject jresponse = response.getJSONObject(i);
String NameDanish = jresponse.getString("NameDanish");
Log.d("NameDanish", NameDanish);
}
}catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Rest Response",error.toString());
}
});
requestQueue.add(objectRequest);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_all_observation, NameDanish);
ListView list = (ListView) findViewById(R.id.AllBirds);
list.setAdapter(adapter);
}
Create ArrayList in your class
ArrayList arrayList = new ArrayList<>();
change your above code with
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_observation);
mAuth = FirebaseAuth.getInstance();
String URL = "myAPI";
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonArrayRequest objectRequest = new JsonArrayRequest(Request.Method.GET, URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("Rest Response", response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jresponse = response.getJSONObject(i);
String NameDanish = jresponse.getString("NameDanish");
arrayList.add(NameDanish);
Log.d("NameDanish", NameDanish);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Rest Response", error.toString());
}
});
requestQueue.add(objectRequest);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_all_observation, arrayList);
ListView list = (ListView) findViewById(R.id.AllBirds);
list.setAdapter(adapter);
}
Create a string arraylist globally like this
ArrayList<String> name_array=new ArrayList<>();
then add
try{
for(int i=0; i<response.length();i++){
JSONObject jresponse = response.getJSONObject(i);
String NameDanish = jresponse.getString("NameDanish");
name_array.add(NameDanish);
Log.d("NameDanish", NameDanish);
}
then pass this arraylist to your adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_all_observation, name_array);
Create listView, adapter, array as member variable and use notifyDataUpdate from responseHandler to update data.
ListView mList;
ArrayAdapter<String> mAdapter
ArrayList<String> mData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_observation);
mData=new ArrayList<>();
mList = (ListView) findViewById(R.id.AllBirds);
mAdapter = new ArrayAdapter<String>(this, R.layout.activity_all_observation, mData);
list.setAdapter(adapter);
mAuth = FirebaseAuth.getInstance();
String URL="myAPI";
RequestQueue requestQueue= Volley.newRequestQueue(this);
JsonArrayRequest objectRequest = new JsonArrayRequest (Request.Method.GET, URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("Rest Response",response.toString());
try{
for(int i=0; i<response.length();i++){
JSONObject jresponse = response.getJSONObject(i);
String NameDanish = jresponse.getString("NameDanish");
mData.add(NameDanish);
Log.d("NameDanish", NameDanish);
}
mAdapter.notifyDataSetChanged();
}catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Rest Response",error.toString());
}
});
requestQueue.add(objectRequest);
}
I have now changed the code to this as Toyj said, i have posted my xml to.
i dont get any data out only all the names are showed in the log?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_observation);
mAuth = FirebaseAuth.getInstance();
final ArrayList arrayList = new ArrayList<>()
String URL="MYAPI";
RequestQueue requestQueue= Volley.newRequestQueue(this);
JsonArrayRequest objectRequest = new JsonArrayRequest (Request.Method.GET, URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.e("Rest Response",response.toString());
try{
//JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<response.length();i++){
JSONObject jresponse = response.getJSONObject(i);
String NameDanish = jresponse.getString("NameDanish");
arrayList.add(NameDanish);
Log.d("NameDanish", NameDanish);
}
}catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Rest Response",error.toString());
}
});
requestQueue.add(objectRequest);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_all_observation, arrayList);
ListView list = (ListView) findViewById(R.id.AllBirds);
list.setAdapter(adapter);
}
JSON data looks like this where i just take NameDanish to start with
{
"BirdId": 1,
"Comment": null,
"Created": "/Date(1523836800000+0000)/",
"Id": 132,
"Latitude": 55.6886037,
"Longitude": 12.5310135,
"Placename": "K",
"Population": 0,
"UserId": "user1",
"NameDanish": "solsort",
"NameEnglish": "blackbird"
}
XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="net.simplifiedlearning.firebaseauth.all_observationActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/AllBirds">
</ListView>
</LinearLayout>
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();
}
}