JSONArray to a ListView array data not shown - java

i want to when run the app make the jsonRequest without pressing any button and save the data. i just add a method for internet connection check:
if the connection to the internet its true, make the json request pass to the spinner, and save de data.
and when the internet connection its false, just load the data from sharedPreferences to the spinner.
The application runs totally fine with the buttons (with simple onClick methods) and without the verificaConexion method.
But when i remove the buttons, add the verificaConexion method and i have internet connection, just, make the json request, show the data in the spinner and not save the data And when I close the app, remove the wifi, open the app, the spinner shows nothing.
For any reason the methods save and load data doesn't works.
This is my onCreate()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnObtener = (Button) findViewById(R.id.btnObtener);
spDelegaciones = (Spinner)findViewById(R.id.spDelegaciones);
btnGuardar = (Button) findViewById(R.id.btnGuardar);
btnCargar = (Button) findViewById(R.id.btnCargar);
txJsonArray = (TextView) findViewById(R.id.txJsonArray);
verificaConexion(this);
}
This is my json Request method, works fine:
public void request() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(json_url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.e("jsonArray", "" + jsonArray);
if (jsonArray == null) {
Toast.makeText(MainActivity.this, "EL JSONArray esta VACIO !!! ", Toast.LENGTH_SHORT).show();
} else {
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
//con el php JsonArrayRequest2.php
// String contact = jsonObject.getString("delegacion");
//con el php JsonArrayVariosCampos.php
String contact = jsonObject.getString("Delegacion");
arrayList.add(contact);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "ERROR...", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(jsonArrayRequest);
}
my guardarDatos method to save the data:
public boolean guardarDatos(){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor mEdit1 = sp.edit();
/* sKey is an array */
mEdit1.putInt("Status_size", arrayList.size());
for(int i=0;i<arrayList.size();i++)
{
mEdit1.remove("Status_" + i);
mEdit1.putString("Status_" + i, arrayList.get(i));
}
Toast.makeText(MainActivity.this, " DATOS GUARDADOS ", Toast.LENGTH_SHORT).show();
return mEdit1.commit();
}
and my cargarDatos method to load the data:
public void cargarDatos(){
SharedPreferences mSharedPreference1 = PreferenceManager.getDefaultSharedPreferences(this);
arrayList.clear();
int size = mSharedPreference1.getInt("Status_size", 0);
for(int i=0;i<size;i++)
{
arrayList.add(mSharedPreference1.getString("Status_" + i, null));
}
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
spDelegaciones.setAdapter(adapter);
Toast.makeText(MainActivity.this, " DATOS CARGADOS ", Toast.LENGTH_SHORT).show();
}
and here is my class to check the internet connection:
public boolean verificaConexion(Context ctx){
boolean bConectado = false;
ConnectivityManager connec = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] redes = connec.getAllNetworkInfo();
for (int i = 0; i < 2; i++) {
if (redes[i].getState() == NetworkInfo.State.CONNECTED) {
bConectado = true;
if(bConectado) {
Toast.makeText(MainActivity.this, " con conexion ", Toast.LENGTH_LONG).show();
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
spDelegaciones.setAdapter(adapter);
request();
guardarDatos();
}else {
cargarDatos();
}
}else{
}
}
return bConectado;
}

