i am trying to populate a spinner from a URl but i cant get the elements on to spinner using the GET method...my POST method works well to do the registration...But cant GET data to spinner...this is my code
public class SuppRegActivity extends AppCompatActivity implements RegistrationView,View.OnClickListener {
EditText company_name,code,Add1,Add2,Add3,Add4,Tel_no,mob_no,email,contact_person,tin_no,password;
Spinner state;
Button save;
ArrayList<String> mystates;
ArrayList<JSONObject> err;
String Get_company_name,Get_code,Get_Add1,Get_Add2,Get_Add3,Get_Add4,Get_Telno,
Get_mobno,Get_email,Get_contactp,Get_tinno,Get_password,Get_state;
RegistrationPresenter registrationPresenter;
ProgressDialog progressDialog;
View v;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_supp_reg);
company_name = (EditText) findViewById(R.id.suppname);
code = (EditText) findViewById(R.id.suppcode);
Add1 = (EditText) findViewById(R.id.Add1);
Add2 = (EditText) findViewById(R.id.Add2);
Add3 = (EditText) findViewById(R.id.Add3);
Add4 = (EditText) findViewById(R.id.Add4);
Tel_no = (EditText) findViewById(R.id.suppPhone);
mob_no = (EditText) findViewById(R.id.SuppMob);
email = (EditText) findViewById(R.id.suppEmail);
contact_person= (EditText) findViewById(R.id.SuppPerson);
tin_no = (EditText) findViewById(R.id.SuppTin);
password = (EditText) findViewById(R.id.suppPass);
state = (Spinner) findViewById(R.id.suppstate);
save = (Button) findViewById(R.id.Saveregister);
save.setOnClickListener(this);
//arr = new ArrayList<JSONObject>();
registrationPresenter = new RegistrationPresenterImpl(this, SuppRegActivity.this);
}
#Override
public void onClick(View view) {
Get_company_name = company_name.getText().toString();
Get_Add1 = Add1.getText().toString();
Get_Add2 = Add2.getText().toString();
Get_Add3 = Add3.getText().toString();
Get_Add4 = Add4.getText().toString();
Get_state = state.getSelectedItem().toString();
Get_Telno = Tel_no.getText().toString();
Get_mobno = mob_no.getText().toString();
Get_email = email.getText().toString();
Get_contactp = contact_person.getText().toString();
Get_tinno = tin_no.getText().toString();
Get_code = code.getText().toString();
Get_password = password.getText().toString();
if(!Get_company_name.equals("")){
if(!Get_Add1.equals("")){
if(!Get_Add2.equals("")){
if(!Get_Add3.equals("")){
if(!Get_Add4.equals("")){
if(!Get_state.equals("")){
if(!Get_Telno.equals("")){
if(Get_Telno.length() ==10 ){
if(!Get_mobno.equals("")){
if(Get_mobno.length() == 10){
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if(Get_email.matches(emailPattern)){
if(!Get_contactp.equals("")){
if(!Get_tinno.equals("")){
if(!Get_code.equals("")){
if(!password.equals("")){
doRegisteration(Get_company_name,Get_code,Get_Add1,Get_Add2,Get_Add3,Get_Add4,Get_state,Get_Telno,Get_mobno,Get_email,Get_contactp,
Get_tinno,Get_password);
}else{
showFailedAlertBox("Password in Required");
}
}else{
showFailedAlertBox("user name is required");
}
}else{
showFailedAlertBox("enter Tin No.");
}
}else{
showFailedAlertBox("enter contact person");
}
}else{
showFailedAlertBox("invalid email");
}
}else{
showFailedAlertBox("enter 10 digit phone no");
}
}else{
showFailedAlertBox("enter mobile no");
}
}else{
showFailedAlertBox("enter 10 digit phone no.");
}
}else{
showFailedAlertBox("enter mobile no");
}
}else{
showFailedAlertBox("State not selected");
}
}else{
showFailedAlertBox("Address line 4 required");
}
}else{
showFailedAlertBox("Address line 3 required");
}
}else{
showFailedAlertBox("Address line 2 required");
}
}else{
showFailedAlertBox("Address line 1 required");
}
}else{
showFailedAlertBox("Company name is required");
}
}
private void showSuccessAlertBox(final String v) {
new AlertDialog.Builder(this).setMessage(v)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (v.equals("Registration Done")) {
/* // String uNameForIntent = company_name.getText().toString().trim();
Intent intent = new Intent(SuppRegActivity.this, MainActivity.class);
// intent.putExtra("uname", uNameForIntent);
startActivity(intent);*/
}
else{
return;
}
}
}).show();
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public void doRegisteration(String companyname, String code, String Add1, String Add2, String Add3, String Add4, String State, String tel_no,
String mobileno, String email, String contactp, String tinno, String password){
/*JSONObject stat = new JSONObject();
try{
JSONObject a = stat.getJSONObject("getAllState");
for(int i=0;i<a.length();i++) {
JSONObject c=(JSONObject) a.get(i);
}
} catch (JSONException e) {
e.printStackTrace();
}*/
JSONObject register= new JSONObject();
try {
register.put("FullName",Get_company_name);
register.put("Alias",Get_code);
register.put("Add1", Get_Add1);
register.put("Add2", Get_Add2);
register.put("Add3", Get_Add3);
register.put("Add4", Get_Add4);
register.put("State",Get_state);
register.put("TelNo",Get_Telno);
register.put("mobile", Get_mobno);
register.put("email", Get_email);
register.put("TinNo",Get_tinno);
register.put("ContactPerson", Get_contactp);
register.put("Password", Get_password);
JSONObject s = register.getJSONObject("http://.............................../getAllState");
err = new ArrayList<JSONObject>();
err.add(s);
ArrayAdapter<JSONObject> adapter = new ArrayAdapter<JSONObject>(this,android.R.layout.simple_spinner_item,err);
state.setAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String REGISTER_URL =" http://........................../AddAccount";
//String STATE_URL = "http://.........................../getAllState";
showProgress();
/*JsonObjectRequest statelist = new JsonObjectRequest(Request.Method.GET, STATE_URL, stat,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
state.setAdapter(new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item,arr));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});*/
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, REGISTER_URL,register,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject j = null;
String result = null;
try {
result = response.getString("Result");
} catch (JSONException e) {
e.printStackTrace();
}
if (result.equals("Saved")) {
showSuccessAlertBox("Registration Done");
//volleyForProfile(sessionManager.getUserName());
}
else
showFailedAlertBox("Failed Process!!!Try Again");
hidePregress();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hidePregress();
}
}
);
request.setRetryPolicy(new DefaultRetryPolicy(
30000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleyApplication.getInstance().getRequestQueue().add(request);
}
private void showFailedAlertBox(String v) {
new AlertDialog.Builder(this).setMessage(v)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).show();
}
#Override
public void showProgress() {
progressDialog = ProgressDialog.show(SuppRegActivity.this, "Please Wait",
"Processing...", true);
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
}
#Override
public void hidePregress() {
progressDialog.dismiss();
}
#Override
public void setErrorOnEditText() {
/*Snackbar.make(v, msg, Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
showSuccessAlertBox(msg);*/
}
#Override
public void savedMsg(String msg) {
}
}
where REGISTER_URL uses the post method....and STATE_URL uses the GET Method...
First instead of accepting response as JSON object use instance of a custom POJO class of your own depending on your requirements. And secondly you can create a custom adapter class for populating your spinner.
If you have a small requirement like mentioned above I'd suggest you should use Retrofit instead of Volley which is lightweight and fast.
Related
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 some problem about setting and getting id from data that showed with volley JSon array request.
I've tried to do this, but it fail.
ChildTidur.java
public class ChildTidur extends AppCompatActivity implements TidurAdapter.ContactsAdapterListener {
private static final String TAG = ChildTidur.class.getSimpleName();
private RecyclerView recyclerView;
private List<Story> storyList;
private TidurAdapter mAdapter;
private SearchView searchView;
private TextView noFavtsTV;
private AppPreferences appPreferences;
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 2000;
public static final int READ_TIMEOUT = 2000;
final String KEY_SAVED_RADIO_BUTTON_INDEX = "SAVED_RADIO_BUTTON_INDEX";
// url to fetch contacts json
private static final String URL = "https://api.kafeinkode.com/childtidur.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.child_tidur);
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
SwipeRefreshLayout pullToRefresh = findViewById(R.id.pullToRefresh);
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
finish();
startActivity(getIntent());
}
});
//toolbar logo and desc
Toolbar topToolBar = (Toolbar) findViewById(R.id.toolbarTidur);
setSupportActionBar(topToolBar); //munculkan menu ke toolbar
getSupportActionBar().setDisplayHomeAsUpEnabled(true); //this line shows back button
recyclerView = findViewById(R.id.recycler_view);
noFavtsTV = findViewById(R.id.no_favt_text);
storyList = new ArrayList<>();
mAdapter = new TidurAdapter(this, storyList, this, appPreferences);
// white background notification bar
whiteNotificationBar(recyclerView);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new TidurDekor(this, DividerItemDecoration.VERTICAL, 36));
recyclerView.setAdapter(mAdapter);
//Make call to AsyncTask
new AsyncLogin().execute();
//Get radio button value
LoadPreferences();
} //OnCreate
private void showNoFavtText(boolean show) {
noFavtsTV.setVisibility(show ? View.VISIBLE : View.GONE); //jika data yang ditampilkan tidak ada, maka show noFavsTv
recyclerView.setVisibility(show ? View.GONE : View.VISIBLE); //jika data yang ditampilkan tidak ada, maka don't show rV
}
private void LoadPreferences(){
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(R.layout.activity_settings, null,false);
RadioGroup radioGroup = (RadioGroup)contentView.findViewById(R.id.radioSex);
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
int savedRadioIndex = sharedPreferences.getInt(KEY_SAVED_RADIO_BUTTON_INDEX, 0);
RadioButton savedCheckedRadioButton = (RadioButton)radioGroup.getChildAt(savedRadioIndex);
savedCheckedRadioButton.setChecked(true);
RadioGroup genderGroup = (RadioGroup) contentView.findViewById(R.id.radioSex);
RadioButton male = (RadioButton) contentView.findViewById(R.id.theme1);
RadioButton female = (RadioButton) contentView.findViewById(R.id.theme2);
if (genderGroup.getCheckedRadioButtonId() == -1) {
Toolbar tb = (Toolbar) findViewById(R.id.toolbarTidur);
tb.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
}
else {
if (male.isChecked()) { // one of the radio buttons is checked
Toolbar tb1 = (Toolbar) findViewById(R.id.toolbarTidur);
tb1.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
}
else if (female.isChecked()) {
Toolbar tb2 = (Toolbar) findViewById(R.id.toolbarTidur);
tb2.setBackgroundColor(getResources().getColor(R.color.colorAccent));
}
}
}
private class AsyncLogin extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(ChildTidur.this);
HttpURLConnection conn;
java.net.URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
showNoFavtText(false);
pdLoading.setMessage("\tMencoba terhubung ke internet...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL("https://api.kafeinkode.com/childtidur.json");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("koneksi gagal");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
/**
* fetches json by making http calls
*/
protected void onPostExecute(String result) {
JsonArrayRequest request = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
pdLoading.dismiss();
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
List<Story> items = new Gson().fromJson(response.toString(), new TypeToken<List<Story>>() {
}.getType());
// adding contacts to contacts list
storyList.clear();
storyList.addAll(items);
// refreshing recycler view
mAdapter.notifyDataSetChanged();
for (int i=0; i<storyList.size(); i++) {
Story story = new Story();
story.setIdStory(String.valueOf(i));
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pdLoading.dismiss();
// error in getting json
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Tidak bisa menampilkan data. Periksa kembali sambungan internet Anda", Toast.LENGTH_LONG).show();
AlertDialog alertDialog = new AlertDialog.Builder(ChildTidur.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Data Tidak bisa ditampilkan. Periksa kembali sambungan internet Anda");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
showNoFavtText(true);
}
});
TidurSearch.getInstance().addToRequestQueue(request);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_tidur, menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
// Associate searchable_tidur configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search2).getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
// listening to search query text change
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// filter recycler view when query submitted
mAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
// filter recycler view when text is changed
mAdapter.getFilter().filter(query);
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search2) {
return true;
}
//Menu
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
else
if (id == R.id.about_us) {
startActivity(new Intent(this, AboutUs.class));
return true;
}
else
if (id == R.id.favlist) {
startActivity(new Intent(this, ShowFavouriteList.class));
return true;
}
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// close search view on back button pressed
if (!searchView.isIconified()) {
searchView.setIconified(true);
return;
}
super.onBackPressed();
}
private void whiteNotificationBar(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int flags = view.getSystemUiVisibility();
flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
view.setSystemUiVisibility(flags);
getWindow().setStatusBarColor(Color.WHITE);
}
}
#Override
public void onContactSelected(Story story) {
Toast.makeText(getApplicationContext(), "Selected: " + story.getName(), Toast.LENGTH_LONG).show();
}
}
TidurAdapter.java
public void onClick(View view) {
// Another problem lays here when I get id of data
Story story = storyList.get(getLayoutPosition());
int ambilId = Integer.parseInt(story.getIdStory());
if ( 0 == ambilId ) {
Intent myIntent = new Intent(view.getContext(), DoaMauTidur.class);
view.getContext().startActivity(myIntent);
}
else if ( 1 == getAdapterPosition() )
{
Intent myIntent = new Intent(view.getContext(), DoaBangunt.class);
view.getContext().startActivity(myIntent);
}
else if ( 2 == getAdapterPosition() )
{
Intent myIntent = new Intent(view.getContext(), DoaJimak.class);
view.getContext().startActivity(myIntent);
}
}
This is a full code:
Story.java
public Story(){}
String name;
String nomor;
private String idStory;
private int isLiked;
public String getName() {
return name;
}
public String getNomor() { return nomor; }
public void setIdStory(String isStory) {
this.idStory = isStory;
}
public String getIdStory() {
return idStory;
}
public void setIsLiked(int isLiked) {
this.isLiked = isLiked;
}
public int getIsLiked() {
return isLiked;
}
}
ChildTidur.java
/**
* fetches json by making http calls
*/
protected void onPostExecute(String result) {
JsonArrayRequest request = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
pdLoading.dismiss();
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
List<Story> items = new Gson().fromJson(response.toString(), new TypeToken<List<Story>>() {
}.getType());
// adding contacts to contacts list
storyList.clear();
storyList.addAll(items);
// refreshing recycler view
mAdapter.notifyDataSetChanged();
for (int i=0; i<storyList.size(); i++) {
Story story = new Story();
story.setIdStory(String.valueOf(i));
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pdLoading.dismiss();
// error in getting json
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Tidak bisa menampilkan data. Periksa kembali sambungan internet Anda", Toast.LENGTH_LONG).show();
AlertDialog alertDialog = new AlertDialog.Builder(ChildTidur.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Data Tidak bisa ditampilkan. Periksa kembali sambungan internet Anda");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
showNoFavtText(true);
}
});
TidurSearch.getInstance().addToRequestQueue(request);
}
}
TidurAdapter.java
public class TidurAdapter extends RecyclerView.Adapter<TidurAdapter.TidurViewHolder> implements Filterable {
private Context context;
private List<Story> storyList;
private List<Story> storyListFiltered;
private ContactsAdapterListener listener;
private int changedItemPosition;
public boolean isLiked;
private AppPreferences appPreferences;
Boolean checked = false;
public TidurAdapter(Context context, List<Story> storyList, ContactsAdapterListener listener, AppPreferences appPreferences) {
this.context = context;
this.listener = listener;
this.storyList = storyList;
this.storyListFiltered = storyList;
this.appPreferences = appPreferences;
}
#Override
public TidurViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.child_row_item_tidur, parent, false);
return new TidurViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull TidurViewHolder holder, int position) {
final Story story = storyListFiltered.get(position);
holder.name.setText(story.getName());
holder.nomor.setText(story.getNomor());
holder.setViewData(storyList.get(position), holder.getAdapterPosition());
}
#Override
public int getItemCount() {
return storyListFiltered.size();
}
public interface ContactsAdapterListener {
void onContactSelected(Story story);
}
//ViewHolder
public class TidurViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView nomor;
public ImageView mFavorite;
private CheckBox likeCheckBox;
final String KEY_SAVED_RADIO_BUTTON_INDEX = "SAVED_RADIO_BUTTON_INDEX";
public TidurViewHolder(View view) {
super(view);
name = view.findViewById(R.id.name);
nomor = view.findViewById(R.id.nomor);
likeCheckBox = itemView.findViewById(R.id.like_button_cb);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// get id of data
Story story = storyList.get(getLayoutPosition());
int ambilId = Integer.parseInt(story.getIdStory());
if ( 0 == ambilId ) {
Intent myIntent = new Intent(view.getContext(), DoaMauTidur.class);
view.getContext().startActivity(myIntent);
}
else if ( 1 == getAdapterPosition() )
{
Intent myIntent = new Intent(view.getContext(), DoaBangunt.class);
view.getContext().startActivity(myIntent);
}
else if ( 2 == getAdapterPosition() )
{
Intent myIntent = new Intent(view.getContext(), DoaJimak.class);
view.getContext().startActivity(myIntent);
}
}
});
//Get radio button value
LayoutInflater inflater = (LayoutInflater) view.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View cV = inflater.inflate(R.layout.activity_settings, null,false);
RadioGroup radioGroup = (RadioGroup)cV.findViewById(R.id.radioSex);
SharedPreferences sharedPreferences = view.getContext().getSharedPreferences("MY_SHARED_PREF", Activity.MODE_PRIVATE);
int savedRadioIndex = sharedPreferences.getInt(KEY_SAVED_RADIO_BUTTON_INDEX, 0);
RadioButton savedCheckedRadioButton = (RadioButton)radioGroup.getChildAt(savedRadioIndex);
savedCheckedRadioButton.setChecked(true);
RadioGroup genderGroup = (RadioGroup) cV.findViewById(R.id.radioSex);
RadioButton male = (RadioButton) cV.findViewById(R.id.theme1);
RadioButton female = (RadioButton) cV.findViewById(R.id.theme2);
if (genderGroup.getCheckedRadioButtonId() == -1) {
nomor.setBackgroundColor(view.getResources().getColor(R.color.colorPrimaryDark));
} else {
if (male.isChecked()) { // one of the radio buttons is checked
nomor.setBackgroundDrawable(ContextCompat.getDrawable(view.getContext(), R.drawable.rounded_drawable));
}
else if (female.isChecked()) {
nomor.setBackgroundDrawable(ContextCompat.getDrawable(view.getContext(), R.drawable.rounded_drawable_red));
}
}
} //TidurViewHolder(View view)
public void setViewData(final Story story, final int adapterPosition) {
if (story.getIsLiked() == 1) {
likeCheckBox.setChecked(true);
}
else {
likeCheckBox.setChecked(false);
}
likeCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
changedItemPosition = adapterPosition;
if (buttonView.isPressed()) {
if (isChecked) {
isLiked = true;
updateLikes();
appPreferences.saveFavouriteCard(story);
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
}
else {
isLiked = false;
updateLikes();
appPreferences.deleteCard(story.getIdStory());
Toast.makeText(context, "Removed", Toast.LENGTH_SHORT).show();
}
}
}
});
} //setviewdata
public void updateLikes() {
if (isLiked && storyList.get(changedItemPosition).getIsLiked() == 0) { //jika dilakukan like (pada posisi hati kosong) di halaman home
storyList.get(changedItemPosition).setIsLiked(1); //maka jadikan hati berwarna merah di halaman favourite list
notifyItemChanged(changedItemPosition, ACTION_LIKE_IMAGE_CLICKED);
}
else if (!isLiked && storyList.get(changedItemPosition).getIsLiked() == 1) { //jika like dicabut (pada posisi hati yang sedang merah) di halaman home
storyList.get(changedItemPosition).setIsLiked(0); //maka cabut juga warna merah di halaman favourite list
notifyItemChanged(changedItemPosition, ACTION_LIKE_IMAGE_CLICKED);
}
} //updateLikes
}//Class TidurViewHolder
}
The error result is, it is showing null... Which mean no ID that can be obtained.
In your for loop you are not setting id of your List, but your new Story.
Instead of:
for (int i=0; i<storyList.size(); i++) {
Story story = new Story();
story.setIdStory(String.valueOf(i));
}
Use this:
for (int i=0; i<storyList.size(); i++) {
storyList.get(i).setIdStory(String.valueOf(i));
}
Also because your index i=0 starts from zero, you should change for loop index i to start from 1 like this:
for (int i=1; i<=storyList.size(); i++) {
storyList.get(i).setIdStory(String.valueOf(i));
}
Check this main activity:
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
private ArrayList<Story> storyList;
// url to fetch contacts json
private static final String URL = "https://api.kafeinkode.com/childtidur.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
storyList = new ArrayList<>();
//Fetch JSON data
fetchData();
}
private void fetchData(){
JsonArrayRequest request = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
List<Story> items = new Gson().fromJson(response.toString(), new TypeToken<List<Story>>() {}.getType());
// adding contacts to contacts list
storyList.clear();
storyList.addAll(items);
for (int i=0; i<storyList.size(); i++) {
storyList.get(i).setIdStory(String.valueOf(i + 1));
}
Log.d("StoryLid: ", storyList.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error in getting json
Log.e(TAG, "Error: " + error.getMessage());
}
});
VolleyService.getInstance(this).getRequestQueue().add(request);
}
}
As a result you have response:
When I put something wrong, I receive everything in onResponse but it does not go for the function resultado() and when I put all the data well, it goes to the function resultaod() but only until the time to assign the values to usuario and from the toast it is not executed.
Login Activity
public class LoginActivity extends AppCompatActivity {
private RelativeLayout parentLayout;
private EditText txtUsuario, txtContraseña;
private TextView txtVersion;
private CheckBox chxRecordar;
private Button btnEntrar;
private SharedPreferences myPreferences;
private Usuario usuario;
private String codes, status, token;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
iniciarComponentes();
btnEntrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
verificarInicio();
}
});
}
private void iniciarComponentes() {
parentLayout = findViewById(R.id.parent_layout);
txtUsuario = findViewById(R.id.txt_usuario);
txtContraseña = findViewById(R.id.txt_password);
chxRecordar = findViewById(R.id.chx_recordar);
btnEntrar = findViewById(R.id.btn_entrar);
txtVersion = findViewById(R.id.txt_version);
txtVersion.setText("Version " + BuildConfig.VERSION_NAME);
myPreferences = PreferenceManager.getDefaultSharedPreferences(this);
}
private void verificarInicio() {
String url = Common.BASE_URL + "usuario";
if (validarSesion()) {
Log.d("verificarInicio: ", url);
final String usuario = txtUsuario.getText().toString();
final String contraseña = txtContraseña.getText().toString();
final android.app.AlertDialog dialog = new SpotsDialog.Builder().setContext(this).setMessage("Cargando...").setCancelable(false).build();
dialog.show();
RequestQueue requestQueue = Volley.newRequestQueue(LoginActivity.this);
final StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
codes = jsonObject.getString("code");
status = jsonObject.getString("status");
token = jsonObject.getString("token");
resultado(codes, status, jsonObject, token);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Snackbar.make(parentLayout, error.getMessage(), Snackbar.LENGTH_LONG).show();
dialog.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> parametros = new HashMap<>();
parametros.put("dni", usuario);
parametros.put("password", contraseña);
return parametros;
}
};
requestQueue.add(stringRequest);
requestQueue.addRequestFinishedListener(new RequestQueue.RequestFinishedListener<String>() {
#Override
public void onRequestFinished(Request<String> request) {
if (dialog.isShowing())
dialog.dismiss();
}
});
}
}
private void resultado(String codes, String status, JSONObject jsonObject, String token) throws JSONException {
if (codes.equals("100")) {
JSONArray array = jsonObject.getJSONArray("result");
JSONObject dato = array.getJSONObject(0);
usuario = new Usuario(dato.getString("NombreCompleto"),
dato.getString("estado"),
dato.getString("foto"),
dato.getString("nombre_Aso"),
dato.getString("nombre_Red"),
dato.getString("sexo_Pro"),
dato.getInt("campana"));
Toast.makeText(LoginActivity.this, status, Toast.LENGTH_SHORT).show();
Common.USUARIO_DNI = txtUsuario.getText().toString();
guardarUsuario(token);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra(Common.USUARIO, usuario);
startActivity(intent);
finish();
} else if (codes.equals("200")) {
Snackbar.make(parentLayout, status, Snackbar.LENGTH_LONG).show();
} else if (codes.equals("203")) {
Snackbar.make(parentLayout, status, Snackbar.LENGTH_LONG).show();
}
}
private boolean validarSesion() {
if (TextUtils.isEmpty(txtUsuario.getText()) || TextUtils.isEmpty(txtContraseña.getText())) {
Snackbar.make(parentLayout, "Ingrese su usuario y contraseña", Snackbar.LENGTH_SHORT).show();
return false;
}
return true;
}
private void guardarUsuario(String token) {
SharedPreferences.Editor myEditor = myPreferences.edit();
if (chxRecordar.isChecked()) {
if (!myPreferences.contains(Common.USUARIO)) {
myEditor.putString(Common.USUARIO, txtUsuario.getText().toString());
myEditor.putString(Common.CONTRASEÑA, txtContraseña.getText().toString());
myEditor.putBoolean(Common.CHECK_ESTADO, chxRecordar.isChecked());
myEditor.putString(Common.TOKEN, token);
myEditor.apply();
if (Common.USUARIO_DNI.isEmpty()) {
Common.USUARIO_DNI = myPreferences.getString(Common.USUARIO, "");
}
}
} else {
myEditor.clear();
myEditor.commit();
}
}
}
The whole code is not executed, only a part, I do not know why, I would be grateful if you helped me
check that recibe in a catch, the problem is when get the string for the jsonObject
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
codes = jsonObject.getString("code");
status = jsonObject.getString("status");
token = jsonObject.getString("token");
resultado(codes, status, jsonObject, token);
} catch (JSONException e) {
e.printStackTrace();
}
}
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.!
public class Recyclerview extends AppCompatActivity {
private RecyclerView mRecyclerView;
CustomAdapter cu;
ArrayList<Employee> arr, arr1;
Toolbar toolbar;
TextView t1, t2;
long l = 0;
private ProgressDialog progress;
int j;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview);
toolbar = (Toolbar) findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
final RecyclerView rv = (RecyclerView) findViewById(R.id.rv);
rv.setHasFixedSize(true);
arr = new ArrayList<Employee>();
arr = InitializeData();
final LinearLayoutManager llm = new LinearLayoutManager(Recyclerview.this);
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
cu = new CustomAdapter(Recyclerview.this, arr);
final bank ban = new bank(Recyclerview.this);
rv.setAdapter(cu);
registerForContextMenu(rv);
ImageButton refresh = (ImageButton) findViewById(R.id.refresh);
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progress = ProgressDialog.show(Recyclerview.this, "dialog title",
"dialog message", true);
Toast.makeText(Recyclerview.this, "ok", Toast.LENGTH_LONG).show();
if (isNetworkAvailable()) {
String url = ConstantValues.BASE_URL;
RequestBody formBody = new FormBody.Builder()
.add("key1", "value1")
.add("key2", "value2")
.add("key3", "value3")
.build();
try {
post(url, formBody, new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.e("JSONDemo", "IOException", e);
}
#Override
public void onResponse(final Call call, final Response response) throws IOException {
String JSON = response.body().string();
Log.e("res", " " + JSON);
try {
JSONObject jsonObj = new JSONObject(JSON);
JSONArray resultarr = jsonObj.getJSONArray("result");
final JSONArray resultarr1 = jsonObj.getJSONArray("result1");
if (resultarr1.length() == 0 ) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(Recyclerview.this);
builder1.setMessage("No data found");
builder1.setCancelable(true);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
} else {
ban.OpenDB();
/*Delete old Data from Table*/
ban.Delete("");
for (int i = 0; i < resultarr1.length(); i++) {
Employee emp = new Employee();
JSONObject result1obj = resultarr1.getJSONObject(i);
String result1Id = result1obj.getString(ConstantValues.Bank_ID);
String result1NAME = result1obj.getString(ConstantValues.Bank_NAME);
Log.e("result", " " + result1Id);
Log.e("result", " " + result1NAME);
emp.setId(result1obj.getString(ConstantValues.Bank_ID));
emp.setName(result1obj.getString(ConstantValues.Bank_NAME));
arr.add(emp);
l = ban.InsertQryForTabEmpData(result1Id, result1NAME);
}
ban.CloseDB();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
// you can access all the UI componenet
if (progress.isShowing())
progress.dismiss();
cu.notifyDataSetChanged();
}
});
} catch (Exception e) {
Log.e("JSONDemo", "onResponse", e);
AlertDialog.Builder builder1 = new AlertDialog.Builder(Recyclerview.this);
builder1.setMessage("No data found");
builder1.setCancelable(true);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
}
}
});
} catch (Exception e) {
Log.e("JSONDemo", "Post Exception", e);
}
} else {
Toast.makeText(Recyclerview.this, "Internet not available", Toast.LENGTH_LONG).show();
}
}
});
}
private ArrayList<Employee> InitializeData() {
ArrayList<Employee> arr_emp = new ArrayList<Employee>();
bank ban = new bank(Recyclerview.this);
long l = 0;
ban.OpenDB();
arr_emp = ban.AllSelectQryForTabEmpData();
ban.CloseDB();
return arr_emp;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private final OkHttpClient client = new OkHttpClient();
Call post(String url, RequestBody formBody, Callback callback) throws IOException {
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Call call = client.newCall(request);
call.enqueue(callback);
return call;
}
}
By calling wrong Api it should give dialog box saying unavailable data and is it possible to write dialog box in catch but its not showing dialog box do help me to get rid out of it I dont know where to use if and else...error is coming on String JSON = response.body().string(); thank you in advance
Create a method called like showAlertDialog
public void showAlertDialog(String title, String message) {
final AlertDialog.Builder builder1 = new AlertDialog.Builder(Recyclerview.this);
builder1.setTitle(title);
builder1.setMessage(message);
builder1.setCancelable(true);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
runOnUiThread(new Runnable() {
#Override
public void run() {
builder1.show();
}
});
}
Call this method from catch block.
One things which i can notice in your code is that
1) You are not creating dialog
2) You are not showing your dialog
With respect to code this is what you need to do extra in your code:
AlertDialog alertDialog = builder1.create();
alertDialog.show();
You can create separate method which you can call in your try and catch block:
public void showErrorAlert()
{
builder1 = new AlertDialog.Builder(Recyclerview.this);
builder1.setMessage("No data found");
builder1.setCancelable(true);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = builder1.create();
alertDialog.show();
}
Hope this helps you somehow.