I want to make a view . Here would be multiple option and one option would have multiple button. Data will retrieve from web-service. The whole process have to do dynamically.
My code is here,and I made like that but i have to do it like image above.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_option_selection);
tableLayout = (TableLayout) findViewById(R.id.linear);
int itemId = getIntent().getIntExtra("itemId", 0);
getGroupName(itemId);
}
private void getGroupName( final int itemId) {
StringRequest stringrequest = new StringRequest(Method.GET,
getString(R.string.base_url)+"ItemsOptions/GetGroupByItemID?itemID="
+ itemId, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
groupId = jsonArray.getJSONObject(i)
.getString("GroupName");
showOption(itemId,groupId);
}
//showOption(itemId,groupId);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
}
});
AppController.getInstance().addToRequestQueue(stringrequest);
}
protected void showOption(int itemId,String groupName) {
StringRequest stringrequest = new StringRequest(Method.GET,
getString(R.string.base_url)+"ItemsOptions/GetAllOptionByItemGroupID?itemID="+itemId+"&groupID="+groupName+"",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
String option = jsonArray.getJSONObject(i)
.getString("OptionsName");
if (i % 3 == 0) {
tableRow = new TableRow(
getApplicationContext());
tableLayout.addView(tableRow);
}
orderBtn = new OrderButton(
getApplicationContext());
orderBtn.setId(i);
orderBtn.setText(option);
orderBtn.setTextColor(Color
.parseColor("#FFFFFF"));
orderBtn.setBackgroundResource((R.drawable.selector));
tableRow.addView(orderBtn);
orderBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
v.setSelected(true);
enabledButton = orderBtn.getId();
deselectButtons();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
}
});
AppController.getInstance().addToRequestQueue(stringrequest);
whateverbuttonclicked.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
LinearLayout layoutyouwantbuttonin = (LinearLayout)findViewById(R.id.layoutyouwantbuttonin);
Button brandnewbutton = new Button(NameofActivity.this);
String bc = whateverbuttonclicked.getText().toString();
brandnewbutton.setText(bc);
layoutyouwantbuttonin.addView(brandnewbutton);
}});
Related
I have an activity with several buttons . Each button loads a json data to the recyclerview from a json link.The problem with Volley here is
1) It loads the JSON data in the recyclerview only after I click the button two times (CLICK , GO BACK AND THEN CLICK).
2) When I try to load the JSON data for other buttons , my data gets replicated and the list is not cleared.
3) If I manually clear the list using json_list.clear() then I get an empty recycler view.
This is my code...
public class PreviousQuestionPapers2 extends AppCompatActivity {
TextView firstYear;
TextView secondYear;
TextView thirdYear;
TextView fourthYear;
PopulateListsForClasses p1=new PopulateListsForClasses();
Parcelable parcelable;
List<SingleItemDetails> listToSend;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prev_question_papers_second_dashboard);
firstYear=findViewById(R.id.FIRST_YEAR);
secondYear=findViewById(R.id.SECOND_YEAR);
thirdYear=findViewById(R.id.THIRD_YEAR);
fourthYear=findViewById(R.id.FOURTH_YEAR);
listToSend=new ArrayList<SingleItemDetails>();
final String branch = getIntent().getStringExtra("branch");
firstYear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (branch)
{
case "it":
populate_it_first_year();
listToSend = getList_to_return();
moveToNextActivity();
break;
case "cse":
populate_cse_first_year();
listToSend = getList_to_return();
moveToNextActivity();
break;
default:
Toast.makeText(PreviousQuestionPapers2.this,"UNDEFINED!",Toast.LENGTH_SHORT).show();
}
}
});
secondYear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (branch)
{
case "it":
populate_it_second_year();
listToSend =getList_to_return();
moveToNextActivity();
break;
case "cse":
populate_cse_second_year();
listToSend = getList_to_return();
moveToNextActivity();
break;
default: Toast.makeText(PreviousQuestionPapers2.this,"UNDEFINED!",Toast.LENGTH_SHORT).show();
}
}
});
List<SingleItemDetails>json_list=new ArrayList<>();
String myurl;
public List<SingleItemDetails> getList_to_return()
{
return json_list;
}
public void FetchJSONData(String url) {
String JSON_URL = url;
RequestQueue queue = Volley.newRequestQueue(this);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, JSON_URL, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
//JSONObject songObject = response.getJSONObject(i);
JSONObject movieObject = response.getJSONObject(i);
SingleItemDetails mov = new SingleItemDetails();
mov.setTitle(movieObject.getString("title"));
mov.setUrlForDownload(movieObject.getString("urlForDownload"));
json_list.add(mov);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("tag", "onErrorResponse: " + error.getMessage());
}
});
queue.add(jsonArrayRequest);
}
public void moveToNextActivity()
{
parcelable = Parcels.wrap(listToSend);
Intent intent = new Intent(PreviousQuestionPapers2.this, RecyclerMainActivity.class);
intent.putExtra("listToDisplay", parcelable);
startActivity(intent);
}
public void populate_it_first_year()
{
myurl = "http://www.json-generator.com/api/json/get/bUcmgeeCJK?indent=2";
FetchJSONData(myurl);
}
public void populate_it_second_year() {
myurl ="http://www.json-generator.com/api/json/get/bOOxdXLLWW?indent=2";
FetchJSONData(myurl);
}
public void populate_cse_first_year () {
myurl ="http://www.json-generator.com/api/json/get/ckWYWzcqrm?indent=2";
}
public void populate_cse_second_year () {
myurl ="http://www.json-generator.com/api/json/get/clAEQTAhQi?indent=2";
}
I have tried send selected item from first spinner and i want second spinner show if first spinner selected and send data to string request URL but failed. Example I've been selected number 1 on first spinner and second spinner showing based string URL which already send from first. like this http://192.168.43.66/json/kota/1 and more
public String DataIDProvinsi;
private ArrayList<String>id_provinsi;
private ArrayList<String>nama_provinsi;
private ArrayList<String>id_kota;
private ArrayList<String>nama_kota;
private ArrayList<String>id_kecamatan;
private ArrayList<String>nama_kecamatan;
private JSONArray result;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
nama_provinsi = new ArrayList<String>();
id_provinsi = new ArrayList<String>();
id_kota = new ArrayList<String>();
nama_kota = new ArrayList<String>();
TxtDataProvinsi = (EditText) findViewById(R.id.TxtDataProvinsi);
spinner_provinsi = (Spinner) findViewById(R.id.spinner_provinsi);
spinner_kota = (Spinner) findViewById(R.id.spinner_kota);
spinner_jk = (Spinner) findViewById(R.id.spinner_jk);
TxtIdProvinsi = (TextView) findViewById(R.id.TxtIdProvinsi);
spinner_provinsi.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?>parent, View view, int position, long id){
}
#Override
public void onNothingSelected(AdapterView<?>parent){
TxtIdProvinsi.setText("");
}
});
spinner_kota.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?>parent, View view, int position, long id){
}
#Override
public void onNothingSelected(AdapterView<?>parent){
}
});
TxtIdKota = (TextView) findViewById(R.id.TxtIdKota);
TxtTglLhr = findViewById(R.id.TxtTglLahir);
findViewById(R.id.TxtTglLahir).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDatePickerDialog();
}
});
getDataProvinsi();
getDataKota();
}
private void showDatePickerDialog(){
DatePickerDialog datePickerDialog = new DatePickerDialog(this,
this, Calendar.getInstance().get(Calendar.YEAR),
Calendar.getInstance().get(Calendar.MONTH),
Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
String tanggal = year+"-"+month+"-"+dayOfMonth;
TxtTglLhr.setText(tanggal);
}
public void getDataProvinsi(){
pDialog = new ProgressDialog(RegisterActivity.this);
pDialog.setCancelable(false);
pDialog.setMessage("Mohon Menunggu...");
// showDialog();
StringRequest stringRequestProvinsi = new StringRequest("http://192.168.43.66/json/provinsi/", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray("result");
getNamaProvinsi(result);
} catch (JSONException e) {
e.printStackTrace();
}
// hideDialog();
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequestProvinsi);
}
public void getDataKota(){
DataIDProvinsi = spinner_provinsi.getSelectedItem().toString();
StringRequest stringRequestKota = new StringRequest("http://192.168.43.66/json/kota/"+DataIDProvinsi, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray("result");
getNamaKota(result);
} catch (JSONException e) {
e.printStackTrace();
}
// hideDialog();
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequestKota);
}
public void getNamaProvinsi(JSONArray j){
for (int i = 0; i < j.length(); i++){
try {
JSONObject jsonProvinsi = j.getJSONObject(i);
id_provinsi.add(jsonProvinsi.getString("id_provinsi"));
//nama_provinsi.add(jsonProvinsi.getString(ProvinsiActivity.TAG_NAMA_PROVINSI));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinner_provinsi.setAdapter(new ArrayAdapter<String>(RegisterActivity.this,
R.layout.support_simple_spinner_dropdown_item, id_provinsi));
}
public void getNamaKota(JSONArray j){
for (int i = 0; i < j.length(); i++){
try {
JSONObject jsonKota = j.getJSONObject(i);
//id_kota.add(jsonKota.getString(KotaActivity.TAG_ID_KOTA));
nama_kota.add(jsonKota.getString("nama_kota"));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinner_kota.setAdapter(new ArrayAdapter<String>(RegisterActivity.this,
R.layout.support_simple_spinner_dropdown_item, nama_kota));
}
private void showDialog(){
if(!pDialog.isShowing())
pDialog.show();
}
private void hideDialog(){
if(pDialog.isShowing())
pDialog.dismiss();
}
}
I have created a separate class in which I have defined all about volley and in another activity, I have directly pass URL, CONTEXT and Get Response...
but in my NavDrawerActivity.java how do I call the subCategoryJSON(); method without writing my volley code again as I have done with mainCategoryJSON(); method in which I just simply pass the URL, method type.
Also is this a correct approach I am doing or there need to be some modification in the code, what I want is that wherever I am using API in my project and using volley for it, I don't have to write code again and again just simply pass the URL,method type
VolleyResponseListener.java
public interface VolleyResponseListener {
void onResponse(String response, String tag);
void onError(VolleyError error, String tag);
}
CustomStringRequestVolley.java
public class CustomStringRequestVolley {
private String url;
private String tag;
Context ctx;
private VolleyResponseListener volleyResponseListener;
public CustomStringRequestVolley(String url, String tag,Context ctx,VolleyResponseListener volleyResponseListener){
this.url = url;
this.tag = tag;
this.ctx=ctx;
this.volleyResponseListener = volleyResponseListener;
sendRequest();
}
private void sendRequest() {
final ProgressDialog pDialog = new ProgressDialog(ctx);
pDialog.setMessage("Loading ...");
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("catresponse", "response " + response);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
volleyResponseListener.onResponse(response, tag);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance(ctx).addToRequestQueue(stringRequest);
}
}
NavDrawerActivity.java
public class NavDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, VolleyResponseListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mainCategoryJSON();
subCategoryJSON();
}
private void mainCategoryJSON() {
CustomStringRequestVolley request1 = new CustomStringRequestVolley(URLs.categoryURL, "TAG1", this, this);
}
#Override
public void onResponse(String response, String tag) {
switch (tag) {
case "TAG1":
try {
Log.i("Responseeeeeezaq :", response.toString() + " " + tag);
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
CategoryModelClass categoryModelClass = new CategoryModelClass();
categoryModelClass.setCategoryID(productObject.getInt("Category-Id"));
categoryModelClass.setCategoryName(productObject.getString("Category-Name"));
categoryModelClass.setCategoryImg(productObject.getString("Category-Image"));
categoryArrayList.add(categoryModelClass);
Log.d("zpuyi", String.valueOf(categoryArrayList));
}
categoryAdapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
#Override
public void onError(VolleyError error, String tag) {
VolleyLog.e("Error: ", error.getMessage());
}
private void subCategoryJSON() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URLs.subcategoryURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("subcategoryJsonResponse", response.toString());
try {
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("sub-categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
SubCategoryModelClass subCategoryModelClass = new SubCategoryModelClass();
subCategoryModelClass.setSubCategory_Id(productObject.getInt("Subcategories-Id"));
subCategoryModelClass.setCat_id(productObject.getInt("categories-Id"));
subCategoryModelClass.setSubCategory_Name(productObject.getString("Subcategories-Name"));
subCategoryModelClass.setSubCategory_Img(productObject.getString("Subcategories-Image"));
subCategoryModelClassList.add(subCategoryModelClass);
Log.d("subCategoryArraylist", String.valueOf(subCategoryModelClassList));
}
for (int i = 0; i < subCategoryModelClassList.size(); i++) {
subcategory_id = subCategoryModelClassList.get(i).getSubCategory_Id();
category_id = subCategoryModelClassList.get(i).getCat_id();
subcategory_name = subCategoryModelClassList.get(i).getSubCategory_Name();
// subcategory_desc = subCategoryModelClassList.get(i).getSubCategory_Desc();
subcategory_image = subCategoryModelClassList.get(i).getSubCategory_Img();
Log.d("fdsaff", subcategory_image);
SQLiteDatabase database = dbHelper.getWritableDatabase();
dbHelper.insertSubCategoryProduct(subcategory_id, category_id, subcategory_name, "https://www.ecrm.sample.in/app/img/"+subcategory_image, database);
dbHelper.close();
}
subCategoryAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
}
You have written the answer correctly but you are not implementing the written custom volley class code in the activity class.
First Define the interface class for the Volley as below,
Now implement the volley interface in the java class where you have written the custom volley class as below:
CustomStringRequestVolley.java
public class CustomStringRequestVolley implements volleyCallback {
public Context context;
public CustomStringRequestVolley(Context context) {
this.context = context;
}
public interface volleyCallback {
void onSuccess(String result);
void onError(String error);
}
public void callGetServer(String URL, final
volleyCallback callback){
if (!checkInternetConnection(context)) {
showNoInternetDialogue(context);
return;
}
RequestQueue requestQueue = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
callback.onSuccess(response);
}
}, error -> {
if (error.networkResponse == null){
if (error.getClass().equals(TimeoutError.class)){
Toast.makeText(context, "Timeout.Please try again",
Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(NoConnectionError.class)){
Toast.makeText(context, "Timeout.Please try again", Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(NetworkError.class)) {
Toast.makeText(context, "Network Error.Please try again", Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(ParseError.class)){
Toast.makeText(context, "Parse error", Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(ServerError.class)){
Toast.makeText(context, "Server Error.Please try again", Toast.LENGTH_SHORT).show();
}
else {
parseVolleyError(error);
}
}
}
) {
#Override
protected Map<String, String> getParams() {
return new HashMap<>();
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
return headers;
}
};
//setting up the retry policy for slower connections
int socketTimeout = 120000;//120000 milli seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
}
Now use this Custom volley class in every activity you required. It reduces you
boilerplate code
NavDrawerActivity.java
CustomStringRequestVolley customStringRequestVolley;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_point_navigation);
customStringRequestVolley = new CustomStringRequestVolley(this);
}
private void subCategoryJSON() {
customStringRequestVolley.callGetServer(URLs.subcategoryURL,new volleyCallback() {
#Override
public void onSuccess(String result) {
try {
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("sub-categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
SubCategoryModelClass subCategoryModelClass = new SubCategoryModelClass();
subCategoryModelClass.setSubCategory_Id(productObject.getInt("Subcategories-Id"));
subCategoryModelClass.setCat_id(productObject.getInt("categories-Id"));
subCategoryModelClass.setSubCategory_Name(productObject.getString("Subcategories-Name"));
subCategoryModelClass.setSubCategory_Img(productObject.getString("Subcategories-Image"));
subCategoryModelClassList.add(subCategoryModelClass);
Log.d("subCategoryArraylist", String.valueOf(subCategoryModelClassList));
}
for (int i = 0; i < subCategoryModelClassList.size(); i++) {
subcategory_id = subCategoryModelClassList.get(i).getSubCategory_Id();
category_id = subCategoryModelClassList.get(i).getCat_id();
subcategory_name = subCategoryModelClassList.get(i).getSubCategory_Name();
// subcategory_desc = subCategoryModelClassList.get(i).getSubCategory_Desc();
subcategory_image = subCategoryModelClassList.get(i).getSubCategory_Img();
Log.d("fdsaff", subcategory_image);
SQLiteDatabase database = dbHelper.getWritableDatabase();
dbHelper.insertSubCategoryProduct(subcategory_id, category_id, subcategory_name, "https://www.ecrm.sample.in/app/img/"+subcategory_image, database);
dbHelper.close();
}
subCategoryAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(String error) {
//show error code
}
});
}
Let me know after you try this #Abhishek
I have a Spinner and a RecyclerView and the RecyclerView is used to display the data that I fetch from the database but the on RecyclerView, I have 2 rows of the same thing when I select the second option on the Spinner.
I have tried switch loop, changing adapter and changing api url.
Spinner spinner = (Spinner) findViewById(R.id.spinner);
adapterspinner = ArrayAdapter.createFromResource(this,R.array.planets_array,android.R.layout.simple_spinner_item);
adapterspinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapterspinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(i==0)
{
loadt1trolley();
}
if(i==1)
{
loadalltrolley();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
private void loadalltrolley(){
StringRequest stringRequest = new StringRequest(Request.Method.GET, PRODUCT_URL,new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray products = new JSONArray(response);
for(int i =0;i<products.length();i++){
JSONObject productObject = products.getJSONObject(i);
String gate_no = productObject.getString("gate_no");
String dock_name = productObject.getString("dock_name");
String dock_desc = productObject.getString("dock_desc") ;
int flight_arrival = productObject.getInt("flight_arrival");
int trolley_count = productObject.getInt("trolley_count");
Product product = new Product(gate_no,dock_name,dock_desc,flight_arrival,trolley_count);
allterminalList.add(product);
}
allterminaladapter = new ProductAdapter(alert.this,allterminalList);
recyclerView.setAdapter(allterminaladapter);
int count = allterminaladapter.getItemCount();
int i =0;
if (count>0)
{
displayNotification();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(alert.this,error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(this).add(stringRequest);
refresh(6000);
}
private void loadt1trolley(){
StringRequest stringRequest1 = new StringRequest(Request.Method.GET, T1_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray products = new JSONArray(response);
for(int i =0;i<products.length();i++){
JSONObject productObject = products.getJSONObject(i);
String gate_no = productObject.getString("gate_no");
String dock_name = productObject.getString("dock_name");
String dock_desc = productObject.getString("dock_desc") ;
int flight_arrival = productObject.getInt("flight_arrival");
int trolley_count = productObject.getInt("trolley_count");
Product product = new Product(gate_no,dock_name,dock_desc,flight_arrival,trolley_count);
allterminalList.add(product);
}
allterminaladapter = new ProductAdapter(alert.this,allterminalList);
recyclerView.setAdapter(allterminaladapter);
int count = allterminaladapter.getItemCount();
int i =0;
if (count>0)
{
displayNotification();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(alert.this,error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(this).add(stringRequest1);
refresh(6000);
}
I expect the output to display according to the URL display with 1 row each data but it is displaying 2 row when I press position 1 on spinner
You need to clear allterminalList before making a new network request
allterminalList.clear();
if(i==0)
{
loadt1trolley();
}
else if(i==1)
{
loadalltrolley();
}
Add the code in onItemSelected() method of the Spinner, this should fix the issue.
getting response from server id and name,
public class UpcomingRaces extends Fragment {
private static final String TAG = "UpcomingRaces";
UserSessionManager session;
Button btn_selectloc;
TextView mItemSelected;
String[] listItems = {};
boolean[] checkedItems;
ArrayList<Integer> mUserItems = new ArrayList<>();
ArrayList<String> arrayList = new ArrayList<String>();
String[] listItems1 = {};
ArrayList<String> arrayList1 = new ArrayList<String>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_upcoming_races, container, false);
session = new UserSessionManager(getActivity());
btn_selectloc = (Button) rootView.findViewById(R.id.btn_selectloc);
mItemSelected = (TextView) rootView.findViewById(R.id.tvItemSelected);
getLocations();
listItems = arrayList.toArray(new String[Arrays.asList(listItems).size()]);
checkedItems = new boolean[listItems.length];
listItems1 = arrayList1.toArray(new String[Arrays.asList(listItems).size()]);
btn_selectloc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(getActivity());
mBuilder.setTitle(R.string.dialog_title);
mBuilder.setMultiChoiceItems(listItems, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int position, boolean isChecked) {
if(isChecked){
mUserItems.add(position);
}else{
mUserItems.remove((Integer.valueOf(position)));
}
}
});
mBuilder.setCancelable(false);
mBuilder.setPositiveButton(R.string.ok_label, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
String item = "";
String item1 = "";
for (int i = 0; i < mUserItems.size(); i++) {
item = item + listItems[mUserItems.get(i)];
if (i != mUserItems.size() - 1) {
item = item + ", ";
}
item1 = item1 + listItems1[mUserItems.get(i)];
if (i != mUserItems.size() - 1) {
item1 = item1 + ", ";
}
}
mItemSelected.setText(item1);
}
});
AlertDialog mDialog = mBuilder.create();
mDialog.show();
}
});
return rootView;
}
private void getLocations() {
StringRequest stringRequest = new StringRequest("https://jsonplaceholder.typicode.com/posts",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject("{"response":1,"message":"locations success","data":[{"id":7,"name":"123 Middle School"},{"id":8,"name":"ABC Jr High"},{"id":3,"name":"Brentwood High school"},{"id":2,"name":"Clinton Elementary"},{"id":5,"name":"Iowa High School"},{"id":1,"name":"Jfk middle school"},{"id":6,"name":"Terryville Elementary "},{"id":4,"name":"West Jr high"}]}");
if (obj.getString("response").equals("1")) {
//mProgress.dismiss();
JSONArray res = new JSONArray(obj.getString("data"));
for (int i=0; i<res.length(); i++) {
JSONObject result = null;
result = res.getJSONObject(i);
arrayList.add(result.getString("name"));
arrayList1.add(result.getString("id"));
}
} else {
Toast.makeText(getActivity(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
}
I want to show the name in setMultiChoiceItems with boolean checkedItems and I want to append checked "id" to TextView mItemSelected.
Also I want to store that checked id in the session.
I have tried in a many ways and couldn't able to solve this issue..please help me to achieve this.
EDITED
public class MainActivity extends AppCompatActivity {
LinearLayout notification_bar_linearlayout;
TextView txtOutput;
private String DEBUG_TAG = "MOVEMENT";
ArrayList<String> arrayList;
ArrayList<Integer> mUserItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtOutput = (TextView) findViewById(R.id.output);
mUserItems = new ArrayList<>();
StringRequest stringRequest = new StringRequest("your_url_here",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
arrayList = new ArrayList<>();
response = " {\"response\":1,\"message\":\"locations success\",\"data\":[{\"id\":7,\"name\":\"123 Middle School\"},{\"id\":8,\"name\":\"ABC Jr High\"},{\"id\":3,\"name\":\"Brentwood High school\"}]}";
JSONObject obj = new JSONObject(response);
if (obj.getString("response").equals("1")) {
JSONArray res = obj.getJSONArray("data");
for (int i=0; i< res.length(); i++) {
JSONObject val = res.getJSONObject(i);
arrayList.add(val.getString("name"));
}
LoadAlert();
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void LoadAlert()
{
String[] listItems = arrayList.toArray(new String[arrayList.size()]);
boolean[] checkedItems = new boolean[listItems.length];
AlertDialog.Builder mBuilder = new AlertDialog.Builder(this);
mBuilder.setTitle("SELECT ITEMS");
mBuilder.setMultiChoiceItems(listItems, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int position, boolean isChecked) {
if(isChecked){
mUserItems.add(position);
}else{
mUserItems.remove((Integer.valueOf(position)));
}
}
});
mBuilder.setCancelable(false);
mBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
String items = "";
for (int i = 0;i < mUserItems.size();i++)
{
items += "" + mUserItems.get(i) + ", ";
}
txtOutput.setText(items);
}
});
mBuilder.show();
}
Hope it will works.!