Show dialog box when json string is not true - android

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.

Related

How Do We Set id For Data That Showed With Volley Json Array Request

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:

Attempt to invoke virtual method xx on a null object reference when I try to reload the activity

I've an activity whuich load some data from mySql db to populate a Recyclerview.
PollActivity.java (relevant code)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poll);
rv = findViewById(R.id.rv);
// *** Rv Init ***
LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
rv.setHasFixedSize(false);
polls = new ArrayList<>();
// SqLite data management
db = new SQLiteHandler(getApplicationContext());
HashMap<String, String> user = db.getUserDetails();
final String userid = user.get("uid");
// Local data
String localBefore = Locale.getDefault().getLanguage().toUpperCase();
final String local;
switch (localBefore){
case "IT":
local = "IT";
break;
case "FR":
local = "FR";
break;
case "DE":
local = "DE";
break;
case "ES":
local = "ES";
break;
default:
local = "EN";
break;
}
// ************
// *** MAIN ***
// ************
// Tag used to cancel the request
String tag_string_req = "req_login";
MaterialDialog.Builder builder = new MaterialDialog.Builder(this)
.title(R.string.strDialogProgressLoading_title)
.content(R.string.strDialogProgressReg_desc)
.progress(true, 0);
final MaterialDialog myDialog = builder.build();
myDialog.show();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.POLL_LOADING, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
for(int i=0; i<jObj.length()-2; i++){
int j = i + 1;
JSONObject pollObject = jObj.getJSONObject("poll" + i);
JSONObject pollObjectNext = jObj.getJSONObject("poll" + j);
i++;
//Id to String Translate
int idInterests = getResources().getIdentifier("strInterestsItem" + pollObject.getString("id_interests"), "string", getPackageName());
String strInterests = getString(idInterests);
String strPoint;
if(pollObject.getString("sponsor").equals("UUABA")){
strPoint = "+200";
}else{
strPoint = "+150";
}
//String concatenation
String idPoll = "#" + pollObject.getString("id_poll");
String strQuestion = "#" + pollObject.getString("poll_question");
String IdUser = userid;
polls.add(new Poll(idPoll
, pollObject.getString("sponsor")
, pollObject.getString("poll_user_state")
, IdUser
, strInterests
, strQuestion
, pollObject.getString("poll_answer")
, pollObject.getString("id_poll_answer")
, pollObjectNext.getString("poll_answer")
, pollObjectNext.getString("id_poll_answer")
, strPoint));
}
initializeAdapter();
myDialog.dismiss();
} else {
myDialog.dismiss();
// Error in loading. Get the error message
String errorMsg = jObj.getString("error_msg");
int idErrorRes = getResources().getIdentifier(errorMsg, "string", getPackageName());
String strErrorRes = getString(idErrorRes);
//POPUP ERRORE
new MaterialDialog.Builder(PollActivity.this)
.title(getResources().getString(R.string.strDialogAttention_title))
.titleColor(getResources().getColor(R.color.colorAccentDark))
.content(strErrorRes)
.positiveText(R.string.strDialogBtnPositive)
.contentGravity(GravityEnum.CENTER)
.positiveColor(getResources().getColor(R.color.colorAccent))
.icon(getResources().getDrawable(R.drawable.ic_dialog_alert))
.cancelable(false)
.autoDismiss(false)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(MaterialDialog dialog, DialogAction which) {
dialog.dismiss();
}
})
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
myDialog.dismiss();
//POPUP ERRORE
new MaterialDialog.Builder(PollActivity.this)
.title(getResources().getString(R.string.strDialogAttention_title))
.titleColor(getResources().getColor(R.color.colorAccentDark))
.content(getResources().getString(R.string.errorVolley1) + "(" + error + ")")
.positiveText(R.string.strDialogBtnPositive)
.contentGravity(GravityEnum.CENTER)
.positiveColor(getResources().getColor(R.color.colorAccent))
.icon(getResources().getDrawable(R.drawable.ic_dialog_alert))
.cancelable(false)
.autoDismiss(false)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(MaterialDialog dialog, DialogAction which) {
dialog.dismiss();
}
})
.show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to loading url
Map<String, String> params = new HashMap<String, String>();
params.put("userid", userid);
params.put("local", local);
//Log.d("NINJA", "UserID: " + userid);
//Log.d("NINJA", "Local: " + local);
return params;
}
};
// Adding request to request queue
AppVolleyController.getInstance().addToRequestQueue(strReq, tag_string_req);
// ************
// ************
// ************
private void initializeAdapter(){
RVAdapter adapter = new RVAdapter(polls);
rv.setAdapter(adapter);
}
public void reloadActivity(){
startActivity(getIntent());
finish();
}
}
RVAdapter.java(my Recycler View Adapter)
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PollViewHolder> {
public static class PollViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView txtIdPoll;
ImageView imgSponsor;
ImageView imgNew;
TextView txtIdInterests;
TextView txtQuestion;
RadioGroup radioGroupAnswers;
RadioButton radioAnswer1;
RadioButton radioAnswer2;
Button btnPoint;
PollViewHolder(View itemView) {
super(itemView);
cv = itemView.findViewById(R.id.cv);
txtIdPoll = itemView.findViewById(R.id.txtIdPoll);
imgSponsor = itemView.findViewById(R.id.imgSponsor);
imgNew = itemView.findViewById(R.id.imgNew);
txtIdInterests = itemView.findViewById(R.id.txtIdInterests);
txtQuestion = itemView.findViewById(R.id.txtQuestion);
radioGroupAnswers = itemView.findViewById(R.id.radioGroupAnswers);
radioAnswer1 = itemView.findViewById(R.id.radioAnswer1);
radioAnswer2 = itemView.findViewById(R.id.radioAnswer2);
btnPoint = itemView.findViewById(R.id.btnPoint);
}
}
List<Poll> polls;
//Context context;
public RVAdapter(List<Poll> polls){
this.polls = polls;
//this.context = context;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public PollViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.poll_item, viewGroup, false);
PollViewHolder pvh = new PollViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(final PollViewHolder pollViewHolder, final int i) {
final int rb1id = 1000;
final int rb2id = 2000;
//Setting RadioButton ID
pollViewHolder.radioAnswer1.setId(rb1id);
pollViewHolder.radioAnswer2.setId(rb2id);
pollViewHolder.txtIdPoll.setText(polls.get(i).txtIdPoll);
if(polls.get(i).txtSponsor.equals("UUABA")){
pollViewHolder.imgSponsor.setImageResource(R.drawable.ic_logo_red_bg);
}else{
pollViewHolder.imgSponsor.setImageResource(R.drawable.ic_sponsor_green_bg);
}
if(polls.get(i).txtNew.equals("0")){
pollViewHolder.imgNew.setImageResource(R.drawable.ic_new);
}else{
pollViewHolder.btnPoint.setEnabled(false);
pollViewHolder.btnPoint.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.SRC_ATOP);
}
pollViewHolder.txtIdInterests.setText(polls.get(i).txtIdInterests);
pollViewHolder.txtQuestion.setText(polls.get(i).txtQuestion);
pollViewHolder.radioAnswer1.setText(polls.get(i).txtAnswer1);
pollViewHolder.radioAnswer2.setText(polls.get(i).txtAnswer2);
pollViewHolder.btnPoint.setText(polls.get(i).txtPoint);
pollViewHolder.btnPoint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(pollViewHolder.radioGroupAnswers.getCheckedRadioButtonId() == -1){
Snackbar snackbar = Snackbar.make(v, R.string.strSnackPoll, Snackbar.LENGTH_LONG);
View snackbarView = snackbar.getView();
TextView textView =snackbarView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}else{
QueryUtils queryUtils = new QueryUtils();
String IdPoll = String.valueOf((polls.get(i).txtIdPoll)).replace("#", "");
switch (pollViewHolder.radioGroupAnswers.getCheckedRadioButtonId()){
case 1000:
queryUtils.upgPollAnswer(String.valueOf((polls.get(i).txtUserId)), IdPoll, String.valueOf((polls.get(i).txtIdAnswer1)));
break;
case 2000:
queryUtils.upgPollAnswer(String.valueOf((polls.get(i).txtUserId)), IdPoll, String.valueOf((polls.get(i).txtIdAnswer2)));
break;
}
}
}
});
}
#Override
public int getItemCount() {
return polls.size();
}
}
At this point, I would like to update a db field at button click and reload PollActivity.java to force the RecyclerView update (I'd like that the NEW image disappear from the updated CardView). I guess to do this calling a method of my QueryUtils.java (one of the method it will contain), avoiding to write too mutch code inside adapter.
QueryUtils.java
#SuppressLint("Registered")
public class QueryUtils extends Application {
private String tag_string_req = "req_poll_answer_upg";
public void upgPollAnswer(final String UserId, final String PollId, final String AnswerId){
Log.d("NINJA", "Utente: " + UserId);
Log.d("NINJA", "Poll: " + PollId);
Log.d("NINJA", "Risposta: " + AnswerId);
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.POLL_ANSWER_UPG, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
String message = jObj.getString("message");
if (!error) {
Log.d("NINJA", "Messaggio: " + message);
PollActivity pollActivity = new PollActivity();
pollActivity.reloadActivity();
} else {
//myDialog.dismiss();
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
int idErrorRes = getResources().getIdentifier(errorMsg, "string", getPackageName());
String strErrorRes = getString(idErrorRes);
Log.d("NINJA", "ErrorePhP: " + strErrorRes);
//POPUP ERRORE
/*new MaterialDialog.Builder(QueryUtils.this)
.title(getResources().getString(R.string.strDialogAttention_title))
.titleColor(getResources().getColor(R.color.colorAccentDark))
.content(strErrorRes)
.positiveText(R.string.strDialogBtnPositive)
.contentGravity(GravityEnum.CENTER)
.positiveColor(getResources().getColor(R.color.colorAccent))
.icon(getResources().getDrawable(R.drawable.ic_dialog_alert))
.cancelable(false)
.autoDismiss(false)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(MaterialDialog dialog, DialogAction which) {
dialog.dismiss();
}
})
.show();*/
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("NINJA", "ErroreVolley: " + error);
//myDialog.dismiss();
//POPUP ERRORE
/*new MaterialDialog.Builder(QueryUtils.this)
.title(getResources().getString(R.string.strDialogAttention_title))
.titleColor(getResources().getColor(R.color.colorAccentDark))
.content(getResources().getString(R.string.errorVolley1) + "(" + error + ")")
.positiveText(R.string.strDialogBtnPositive)
.contentGravity(GravityEnum.CENTER)
.positiveColor(getResources().getColor(R.color.colorAccent))
.icon(getResources().getDrawable(R.drawable.ic_dialog_alert))
.cancelable(false)
.autoDismiss(false)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(MaterialDialog dialog, DialogAction which) {
dialog.dismiss();
}
})
.show();*/
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to loading url
Map<String, String> params = new HashMap<String, String>();
params.put("userid", UserId);
params.put("id_poll", PollId);
params.put("id_answer", AnswerId);
return params;
}
};
// Adding request to request queue
AppVolleyController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
At the end of the update procedure, I call the reloadActivity method in PollActivity, to reload itself. THIS call generate the error below:
LOGCAT
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
at android.app.Activity.startActivityForResult(Activity.java:4226)
at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:68)
at android.app.Activity.startActivityForResult(Activity.java:4183)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:751)
at android.app.Activity.startActivity(Activity.java:4522)
at android.app.Activity.startActivity(Activity.java:4490)
at com.uuaba.uuaba.core.PollActivity.reloadActivity(PollActivity.java:345)
at com.uuaba.uuaba.utils.QueryUtils$1.onResponse(QueryUtils.java:48)
at com.uuaba.uuaba.utils.QueryUtils$1.onResponse(QueryUtils.java:33)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
I'm new in Android programming and I tried different solution found in this great forum, but none of them worked for me.
Please help me
Problem is that you are trying to create a new instance of activity without the use of intent :
PollActivity pollActivity = new PollActivity();
pollActivity.reloadActivity();
You should replace this code with the following lines:
public void onClickChangeActivity() {
Intent intent = new Intent(this, PollActivity.class);
startActivity(intent);
}
But your solution is far away from the ideal solutions available in the market. Restarting the activity whenever there is a change in data because you have to update data can never be a good way to go.
Try considering one of these ways to prevent activity restart
Create a data stream(list of data) and keep on reading that on
activity level.
Create a local broadcast receiver
Do let me know if you need help in above ways.
As a quick fix for the problem you can use this hackish way
Create a callback
interface Result {
void success(ResponseModel model);
void failure(Throwable throw);
}
In QueryUtils
List resultCallbacks = new ArrayList(); public void
addCallback(Result result) { resultCallbacks.add(result); }
create List resultCallbacks and a method addCallback to add the callbacks
In PollsActivity write this
((QueryApplication)getApplicationContext().getApplication()).addCallbacks(this);
and implement the callback.
On receiving any data update your list and do
RVUpdater.notifyDataSetChanged();
Hope this will help.

