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();
}
}
Related
I have an activity where I have a URL and with the Volley Library , I am fetching the JSON data in an ArrayList of Objects of Model Class DmIncomingTest. Now, I pas URL to the checkLiveQuiz() method, even after getting data from server and adding it to the ArrayList, the size of ArrayList is always 0. I am sharing the code here:
private List<DmInComingTest> inComingTestList;
setContentView(R.layout.activity_no_live_quiz);
......
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
private Context context;
#Override
protected void onPreExecute() {
inComingTestList= new ArrayList<DmInComingTest>();
// dialog = ProgressDialog.show(NoLiveQuiz.this, "Please wait..", "Doing stuff..", true);
}
#Override
protected Void doInBackground(Void... voids) {
checkLiveQuiz();
return null;
}
#Override
protected void onPostExecute(Void result) {
// Toast.makeText(NoLiveQuiz.this,"Size of inComingTestList :"+inComingTestList.size(),Toast.LENGTH_LONG).show();
if(inComingTestList.size()==0)
{
Toast.makeText(NoLiveQuiz.this,"Size of inComingTestList :"+inComingTestList.size(),Toast.LENGTH_LONG).show();
}
else
{
startActivity(new Intent(NoLiveQuiz.this,LiveQuiz.class));
}
// dialog.dismiss();
}
}
public void checkLiveQuiz()
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url_live_quiz, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
DmInComingTest inComingTest = new DmInComingTest();
inComingTest.setTitle(jsonObject.getString("title"));
inComingTest.setTotal_questions(jsonObject.getString("qcount"));
inComingTest.setDated(jsonObject.getString("date_format(dated,'%d.%m.%Y')"));
inComingTest.setStartTime(jsonObject.getString("starttime"));
inComingTest.setEndTime(jsonObject.getString("endtime"));
inComingTest.setDuration(jsonObject.getInt("duration"));
inComingTest.setMaxMarks(jsonObject.getInt("maxmarks"));
if(validateTest(jsonObject.getString("date_format(dated,'%d.%m.%Y')"),jsonObject.getString("starttime"),jsonObject.getString("endtime"),jsonObject.getInt("duration")))
{
inComingTestList.add(inComingTest);
Toast.makeText(NoLiveQuiz.this,"Test Added: "+ inComingTestList.size(),Toast.LENGTH_LONG).show();
// flag=1;
// Toast.makeText(MainActivity.this,"Flag Inner="+flag,Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
}
}
// adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
// progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
private boolean validateTest(String testDate, String startTime, String endTime, int duration)
{
Date oldDate, newDate,newDate1;
String oldTime,newTime,newTime1;
long diff=0;
long oldLong=0;
long newLong=0;
long newLong1=0;
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss");
formatter.setLenient(false);
Calendar c = Calendar.getInstance();
oldTime=formatter.format(c.getTime());
// Toast.makeText(MainActivity.this, ""+oldTime, Toast.LENGTH_SHORT).show();
newTime=testDate +", "+startTime+":00";
newTime1=testDate +", "+endTime+":00";
// Toast.makeText(MainActivity.this, ""+newTime, Toast.LENGTH_SHORT).show();
try {
oldDate = formatter.parse(oldTime);
newDate = formatter.parse(newTime);
newDate1=formatter.parse(newTime1);
oldLong = oldDate.getTime();
newLong = newDate.getTime();
newLong1=newDate1.getTime();
diff = newLong - oldLong;
} catch (ParseException e) {
e.printStackTrace();
}
//long timer= (long) Long.parseLong(String.valueOf(diff));
//Toast.makeText(IncomingActivity.this, ""+timer, Toast.LENGTH_SHORT).show();
if(oldLong>newLong && oldLong<newLong1)
{
return true;
}
else
return false;
}
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.!
After a long search on the internet I couldn't find any solution to meet my requirements.
I have one array list which is passed into the dialog fragment, but my requirement is:
When the user selects the date it calls the web service again and gets another data according to data and passes the same dialog fragment. How can I achieve that ? I have tried with static value but its not clearing the value. My code is:
public static class DatePickerDialogFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener
{
String userName;
public interface UserUserIdListener {
void updateIdUserName(String userName);
}
public static final int FLAG_START_DATE = 0;
public static final int FLAG_END_DATE = 1;
public static List<Orederlist>reportorderIdList=new ArrayList<>();
// private List<Userlist> reportUserList = new ArrayList<>();
private int flag = 0;
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void setFlag(int i) {
flag = i;
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar calendar = Calendar.getInstance();
Calendar calendar1=Calendar.getInstance();
calendar1.set(year, monthOfYear, dayOfMonth);
calendar.set(year, monthOfYear, dayOfMonth);
String reportOrderIds="";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
if (flag == FLAG_START_DATE) {
textviewFromDate.setText(format.format(calendar.getTime()));
fromDateReport=textviewFromDate.getText().toString();
JSONObject pieObject = new JSONObject();
try
{
pieObject.put("fromDate",""+fromDateReport);
pieObject.put("orderId",""+reportOrderIds);
pieObject.put("password",""+sPrefs.getString(Constants.PASSWORD,""));
pieObject.put("toDate",""+toDateReport);
pieObject.put("user",""+sPrefs.getString(Constants.USER_NAME,""));
pieObject.put("subUser",""+reportSubUsers);
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading....");
progressDialog.setCancelable(false);
progressDialog.show();
} catch (Exception e)
{
e.printStackTrace();
}
// String TAG = "delivered";
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonObjectRequest jsOnbjRequest = new
JsonObjectRequest(Request.Method.POST,
Constants.GetSummarizedReports, pieObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
progressDialog.dismiss();
try {
JSONArray jsonArray = (JSONArray) response.get("orderlist");
{
if (jsonArray.length()>0)
{
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
// Integer name = json.optInt();
String name = json.optString("orderId").toString();
Orederlist user = new Orederlist(name);
user.setOrderId(name);
reportorderIdList.add(user);
}}
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
};
jsOnbjRequest.setRetryPolicy(new DefaultRetryPolicy(500000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsOnbjRequest);
} else if (flag == FLAG_END_DATE) {
textviewToDate.setText(format.format( calendar1.getTime()));
toDateReport= textviewToDate.getText().toString();
JSONObject pieObject = new JSONObject();
try
{
pieObject.put("fromDate",""+fromDateReport);
pieObject.put("orderId",""+reportOrderIds);
pieObject.put("password",""+sPrefs.getString(Constants.PASSWORD,""));
pieObject.put("toDate",""+toDateReport);
pieObject.put("user",""+sPrefs.getString(Constants.USER_NAME,""));
pieObject.put("subUser",""+reportSubUsers);
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading....");
progressDialog.setCancelable(false);
progressDialog.show();
} catch (Exception e)
{
e.printStackTrace();
}
// String TAG = "delivered";
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonObjectRequest jsOnbjRequest = new
JsonObjectRequest(Request.Method.POST,
Constants.GetSummarizedReports, pieObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
progressDialog.dismiss();
try {
JSONArray jsonArray = (JSONArray) response.get("orderlist");
{
if (jsonArray.length()>0)
{
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
// Integer name = json.optInt();
String name = json.optString("orderId").toString();
Orederlist user = new Orederlist(name);
user.setOrderId(name);
reportorderIdList.add(user);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
};
jsOnbjRequest.setRetryPolicy(new DefaultRetryPolicy(500000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsOnbjRequest);
}
}
}
and for dialog fragment pass data is :
FragmentManager managerOrderIds = getSupportFragmentManager();
UserJobIds dialogOrderIds = new UserJobIds();
dialogOrderIds.setdata(orderIdList,reportorderIdList);//with static array list which is not claer the value
dialogOrderIds.show(managerOrderIds, "Dialog");
What you can do is just create a newInstance of Dialog Fragment assign data to it, then call show().Below is an example.
public class D2Fragment extends DialogFragment {
private ArrayList<String> list;
public static D2Fragment getInstanceFor(ArrayList<String> list){
D2Fragment d2Fragment=new D2Fragment();
d2Fragment.list=list;
return d2Fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.item_dialog, container,
false);
getDialog().setTitle("DialogFragment Sample");
Log.e("size",list.size()+"");// Here is the list
// Do something else
return rootView;
}
}
When you show dialog.
ArrayList<String> list=new ArrayList<>();
list.add("Val1");
list.add("Val2");
D2Fragment d2Fragment=D2Fragment.getInstanceFor(list);
d2Fragment.show(getSupportFragmentManager(),"dialog2");
Or just create a setter for your data.
public class D2Fragment extends DialogFragment {
private ArrayList<String> list;
public void setData(ArrayList<String> list){
this.list=list;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.item_dialog, container,
false);
getDialog().setTitle("DialogFragment Sample");
Log.e("size",list.size()+"");// Here is the list
// Do something else
return rootView;
}
}
and to show Dialog.
ArrayList<String> list = new ArrayList<>();
list.add("Val1");
list.add("Val2");
D2Fragment d2Fragment = new D2Fragment();
d2Fragment.setData(list);
d2Fragment.show(getSupportFragmentManager(), "dialog2");
In activity you can always find that particular DialgFragment by tag you assigned at the time of transaction.
Fragment fragment=getSupportFragmentManager().findFragmentByTag("dialog2");
if(fragment!=null && fragment instanceof D2Fragment){
((D2Fragment)fragment).call();// You can call any public method of this dialog fragment here
}
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);
}});