Since you are using only one string in contact class. instead of arrayList<Contact> I will use ArrayList<String>
here I have removed singleTone class. and added jsonArrayRequest code inside in same class. and after adding item in arraylist I have called adapter.notifyDataSetChanged();
MainActivity.class
public class MainActivity extends AppCompatActivity {
TextView txdeleg_lista;
Button btnObtener;
ArrayList<String> arrayList = new ArrayList<String>();
ListView listView;
String json_url = "your url";
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnObtener = (Button) findViewById(R.id.btnObtener);
txdeleg_lista = (TextView) findViewById(R.id.txdeleg_lista);
listView = (ListView) findViewById(R.id.lvDelegacion);
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
btnObtener.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//startActivity(new Intent(MainActivity.this, DesplegarLista.class));
listView.setAdapter(adapter);
request();
}
});
}
public void request() {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(json_url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.e("jsonArray",""+jsonArray);
if(jsonArray == null){
Toast.makeText(MainActivity.this,"EL JSONArray esta VACIO !!! ", Toast.LENGTH_SHORT).show();
}
else {
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String contact = jsonObject.getString("UFULLNAME");
arrayList.add(contact);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,"ERROR...", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(jsonArrayRequest);
}
}
check and if you have any query comment.

Related

ScrollView should scroll to a particular TextView While selecting the same name in Spinner

In my app I want to scroll my ScrollView when I am selecting a text in Spinner upto one particular TextView which contains the text same as selected Spinner text in Android Studio using Java. (you can check image also). Here my spinner is dynamic and my textviews are also dynamic.
My Code - For Spinner
private void spinnerbind() {
JSONObject request = new JSONObject();
try {
request.put("action", "get_spinner");
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsArrayRequest = new JsonObjectRequest
(Request.Method.POST, url,request, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray dataArray = response.getJSONArray("data");
if(response.optString("status").equals("1")){
goodModelArrayList = new ArrayList<>();
//JSONArray dataArray = obj.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
PlayerModel playerModel = new PlayerModel();
JSONObject dataobj = dataArray.getJSONObject(i);
playerModel.setid(dataobj.getString("id"));
playerModel.setTitle(dataobj.getString("specialist"));
goodModelArrayList.add(playerModel);
}
for (int i = 0; i < goodModelArrayList.size(); i++){
names.add(goodModelArrayList.get(i).getTitle().toString());
}
spinnerArrayAdapter = new ArrayAdapter<String>(DoctorsActivity.this, simple_spinner_item, names);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
mySpinner.setAdapter(spinnerArrayAdapter);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
PlayerModel playerModel = goodModelArrayList.get(position);
myid=playerModel.getId();
scrollView.scrollTo(0, 200);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
}
My Code - For Text Binding
public void detailsbind(){
JSONObject docrequest = new JSONObject();
try {
myrequest.put("action", "get_doctors");
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsArrayRequest = new JsonObjectRequest
(Request.Method.POST, url,myrequest, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if(response.optString("status").equals("1")){
// Toast.makeText(getApplicationContext(),response.getString("data"), Toast.LENGTH_SHORT).show();
JSONArray dataSpecArray = response.getJSONArray("data");
LayoutInflater inflater = getLayoutInflater();
for (int k = 0; k < dataSpecArray.length(); k++) {
PlayerModel Specialist = new PlayerModel();
JSONObject specJSONobj = dataSpecArray.getJSONObject(k);
TextView text1 = new TextView(MyActivity.this);
text1.setText(specJSONobj.getString("specialist"));
mainlayout.addView(text1);
}
}else{
Toast.makeText(DoctorsActivity.this, response.optString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
//Display error message whenever an error occurs
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsArrayRequest);
}
scrollview.scrollTo(0, getRelativeTop(textView))
private int getRelativeTop(View textView) {
if (textView.getParent() == textView.getRootView())
return textView.getTop();
else
return textView.getTop() + getRelativeTop((View) textView.getParent());
}

No adapter attached; skipping layout error (with JSON prasing)

I've done everything right but my logcat still shows this error No adapter attached; skipping layout
I have tried setting an empty adapter first inside of onCreate() and adapter.notifyDataSetChanged(); after I get the data in my praseJSON() but still no luck!
Everything in the Recycler adapter file is also set according to all the fix is found online.
private static final String TAG = "Nearby";
private RecyclerView mRecyclerView;
private NearbyAdapter mNearbyAdapter;
private ArrayList<NearbyItem> mNearbyList;
private RequestQueue mRequestQueue;
private LocationManager locationManager;
private String apiURL = "";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby);
mRecyclerView = findViewById(R.id.recyclerViewNearby);
mRecyclerView.setAdapter(mNearbyAdapter);
mNearbyAdapter = new NearbyAdapter(NearbyActivity.this, mNearbyList);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mNearbyList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
{
return;
}
Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
onLocationChanged(location);
}
private void parseJSON()
{
Log.d(TAG, "Starting parseJSON()"+TAG);
String url = apiURL;
Log.d(TAG,"URL: " + url);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
try
{
JSONArray jsonArray = response.getJSONArray("member");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject member = jsonArray.getJSONObject(i);
String nName = "";
String nType = "";
String nDesc = "";
if (member.has("name")){
nName = member.getString("name");
Log.d(TAG, "Name is: " + nName);
}
if(member.has("type")) {
nType = member.getString("type");
Log.d(TAG, "Type is: " + nType);
}
if(member.has("description")){
nDesc = member.getString("description");
Log.d(TAG, "Desc is: " + nDesc);
}
else
{
nDesc += nName;
Log.d(TAG, "Desc is: " + nDesc);
}
if(nType.contains("bus_stop")){
nType = "Bus Stop";
}
else if (nType.contains("train_station"))
{
nType = "Train Station";
}
mNearbyList.add(new NearbyItem(nName, nType, nDesc));
}
mNearbyAdapter.notifyDataSetChanged();
mNearbyAdapter = new NearbyAdapter(NearbyActivity.this, mNearbyList);
mRecyclerView.setAdapter(mNearbyAdapter);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
The problem is that you've set the adapter mNearbyAdapter before creating the NearbyAdapter object.
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby);
mRecyclerView = findViewById(R.id.recyclerViewNearby);
// you passed mNearbyAdapter here
mRecyclerView.setAdapter(mNearbyAdapter);
// but you created the object for it here
mNearbyAdapter = new NearbyAdapter(NearbyActivity.this, mNearbyList);
...
To fix this, create the object for your adapter first, then call setAdapter(mNearbyAdapter).

Getting data from webservice android studio

I am working on an android application. In this application, I have to retrieve data from a web service and put it in a listview, but it is not retrieving anything. I don't know what I am doing wrong here. Maybe someone can help me with this.
Webservice: http://10.247.240.53/kas/lampen.php
Mainactivity:
`
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayAdapter<String> adapter;
String[] data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listview);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
getData();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Showdata.class);
intent.putExtra("teeltbed", listView.getItemAtPosition(position).toString());
startActivity(intent);
}
});
}
private void getData()
{
String getData = null;
String dbResult = "empty";
dbConnect database = new dbConnect(this);
try{
String query = "SELECT * FROM Lamp";
getData = "?query=" + URLEncoder.encode(query, "UTF-8");
String link = "http://10.247.240.53/kas/lampen.php";
dbResult = database.execute(link).get();
}
catch (Exception e){
}
try{
JSONArray ja = new JSONArray(dbResult);
JSONObject jo = null;
data = new String[ja.length()];
for (int i = 0; i < ja.length(); i++)
{
jo = ja.getJSONObject(i);
data[i] = jo.getString("teeltbed");
}
adapter = new ArrayAdapter<String>(this, R.layout.layout_list, R.id.list_item, data);
listView.setAdapter(adapter);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}`

No adapter attached; skipping layout - beginner issue

Im using volley to download the JSON data from a server, setting the Adapter within the function that reads and parses the data. However, the adapter is not being recognized. The problem is, I have successfully implemented the adapter in another activity with the same method without errors. The following is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras!=null) {
user_id = getIntent().getStringExtra("user_id");
} else {
Intent logIn = new Intent(JoinedActivity.this, LoginActivity.class);
startActivity(logIn);
}
setContentView(R.layout.activity_joined);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(this));
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
GetJoinedEvents();
}
public void GetJoinedEvents(){
String tag_string_req = "req_getJoinedEvents";
StringRequest stringRequest = new StringRequest(Request.Method.GET, Config.URL_USER_lIST_EVENTS+user_id, new Response.Listener<String>(){
#Override
public void onResponse(String response) {
// progressDialog.dismiss();
Log.i("responseTest",response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
int length = result.length();
HashMap<String, String> events;
for (int i = 0; i < length; i++) {
JSONObject jo = result.getJSONObject(i);
String event_id = jo.getString(Config.TAG_EVENT_ID);
String name = jo.getString(Config.TAG_EVENT_NAME);
String date = jo.getString(Config.TAG_EVENT_START_DT);
String weekday = jo.getString(Config.TAG_EVENT_WEEKDAY);
String event_type = jo.getString(Config.TAG_EVENT_TYPE);
events = new HashMap<>();
events.put(Config.TAG_EVENT_ID, event_id);
events.put(Config.TAG_EVENT_NAME, name);
events.put(Config.TAG_EVENT_START_DT, date);
events.put(Config.TAG_EVENT_WEEKDAY, weekday);
events.put(Config.TAG_EVENT_TYPE, event_type);
eventList.add(events);
}
listAdapter = new RecyclerViewAdapter(JoinedActivity.this,eventList, user_id);
recyclerView.setAdapter(listAdapter);
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", "Bad internet connection");
}
}) {};
AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
Log.i("URL", stringRequest.toString());
}
}
A better approach to this is just to initialize the Recycler view and adapter on the onCreate. Then later on when you have the data you could create a swapItems method just for the purpose of changing the data within the recyclerview through the adapter, but in a way that both the RecyclerView and its adapter is instantiated as the activity starts.
on your swapItems you could do something like below:
public void swapItems(List<Events> eventList) {
if (eventList != null) {
this.items = eventList;
notifyDataSetChanged();// should call this to let the recyclerview know that our data set has changed
}
}
Then you could just call it via the activity by
listAdapter.swapItems(eventList);// this is done the moment you already got your list of events

how can i send data from editText of dialog box whose context is in mainactivity using json object?

While submitting data from editTexts of Dialog box whose context is in Home activity, the submitted button doing nothing.
host is a button on home activity,when clicked opens up a dialog box in same activity consists of two editText field (ename,eemail) and submit , cancel button. On submit getFeedback() functions called (used from ApiInterface method)
host.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view)
{
final Dialog d=new Dialog(context);
d.setCanceledOnTouchOutside(false);
d.setContentView(R.layout.hostdialog);
d.getWindow().setBackgroundDrawableResource(R.drawable.bgdialog);
final EditText ename=(EditText)d.findViewById(R.id.ename);
final EditText eemail=(EditText)d.findViewById(R.id.eemail);
final Button submit=(Button)d.findViewById(R.id.submit);
final Button clear=(Button)d.findViewById(R.id.clear);
submit.setOnClickListener(new View.OnClickListener() {
#SuppressLint("WrongConstant")
#Override
public void onClick(View view) {
try {
getFeedbacks(ename.getText().toString(),eemail.getText().toString());
d.dismiss();
Toast t = Toast.makeText(getApplicationContext()," ✓ Thank You, We'll contact you soon",Toast.LENGTH_LONG);
View v = t.getView();
v.setBackgroundResource(R.drawable.clear);
t.show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
d.dismiss();
}
});
d.show();
}
});
and my ApiInterface code is:
#GET("myurl")
Call<JsonElement> getFeedbacks(#Body RequestBody requestBody);
getFeedback method consist of:-
private void getFeedbacks(String user_name, String user_email){
JSONObject paramobject = new JSONObject();
try {
paramobject.put("user_name",user_name);
paramobject.put("user_email",user_email);
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody body = RequestBody.create(MediaType.parse("application/json,charset=utf-8"),paramobject.toString());
Call<JsonElement> call = retrofitAPI.getFeedbacks(body);
call.enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
try {
JSONArray jsonArray = new JSONArray(response.body().toString());
JSONObject jsonObject = new JSONObject();
for (int n = 0; n < jsonArray.length(); n++){
jsonObject = jsonArray.getJSONObject(n);
String successval = jsonObject.optString("success");
if(successval.equals("0")){
Toast t=Toast.makeText(getApplicationContext()," Request Failed, Try Again",Toast.LENGTH_LONG);
View v=t.getView();
v.setBackgroundResource(R.drawable.clear);
t.show();
}else {
Toast t=Toast.makeText(getApplicationContext()," ✓ Thank You, We'll contact you soon",Toast.LENGTH_LONG);
View v=t.getView();
v.setBackgroundResource(R.drawable.clear);
t.show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<JsonElement> call, Throwable t) {
Toast.makeText(Home.this,"Error,Try Again",Toast.LENGTH_LONG).show();
}
});
}
Button does not works. Please provide appropriate solution.
now i alter a little bit code as i change the call anonymously within method. but again no work
host.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Dialog d = new Dialog(context);
d.setCanceledOnTouchOutside(false);
d.setContentView(R.layout.hostdialog);
d.getWindow().setBackgroundDrawableResource(R.drawable.bgdialog);
final EditText ename = (EditText) d.findViewById(R.id.ename);
final EditText eemail = (EditText) d.findViewById(R.id.eemail);
final Button submit = (Button) d.findViewById(R.id.submit);
final Button clear = (Button) d.findViewById(R.id.clear);
submit.setOnClickListener(new View.OnClickListener() {
#SuppressLint("WrongConstant")
#Override
public void onClick(View view) {
try {
sendDataToServer();
d.dismiss();
Toast t = Toast.makeText(getApplicationContext(), " ✓ Thank You, We'll contact you soon", Toast.LENGTH_LONG);
View v = t.getView();
v.setBackgroundResource(R.drawable.clear);
t.show();
} catch (Exception e) {
e.printStackTrace();
}
}
private void sendDataToServer() {
JSONObject paramobject = new JSONObject();
try {
paramobject.put("comment", ename);
paramobject.put("email", eemail);
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody body = RequestBody.create(MediaType.parse("application/json,charset=utf-8"), paramobject.toString());
Call<JsonElement> call = retrofitAPI.getFuturehosts((RequestBody) body);
call.enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
try {
JSONArray jsonArray = new JSONArray(response.body().toString());
JSONObject jsonObject = new JSONObject();
for (int n = 0; n < jsonArray.length(); n++) {
jsonObject = jsonArray.getJSONObject(n);
String successval = jsonObject.optString("success");
if (successval.equals("0")) {
Toast t = Toast.makeText(getApplicationContext(), " Request Failed, Try Again", Toast.LENGTH_LONG);
View v = t.getView();
v.setBackgroundResource(R.drawable.clear);
t.show();
} else {
Toast t = Toast.makeText(getApplicationContext(), " ✓ Thank You, We'll contact you soon", Toast.LENGTH_LONG);
View v = t.getView();
v.setBackgroundResource(R.drawable.clear);
t.show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<JsonElement> call, Throwable t) {
Toast.makeText(Home.this, "Error,Try Again", Toast.LENGTH_LONG).show();
}
});
}
});
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
d.dismiss();
}
});
d.show();
}
});
Check your hostdialog.xml file
-button id is "submit" or not
may be that id is diffrent so the code is not working

Categories