java.sql.SQLException: No value specified for parameter 2, in a web service

I have a problem when trying to make a POST request to a webservice, review the structure of my method in my webservice and my Android method but I did not find the error.
this is my class of Android, my method is called:
onClickUpdate (final int position, end String identifier)
public class tareasFragmento extends Fragment implements TareasAdapter.OnClickButton{
private String url = "http://192.168.1.128:8080/WebServiceExamenFinal/webapi/tareas";
private ArrayList<Tareas> listatarea = new ArrayList<>();
//Si no funciona esto se puede borrar
AlertDialog alertDialog;
private List<Tareas> tareasList;
private TareasAdapter tareasAdapter;
private int assiId;
public tareasFragmento() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_tareas, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2,
GridLayoutManager.VERTICAL, false));
final TareasAdapter adapter = new TareasAdapter(getActivity(), listatarea);
adapter.setCallback(this);
recyclerView.setAdapter(adapter);
RequestQueue queue = Volley.newRequestQueue(getContext());
final ProgressDialog dialog = new ProgressDialog(getContext());
dialog.setMessage("Por favor espere...");
dialog.show();
try {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
deserializarJSONArray(response);
adapter.notifyDataSetChanged();
if (dialog.isShowing()) dialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),
"Error al realizar la petición\n" + error.getMessage(),
Toast.LENGTH_LONG).show();
if (dialog.isShowing()) dialog.dismiss();
}
});
queue.add(jsonArrayRequest);
}catch (Exception e) {
Toast.makeText(getActivity(),"El error es: "+e,Toast.LENGTH_LONG).show();
}
return view;
}
public void deserializarJSONArray(JSONArray jsonArray) {
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject item = jsonArray.getJSONObject(i);
Tareas tareas = new Tareas();
tareas.setId(item.getString("id"));
tareas.setNombreTarea(item.getString("nombreUsuario"));
tareas.setEstudiante(item.getString("estudiante"));
tareas.setNota(item.getString("nota"));
listatarea.add(tareas);
} catch (JSONException e) {
Toast.makeText(getActivity(), "Error al procesar la respuesta de la petición: " + e,
Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onClickUpdate(final int position, final String identificador) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = this.getLayoutInflater();
View MyView = inflater.inflate(R.layout.dialog_signin_updatedonante, null);
final EditText identidad = (EditText)MyView.findViewById(R.id.identificador_tarea);
final EditText nombre_tarea = (EditText)MyView.findViewById(R.id.nombre_tarea);
final EditText nota = (EditText)MyView.findViewById(R.id.nota_tarea);
final EditText estudiante = (EditText)MyView.findViewById(R.id.estudiante_tarea);
identidad.setEnabled(false);
identidad.setText(identificador);
final JSONObject jsonObject = new JSONObject();
try{
jsonObject.put("nombre_tarea","Ejemplo").put("nota","Ejemplo").put("estudiante", "Ejemplo");
}catch(JSONException e){
e.printStackTrace();
}
final RequestQueue queue = Volley.newRequestQueue(getActivity());
builder.setView(MyView)
.setPositiveButton("Registrar", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
if(nombre_tarea.getText().toString().equals("") || nota.getText().toString().equals("") || estudiante.getText().toString().equals("")){
Toast.makeText(getActivity(), "Porfavor llena todos los campos", Toast.LENGTH_LONG ).show();
}else{
String urlPut = "http://192.168.1.128:8080/WebServiceExamenFinal/webapi/tareas/";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.PUT, urlPut + identificador, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getActivity(), "Se envió correctamente", Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Ocurrió un error al enviar la información", Toast.LENGTH_LONG).show();
}
});
queue.add(request);
}
}
})
.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getActivity(),"No se actualizo ningun registro", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
});
alertDialog = builder.create();
alertDialog.show();
}
#Override
public void onClickDelete(final int position, final String identificador) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = this.getLayoutInflater();
View MyView = inflater.inflate(R.layout.dialog_signin_deletedonante, null);
RecyclerView recyclerView = (RecyclerView)getView().findViewById(R.id.recycler_list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2,
GridLayoutManager.VERTICAL, false));
final TareasAdapter adapter = new TareasAdapter(getActivity(), listatarea);
adapter.setCallback(this);
recyclerView.setAdapter(adapter);
builder.setView(MyView)
.setPositiveButton("Eliminar", new DialogInterface.OnClickListener() {
#Override
public void onClick(final DialogInterface dialog, int id) {
//Toast.makeText(getActivity(),"id: "+ identificador, Toast.LENGTH_SHORT).show();
String urlDelete = "http://192.168.1.128:8080/WebServiceExamenFinal/webapi/tareas/";
final RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest request = new StringRequest(Request.Method.DELETE, urlDelete + identificador, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Aqui actualizo mi fragmento para que se vean reflejados los cambios, intete usar un notifysetDataChange pero no me
//funciono
tareasFragmento tareas = new tareasFragmento();
android.support.v4.app.FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.qwe, tareas).commit();
Toast.makeText(getActivity(), "La tarea se eliminó correctamente", Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Ocurrió un error en la petición", Toast.LENGTH_LONG).show();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json;charset=utf-8");
return headers;
}
};
queue.add(request);
}
})
.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(getActivity(),"No se ha eliminado la tarea", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
});
alertDialog = builder.create();
alertDialog.show();
}
}
This is my PUT method in my web Service:
#PUT
#Path("{id}")
public void put(#PathParam("id")Integer id, Tareas tareas){
tareas.setId(id);
try {
DaoTareas.getInstance().actualizar(tareas);
} catch (SQLException ex) {
Logger.getLogger(TareasResource.class.getName()).log(Level.SEVERE, null, ex);
}
}
And finally this is the method where I have my query:
#Override
public void actualizar(Tareas entidad) throws SQLException {
String query = "UPDATE tareas SET nombre_tarea=?, nota=?, estudiante=? WHERE id = ?";
if (actualizar == null) {
actualizar = Conexion.getInstance().getCon().prepareStatement(query);
}
actualizar.setString(1, entidad.getNombreUsuario());
actualizar.setInt(3, entidad.getId());
actualizar.executeUpdate();
}
You need add all parameter: actualizae.setString(2, etidad.getNota()) same with quantity of "?" character.

Dynamic setMultiChoiceItems from server

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.!

JSONObjectRequest how to populate spinner using volley

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.

Categories

Resources