I want to do calculation using JSON Data in RecyclerView with ToggleButton. When the toggle button is checked the value should change and when its not checked the value should change again for that particular RecyclerView row. The problem is when I click the ToggleButton, 2 other RecyclerView row's ToggleButton is also checked.
CODE:
Activity
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.gridlayout.widget.GridLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class GstPlanner extends AppCompatActivity implements GstPlanAdapter.GstPlanListener{
private static final String TAG = GstPlanner.class.getSimpleName();
List<String> dateNames = new ArrayList<String>();
private List<GstPlanList> GSTLisT;
private GstPlanAdapter mAdapter;
Context context;
Spinner ret_pending_drop, state_drop, nil_drop;
String URL, URL1;
ProgressBar progress_gst, Progress_Gst_Plan;
GridLayout grid_gst;
TextView txt_retry_gst, txt_state_gst, txt_ret_type, txt_final_gst;
Button btn_retry_gst, btn_submit_state, btn_submit;
String State_GET;
RecyclerView recyclerView1;
RelativeLayout Gst_Plan_Relative;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gst_planner);
Gst_Plan_Relative = findViewById(R.id.Gst_Plan_Relative);
recyclerView1 = findViewById(R.id.Recycler_Gst_Plan);
Progress_Gst_Plan = findViewById(R.id.Progress_Gst_Plan);
btn_submit_state = findViewById(R.id.btn_submit_state);
txt_state_gst = findViewById(R.id.txt_state_gst);
txt_ret_type = findViewById(R.id.txt_ret_type);
txt_retry_gst = findViewById(R.id.txt_retry_gst);
btn_retry_gst = findViewById(R.id.btn_retry_gst);
ret_pending_drop = findViewById(R.id.ret_pending_drop);
txt_final_gst = findViewById(R.id.txt_final_gst);
state_drop = findViewById(R.id.state_drop);
btn_submit = findViewById(R.id.btn_submit);
nil_drop = findViewById(R.id.nil_drop);
grid_gst = findViewById(R.id.grid_gst);
progress_gst = findViewById(R.id.progress_gst);
GSTLisT = new ArrayList<>();
mAdapter = new GstPlanAdapter(this, GSTLisT, this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView1.setLayoutManager(mLayoutManager);
recyclerView1.setItemAnimator(new DefaultItemAnimator());
recyclerView1.addItemDecoration(new MyDividerItemDecoration(this, DividerItemDecoration.VERTICAL, 36));
recyclerView1.setAdapter(mAdapter);
btn_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
URL1 = "http://url.com/something.php?state="+state_drop.getSelectedItem().toString()+"&RType="+txt_ret_type.getText().toString()+"&NIL="+nil_drop.getSelectedItem().toString()+"&Month="+ret_pending_drop.getSelectedItem().toString();
Log.e("URL1",URL1);
Progress_Gst_Plan.setVisibility(View.VISIBLE);
fetchData();
GlobalValue.getit = true;
}
});
btn_submit_state.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
URL = "http://url.com/something.php?state="+state_drop.getSelectedItem().toString();
State_GET = state_drop.getSelectedItem().toString();
btn_submit_state.setVisibility(View.INVISIBLE);
state_drop.setVisibility(View.INVISIBLE);
progress_gst.setVisibility(View.VISIBLE);
fetchMonths();
}
});
btn_retry_gst.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progress_gst.setVisibility(View.INVISIBLE);
txt_retry_gst.setVisibility(View.GONE);
btn_retry_gst.setVisibility(View.GONE);
btn_submit_state.setVisibility(View.VISIBLE);
state_drop.setVisibility(View.VISIBLE);
}
});
}
private void fetchData() {
JsonArrayRequest request = new JsonArrayRequest(URL1,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response == null) {
Toast.makeText(getApplicationContext(), "Couldn't fetch the Details! Please try again.", Toast.LENGTH_LONG).show();
return;
}
Gst_Plan_Relative.setVisibility(View.VISIBLE);
Progress_Gst_Plan.setVisibility(View.INVISIBLE);
List<GstPlanList> items = new Gson().fromJson(response.toString(), new TypeToken<List<GstPlanList>>() {
}.getType());
// adding contacts to contacts list
GSTLisT.clear();
GSTLisT.addAll(items);
// refreshing recycler view
mAdapter.notifyDataSetChanged();
Progress_Gst_Plan.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error in getting json
Log.e(TAG, "Error: " + error.getMessage() +error.getCause());
AlertDialog("Error...Please try after some time.");
progress_gst.setVisibility(View.INVISIBLE);
txt_retry_gst.setVisibility(View.VISIBLE);
btn_retry_gst.setVisibility(View.VISIBLE);
btn_submit.setVisibility(View.INVISIBLE);
Gst_Plan_Relative.setVisibility(View.INVISIBLE);
}
});
APP.getInstance().addToRequestQueue(request);
}
private void fetchMonths() {
StringRequest stringRequest = new StringRequest(URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject object = jsonArray.getJSONObject(0);
JSONArray arrayContacts = object.getJSONArray("Status");
for (int i = 0; i<arrayContacts.length(); i++) {
JSONObject contactObject = arrayContacts.getJSONObject(i);
dateNames.add(contactObject.getString("Month"));
}
spinnervalue(dateNames, ret_pending_drop);
txt_state_gst.setText(State_GET);
progress_gst.setVisibility(View.INVISIBLE);
grid_gst.setVisibility(View.VISIBLE);
txt_retry_gst.setVisibility(View.GONE);
btn_retry_gst.setVisibility(View.GONE);
btn_submit.setVisibility(View.VISIBLE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog("Error...Please try after some time.");
progress_gst.setVisibility(View.INVISIBLE);
txt_retry_gst.setVisibility(View.VISIBLE);
btn_retry_gst.setVisibility(View.VISIBLE);
btn_submit.setVisibility(View.INVISIBLE);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
public void spinnervalue(List<String> value, Spinner spinner1){
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item, value);
dataAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
}
public void AlertDialog(String s) {
try{
AlertDialog.Builder builder1 = new AlertDialog.Builder(GstPlanner.this);
builder1.setMessage(s);
builder1.setCancelable(true);
builder1.setPositiveButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}catch (
WindowManager.BadTokenException ex){
ex.printStackTrace();
}
}
#Override
public void onSubTotalUpdate(int total){
txt_final_gst.setText(String.valueOf(total));
}
RecyclerView Adapter
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.ToggleButton;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GstPlanAdapter extends RecyclerView.Adapter<GstPlanAdapter.MyViewHolder>
implements Filterable {
private Context context;
private List<GstPlanList> GstPlanList;
private List<GstPlanList> GstPlanListFiltered;
private GstPlanListener listener;
int totalPrice;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView ret_month, due_date, penalty_amt;
Spinner nil_ret;
ToggleButton toggleSwitch;
public MyViewHolder(View view) {
super(view);
ret_month = view.findViewById(R.id.ret_month);
due_date = view.findViewById(R.id.due_date);
penalty_amt = view.findViewById(R.id.penalty_amt);
toggleSwitch = view.findViewById(R.id.switch_gst);
}
}
public GstPlanAdapter(Context context, List<GstPlanList> BiLLList, GstPlanListener listener ) {
this.context = context;
this.listener = listener;
this.GstPlanList = BiLLList;
this.GstPlanListFiltered = BiLLList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent1, int viewType1) {
View itemView = LayoutInflater.from(parent1.getContext())
.inflate(R.layout.gst_plan_view_item_row, parent1, false);
return new MyViewHolder(itemView);
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, final int position) {
final GstPlanList bill = GstPlanListFiltered.get(position);
holder.nil_ret.setAdapter(categoriesAdapter);
holder.ret_month.setText(bill.getMonth());
holder.due_date.setText(bill.getDate());
holder.penalty_amt.setText(bill.getPenatly().toString());
totalPrice = 0;
for (int i = 0; i < GstPlanList.size(); i++) {
totalPrice += GstPlanList.get(i).getPenatly();
countTotal(totalPrice);
}
if (GlobalValue.getit == true) {
if (bill.getNIL().equals("YES")) {
holder.toggleSwitch.setChecked(true);
GlobalValue.getit = false;
} else {
holder.toggleSwitch.setChecked(false);
GlobalValue.getit = false;
}
}
holder.toggleSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.toggleSwitch.isChecked()) {
int AC = bill.getTODATE();
int BC = Integer.parseInt(bill.getNILNO().toString());
int ABC = AC * BC;
totalPrice = totalPrice - ABC;
int A = bill.getTODATE();
int B = Integer.parseInt(bill.getNILYES().toString());
int AB = A * B;
if (AB >= 10000) {
holder.penalty_amt.setText("10000");
totalPrice = totalPrice + 10000;
countTotal(totalPrice);
} else {
holder.penalty_amt.setText(String.valueOf(AB));
totalPrice = totalPrice + AB;
countTotal(totalPrice);
}
}
if (!holder.toggleSwitch.isChecked()) {
int AC = bill.getTODATE();
int BC = Integer.parseInt(bill.getNILYES().toString());
int ABC = AC * BC;
totalPrice = totalPrice - ABC;
int A = bill.getTODATE();
int B = Integer.parseInt(bill.getNILNO().toString());
int AB = A * B;
if (AB >= 10000) {
holder.penalty_amt.setText("10000");
totalPrice = totalPrice + 10000;
countTotal(totalPrice);
} else {
holder.penalty_amt.setText(String.valueOf(AB));
totalPrice = totalPrice + AB;
countTotal(totalPrice);
}
}
}
});
}
public void countTotal(int total){
listener.onSubTotalUpdate(total);
}
#Override
public int getItemCount() {
return GstPlanListFiltered.size();
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
GstPlanListFiltered = GstPlanList;
} else {
List<GstPlanList> filteredList = new ArrayList<>();
for (GstPlanList row : GstPlanList) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getDate().toLowerCase().contains(charString.toLowerCase()) || row.getMonth().toLowerCase().contains(charString.toLowerCase()) || row.getRType().toLowerCase().contains(charString.toLowerCase())) {
filteredList.add(row);
}
}
GstPlanListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = GstPlanListFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
GstPlanListFiltered = (ArrayList<GstPlanList>) filterResults.values;
notifyDataSetChanged();
}
};
}
public interface GstPlanListener {
// void onGstPlanSelected(GstPlanList bill);
void onSubTotalUpdate(int total);
}
}
GstPlanList
public class GstPlanList {
private String RType;
private String State;
private String NILNO;
private String NILYES;
private String Month;
private String Date;
private String NIL;
private int Penatly;
private int TODATE;
public GstPlanList() {
}
public Integer getPenatly() {
return Penatly;
}
public int getTODATE() {
return TODATE;
}
public String getNIL() {
return NIL;
}
public String getRType() {
return RType;
}
public String getState() {
return State;
}
public String getNILNO() {
return NILNO;
}
public String getNILYES() {
return NILYES;
}
public String getMonth() {
return Month;
}
public String getDate() {
return Date;
}
}
Related
I just created my recyclerview to show a cardview when I just filling the required data on AddNewTimerFragment.java. But somehow it wont show the card that contains the data that I've fill in before. I've tried to changes something, but doesn't work.
Code :
MainActivity.java
package com.mobprog.ius.dwasu;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.LinkedList;
public class MainActivity extends AppCompatActivity {
private ArrayList<MyListDataTimer> mintervalTimeList = new ArrayList();
private RecyclerView mRecyclerView;
private alarmListAdapter mAdapter;
public boolean isFragmentAddNewAlarmDisplayed = false;
static final String STATE_FRAGMENT = "state_of_fragment";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((TextView) findViewById(R.id.textUserName)).setText("Hello " + getSharedPreferences("Dwasu", 0).getString("user", ""));
if (getSharedPreferences("Dwasu", 0) == null || !getSharedPreferences("Dwasu", 0).contains("user")) {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
// Create recycler view.
mRecyclerView = findViewById(R.id.recyclerView);
// Create an adapter and supply the data to be displayed.
mAdapter = new alarmListAdapter(getApplicationContext(), mintervalTimeList);
// Connect the adapter with the recycler view.
mRecyclerView.setAdapter(mAdapter);
// Give the recycler view a default layout manager.
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
if (savedInstanceState != null)
isFragmentAddNewAlarmDisplayed = savedInstanceState.getBoolean(STATE_FRAGMENT);
Button mnewReminderButton = findViewById(R.id.newReminder);
mnewReminderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(MainActivity.class.getSimpleName(),"Button Clicked");
displayFragment();
}
});
ImageButton mlogOutButton = findViewById(R.id.logOutButton);
findViewById(R.id.logOutButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getSharedPreferences("Dwasu", 0).edit().clear().apply();
startActivity(new Intent(MainActivity.this, MainActivity.class));
finish();
}
});
// // Get the Drawable custom_progressbar
// Drawable draw = ResourcesCompat.getDrawable(getResources(), R.drawable.progress_bar, null);
// // set the drawable as progress drawable
// ProgressBar.setProgressDrawable(draw);
}
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the state of the fragment (true=open, false=closed).
savedInstanceState.putBoolean(STATE_FRAGMENT, isFragmentAddNewAlarmDisplayed);
super.onSaveInstanceState(savedInstanceState);
}
public void closeFragment(){
// Get the FragmentManager.
FragmentManager fragmentManager = getSupportFragmentManager();
// Check to see if the fragment is already showing.
AddNewTimerFragment simpleFragment = (AddNewTimerFragment) fragmentManager
.findFragmentById(R.id.FragmentContainer_AddNewAlarm);
if (simpleFragment != null) {
// Create and commit the transaction to remove the fragment.
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.remove(simpleFragment).commit();
}
// Set boolean flag to indicate fragment is closed.
isFragmentAddNewAlarmDisplayed = false;
}
public void displayFragment(){
AddNewTimerFragment simpleFragment = AddNewTimerFragment.newInstance();
// Get the FragmentManager and start a transaction.
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
// Add the SimpleFragment.
fragmentTransaction.add(R.id.FragmentContainer_AddNewAlarm,
simpleFragment).addToBackStack(null).commit();
// Set boolean flag to indicate fragment is open.
isFragmentAddNewAlarmDisplayed = true;
}
}
AddNewTimerFragment.java
package com.mobprog.ius.dwasu;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;
import org.apache.http.entity.mime.content.StringBody;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import static android.content.Context.MODE_PRIVATE;
public class AddNewTimerFragment extends Fragment {
Button startTime;
Button endTime;
Button meditConfirm_button;
int startHour;
int startMinute;
int endHour;
int endMinute;
int position = 1;
long totalSize = 0;
String value;
ProgressDialog progDailog;
View rootview;
private SharedPreferences mPreferences;
private String sharedPrefFile =
"com.mobprog.ius.dwasu";
public AddNewTimerFragment() {
// Required empty public constructor
}
public static AddNewTimerFragment newInstance() {
return new AddNewTimerFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_add_new_alarm,
container, false);
rootview = rootView;
/*Shared Pref*/
mPreferences = this.getActivity().getSharedPreferences(sharedPrefFile, MODE_PRIVATE);
SharedPreferences.Editor mPreferencesEditor = mPreferences.edit();
ImageButton mbtnCloseFragment = rootView.findViewById(R.id.btnCloseFragment);
mbtnCloseFragment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity) getActivity()).closeFragment();
}
});
// initiate the edit text
startTime = rootView.findViewById(R.id.startTimePick);
startTime.setText(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + Calendar.getInstance().get(Calendar.MINUTE));
// perform click event listener on edit text
startTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar mcurrentTime = Calendar.getInstance();
startHour = mcurrentTime.get(Calendar.HOUR);
startMinute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mStartTimePicker;
mStartTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedStartHour, int selectedStartMinute) {
if (selectedStartMinute == 0) {
startTime.setText(selectedStartHour + ":00");
} else if (selectedStartMinute < 10) {
if (selectedStartHour < 10) {
startTime.setText("0" + selectedStartHour + ":0" + selectedStartMinute);
}
} else {
startTime.setText(selectedStartHour + ":" + selectedStartMinute);
}
startHour = selectedStartHour;
}
}, startHour, startMinute, true);//Yes 24 hour time
mStartTimePicker.show();
}
});
endTime = rootView.findViewById(R.id.endTimePick);
endTime.setText(Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + Calendar.getInstance().get(Calendar.MINUTE));
// perform click event listener on edit text
endTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar mcurrentTime = Calendar.getInstance();
endHour = mcurrentTime.get(Calendar.HOUR);
endMinute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mEndTimePicker;
mEndTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedEndHour, int selectedEndMinute) {
if (selectedEndMinute == 0) {
endTime.setText(selectedEndHour + ":00");
} else if (selectedEndMinute < 10) {
if (selectedEndHour < 10) {
endTime.setText("0" + selectedEndHour + ":0" + selectedEndMinute);
}
} else {
endTime.setText(selectedEndHour + ":" + selectedEndMinute);
}
endHour = selectedEndHour;
}
}, endHour, endMinute, true);//Yes 24 hour time
mEndTimePicker.show();
}
});
Spinner spinner = (Spinner) rootView.findViewById(R.id.timeIntervalPick);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(),
R.array.listtimer, R.layout.spinner_support);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(R.layout.spinner_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
String[] valueListTimer = getResources().getStringArray(R.array.valueListTimer);
value = valueListTimer[position];
Log.e("Value of Spinner", value);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
meditConfirm_button = rootView.findViewById(R.id.editConfirm_button);
meditConfirm_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String.valueOf(startHour);
String.valueOf(endHour);
String.valueOf(value);
new MyListDataTimer(String.valueOf(startHour),String.valueOf(endHour),String.valueOf(value),String.valueOf(position));
new UploadAlarmDataToServer().execute();
position++;
}
});
// Inflate the layout for this fragment
return rootView;
}
private class UploadAlarmDataToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
progDailog = new ProgressDialog(getContext());
progDailog.setMessage("Menyimpan...");
progDailog.setIndeterminate(false);
progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDailog.setCancelable(false);
progDailog.setCanceledOnTouchOutside(false);
progDailog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
String data = null;
try {
data = sendDataTimer();
} catch (Exception e) {
e.printStackTrace();
data = "Gagal";
}
return data;
}
public String sendDataTimer() throws Exception {
URL url = new URL("https://ius.mobile.indoserver.web.id/alarmData.php");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
entity.addPart("startHour", new StringBody(startHour + ""));
entity.addPart("endHour", new StringBody(endHour + ""));
entity.addPart("intervalWaktu", new StringBody(value + ""));
totalSize = entity.getContentLength();
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.addRequestProperty("Content-length", totalSize + "");
con.addRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue());
OutputStream os = con.getOutputStream();
entity.writeTo(con.getOutputStream());
os.close();
con.connect();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
#Override
protected void onPostExecute(String result) {
progDailog.dismiss();
if (result != null) {
Log.e("UPLOAD", result);
if (result.equalsIgnoreCase("OK")) {
Toast.makeText(getContext(), "Data Alarm tersimpan", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getContext(), MainActivity.class));
}
}
super.onPostExecute(result);
}
}
}
alarmListAdapter.java
package com.mobprog.ius.dwasu;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.LinkedList;
public class alarmListAdapter extends RecyclerView.Adapter<alarmListAdapter.alarmListHolder>{
private final ArrayList<MyListDataTimer> mintervalTimeList;
private LayoutInflater mInflater;
public alarmListAdapter(Context context, ArrayList<MyListDataTimer> mintervalTimeList) {
mInflater = LayoutInflater.from(context);
this.mintervalTimeList = mintervalTimeList;
}
#Override
public alarmListHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View mItemView = mInflater.inflate(R.layout.alarm_item,
parent, false);
return new alarmListHolder(mItemView, this);
}
#Override
public void onBindViewHolder(alarmListAdapter.alarmListHolder holder, int position) {
final MyListDataTimer myListData = mintervalTimeList.get(position);
holder.mintervalTime.setText(myListData.getIntervalWaktu());
holder.mtimeWork.setText(myListData.getStartHour() +":00 - " + myListData.getEndHour() +":00");
}
#Override
public int getItemCount() {
return mintervalTimeList.size();
}
public class alarmListHolder extends RecyclerView.ViewHolder {
public TextView mintervalTime;
public TextView mtimeWork;
final alarmListAdapter mAdapter;
public alarmListHolder(View itemView, alarmListAdapter adapter) {
super(itemView);
mintervalTime = itemView.findViewById(R.id.intervalTime);
mtimeWork = itemView.findViewById(R.id.timeWork);
this.mAdapter = adapter;
}
}
}
**MyListDataTimer.java**
package com.mobprog.ius.dwasu;
public class MyListDataTimer {
private String startHour;
private String endHour;
private String intervalWaktu;
private String position;
public MyListDataTimer(String startHour, String endHour, String intervalWaktu, String position) {
this.startHour = startHour;
this.endHour = endHour;
this.intervalWaktu = intervalWaktu;
this.position = position;
}
public String getStartHour() {
return startHour;
}
public void setStartHour(String startHour) {
this.startHour = startHour;
}
public String getEndHour() {
return endHour;
}
public void setEndHour(String endHour) {
this.endHour = endHour;
}
public String getIntervalWaktu() {
return intervalWaktu;
}
public void setIntervalWaktu(String intervalWaktu) {
this.intervalWaktu = intervalWaktu;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
}
I've been following this tutorial: Tutorial
To make a json recyclerviewer with onclick, but i wanted to use Fragments instead of activities.
I've figured everything out until the point of the onClick.
My problem is the setOnItemClickListener is not taking my getActivity()
I've tried so much, but i just cant see the bright light.
If anyone could help me out that would be totally awesome!
Me only real problem is that the getActivity is giving a red line in the:
fNieuwsAdapter.setOnItemClickListener(getActivity());
NieuwsFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import java.util.ArrayList;
public class NieuwsFragment extends Fragment implements NieuwsAdapter.OnItemClickListener {
public static final String EXTRA_URL = "nieuwsImageUrl";
public static final String EXTRA_HEADING = "nieuwsHeading";
public static final String EXTRA_CONTENT = "nieuwsContent";
private RecyclerView fNieuwsRecyclerView;
private NieuwsAdapter fNieuwsAdapter;
private ArrayList<NieuwsItem> fNieuwsList;
private RequestQueue fNieuwsQueue;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_nieuws, container, false);
fNieuwsRecyclerView = view.findViewById(R.id.recycler_view);
fNieuwsRecyclerView.setHasFixedSize(true);
fNieuwsRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
fNieuwsList = new ArrayList<>();
fNieuwsQueue = Volley.newRequestQueue(getActivity());
parseJSON();
return view;
}
private void parseJSON() {
String url = "urlissecretsorry<3butthejsonparsingworks";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
public String nieuwsImageUrl;
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("posts");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject hit = jsonArray.getJSONObject(i);
JSONArray attachArray = hit.getJSONArray("attachments");
for (int a = 0; a < attachArray.length(); a++) {
JSONObject attach = attachArray.getJSONObject(a);
nieuwsImageUrl = attach.getString("url");
}
String nieuwsHeading = hit.getString("title");
String nieuwsExcerpt = hit.getString("excerpt");
String nieuwsContent = hit.getString("content");
nieuwsExcerpt = html2text(nieuwsExcerpt);
fNieuwsList.add(new NieuwsItem(nieuwsImageUrl, nieuwsHeading, nieuwsExcerpt,nieuwsContent));
}
fNieuwsAdapter = new NieuwsAdapter(getActivity(), fNieuwsList);
fNieuwsAdapter.setOnItemClickListener(getActivity());
fNieuwsRecyclerView.setAdapter(fNieuwsAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
fNieuwsQueue.add(request);
}
#Override
public void onItemClick(int position) {
Intent detailIntent = new Intent(getActivity(), DetailActivity.class);
NieuwsItem clickedItem = fNieuwsList.get(position);
detailIntent.putExtra(EXTRA_URL, clickedItem.getImageUrl());
detailIntent.putExtra(EXTRA_HEADING, clickedItem.getHeading());
detailIntent.putExtra(EXTRA_CONTENT, clickedItem.getContent());
startActivity(detailIntent);
}
public String html2text(String html) {
try {
return Jsoup.parse(html).text();
} catch (Exception ignored) {
return "";
}
}
}
NieuwsItem.java
public class NieuwsItem {
private String nieuwsImageUrl;
private String nieuwsHeading;
private String nieuwsExcerpt;
private String nieuwsContent;
public NieuwsItem(String imageUrl, String heading, String excerpt, String content){
nieuwsImageUrl = imageUrl;
nieuwsHeading = heading;
nieuwsExcerpt = excerpt;
nieuwsContent = content;
}
public String getImageUrl(){
return nieuwsImageUrl;
}
public String getHeading(){
return nieuwsHeading;
}
public String getExcerpt(){
return nieuwsExcerpt;
}
public String getContent(){
return nieuwsContent;
}
}
NieuwsAdapter.java
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class NieuwsAdapter extends RecyclerView.Adapter<NieuwsAdapter.NieuwsViewHolder> {
private Context NieuwsContext;
private ArrayList<NieuwsItem> NieuwsList;
private OnItemClickListener NieuwsListener;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
NieuwsListener = listener;
}
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist) {
NieuwsContext = context;
NieuwsList = nieuwslist;
}
#NonNull
#Override
public NieuwsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(NieuwsContext).inflate(R.layout.nieuws_item, parent, false);
return new NieuwsViewHolder(v);
}
#Override
public void onBindViewHolder(NieuwsViewHolder holder, int position) {
NieuwsItem currentitem = NieuwsList.get(position);
String ImageUrl = currentitem.getImageUrl();
String Heading = currentitem.getHeading();
String Excerpt = currentitem.getExcerpt();
holder.NieuwsTextViewHeading.setText(Heading);
holder.NieuwsTextViewExcerpt.setText(Excerpt);
Picasso.get().load(ImageUrl).fit().centerInside().into(holder.NieuwsImageView);
}
#Override
public int getItemCount() {
return NieuwsList.size();
}
public class NieuwsViewHolder extends RecyclerView.ViewHolder {
public ImageView NieuwsImageView;
public TextView NieuwsTextViewHeading;
public TextView NieuwsTextViewExcerpt;
public NieuwsViewHolder(#NonNull View itemView) {
super(itemView);
NieuwsImageView = itemView.findViewById(R.id.nieuws_image);
NieuwsTextViewHeading = itemView.findViewById(R.id.nieuws_heading);
NieuwsTextViewExcerpt = itemView.findViewById(R.id.nieuws_excerpt);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (NieuwsListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
NieuwsListener.onItemClick(position);
}
}
}
});
}
}
}
DetailActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Intent intent = getIntent();
String imageUrl = intent.getStringExtra("EXTRA_URL");
String creatorName = intent.getStringExtra("EXTRA_HEADING");
String likeCount = intent.getStringExtra("EXTRA_CONTENT");
ImageView imageView = findViewById(R.id.nieuws_detail_image);
TextView textViewHeading = findViewById(R.id.nieuws_detail_heading);
TextView textViewContent = findViewById(R.id.nieuws_detail_content);
Picasso.get().load(imageUrl).fit().centerInside().into(imageView);
textViewHeading.setText(creatorName);
textViewContent.setText("Likes: " + likeCount);
}
}
You cant use NieuwsAdapter.setOnItemClickListener(getActivity()); , unless your activity implements OnItemClickListener interface, but im seeing that your fragment implements OnItemClickListener, so you can use the fragment instead like this :
fNieuwsAdapter.setOnItemClickListener(NieuwsFragment.this);
And by the way, you are sending the data via intent with :
detailIntent.putExtra(EXTRA_URL, clickedItem.getImageUrl());
detailIntent.putExtra(EXTRA_HEADING, clickedItem.getHeading());
detailIntent.putExtra(EXTRA_CONTENT, clickedItem.getContent());
You have to get them with the same parameters (remove the ""):
String imageUrl = intent.getStringExtra(EXTRA_URL);
String creatorName = intent.getStringExtra(EXTRA_HEADING);
String likeCount = intent.getStringExtra(EXTRA_CONTENT);
Hope this helps
change
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist) {
NieuwsContext = context;
NieuwsList = nieuwslist;
}
to
public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist, OnItemClickListener mOnClickListener) {
this.NieuwsContext = context;
this.NieuwsList = nieuwslist;
this.NieuwsListener = mOnClickListener;
}
and this
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (NieuwsListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
NieuwsListener.onItemClick(position);
}
}
}
});
change to
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NieuwsListener.onItemClick(int position);
}
});
and then in fragment You can do it like this
fNieuwsAdapter = new NieuwsAdapter(getActivity(), fNieuwsList,new NieuwsAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position)
{
//DoSomethingHere
}
});
i am working of live search with MySQL, JSON. its working fine with local array values. but not working with MySQL. my concern is when user start typing it has to search from data base and show it in listview. bellow is my Adapter for search
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import zesteve.com.myapplication.R;
import zesteve.com.myapplication.Search;
import zesteve.com.myapplication.VendProfileActivity;
/**
* Created by Ravi Shankar on 6/22/2017.
*/
public class SearchAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<Search> vendersearchlist = null;
private ArrayList<Search> arraylist;
public SearchAdapter(Context context,
List<Search> vendersearchlist) {
mContext = context;
this.vendersearchlist = vendersearchlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<Search>();
this.arraylist.addAll(vendersearchlist);
}
public class ViewHolder {
TextView id;
TextView vname;
}
#Override
public int getCount() {
return vendersearchlist.size();
}
#Override
public Search getItem(int position) {
return vendersearchlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.search_item_list, null);
// Locate the TextViews in listview_item.xml
//holder.id = (TextView) view.findViewById(R.id.id);
holder.vname = (TextView) view.findViewById(R.id.autoCompleteTextView);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
//holder.rank.setText(Search.get(position).getRank());
holder.vname.setText(vendersearchlist.get(position).getVname());
// Listen for ListView Item Click
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, VendProfileActivity.class);
// Pass all data rank
intent.putExtra("Vend_Id",
(vendersearchlist.get(position).getId()));
// Pass all data country
intent.putExtra("Vend_Name",
(vendersearchlist.get(position).getVname()));
// Pass all data population
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
vendersearchlist.clear();
if (charText.length() == 0) {
vendersearchlist.addAll(arraylist);
} else {
for (Search sl : arraylist) {
if (sl.getVname().toLowerCase(Locale.getDefault())
.contains(charText)) {
vendersearchlist.add(sl);
}
}
}
notifyDataSetChanged();
}
}
AND POJO
public class Search {
private int id;
private String vname;
public Search(int id, String vname) {
this.id = id;
this.vname = vname;
}
public int getId() {
return this.id;
}
public String getVname() {
return this.vname;
}
}
And my SearchActivity.java
import android.content.res.Resources;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import zesteve.com.myapplication.adapter.SearchAdapter;
import zesteve.com.myapplication.adapter.VenderAdapter;
public class Search_vender extends AppCompatActivity {
String catname,city;
int catid;
private EditText Vendname;
private Session session;
ListView listview;
SearchAdapter adapter;
int[] id;
String[] vname;
ArrayList<Search> vendersearchlist = new ArrayList<Search>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_vender);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
session = new Session(Search_vender.this);
catid = getIntent().getIntExtra("CatId",00);
catname= getIntent().getStringExtra("CatName");
city = session.getUserLocation().get(session.KEY_UCITY);
listview = (ListView) findViewById(R.id.listview);
Vendname = (EditText) findViewById(R.id.searchitem);
Vendname.setHint("Search "+catname+" in "+city);
//fetch data from server in json
String vsearch = Vendname.getText().toString();
prepareVender(vsearch);
// Pass results to ListViewAdapter Class
adapter = new SearchAdapter(this, vendersearchlist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Locate the EditText in listview_main.xml
Vendname.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = Vendname.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
}
private void prepareVender(String sText){
AsyncTask<String,Void,Void> task = new AsyncTask<String, Void, Void>() {
#Override
protected Void doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/vend_list.php?city="+city+"&catid="+catid+"&name="+strings[0])
.build();
try{
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object= array.getJSONObject(i);
Search vender = new Search(object.getInt("id"),
object.getString("name"));
vendersearchlist.add(vender);
}
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of Catagory");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
adapter.notifyDataSetChanged();
}
};
task.execute(sText);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
Please comment if you have any doubts.
if Somebody looking for same Solution. bellow is my code
public class Search_vender extends AppCompatActivity {
String catname,city;
int catid;
SearchView Vendname;
private Session session;
ListView listview;
SearchAdapter adapter;
ArrayList<Search> vendersearchlist = new ArrayList<Search>();
ArrayList<Search> filteredSearchResults = new ArrayList<Search>();
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_vender);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
session = new Session(Search_vender.this);
progressDialog = new ProgressDialog(Search_vender.this);
progressDialog.setCancelable(false);
catid = getIntent().getIntExtra("CatId",00);
catname= getIntent().getStringExtra("CatName");
city = session.getUserLocation().get(session.KEY_UCITY);
//Toast.makeText(Search_vender.this,catid + city,Toast.LENGTH_LONG).show();
listview = (ListView) findViewById(R.id.listview);
Vendname = (SearchView) findViewById(R.id.searchitem);
Vendname.setQueryHint("Search "+catname+" in "+city);
Vendname.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
//Toast.makeText(Search_vender.this, String.valueOf(hasFocus),Toast.LENGTH_SHORT).show();
}
});
Vendname.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if(newText.length() > 2){
listview.setVisibility(View.VISIBLE);
GetDataVender gv = (GetDataVender) new GetDataVender().execute(newText);
}else{
listview.setVisibility(View.INVISIBLE);
}
return false;
}
});
}
public void filterSearchArray(String newText){
String pName;
filteredSearchResults.clear();
for (int i = 0; i < vendersearchlist.size(); i++)
{
pName = vendersearchlist.get(i).getVname().toLowerCase();
if ( pName.contains(newText.toLowerCase()))
{
filteredSearchResults.add(vendersearchlist.get(i));
}
}
}
class GetDataVender extends AsyncTask<String, Void, String>{
String textsearch;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Loading Please Wait...");
showDialog();
}
#Override
protected String doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/autosearch.php?city="+city+"&catid="+catid+"&name="+strings[0])
.build();
this.textsearch = strings[0];
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object =array.getJSONObject(i);
Search catagory = new Search(object.getInt("id"),
object.getString("name"));
vendersearchlist.add(catagory);
}
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of Catagory");
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null && result.equalsIgnoreCase("Exception Caught")){
Toast.makeText(Search_vender.this, "Unable to connect to server,please try later", Toast.LENGTH_LONG).show();
hideDialog();
}else{
filterSearchArray(textsearch);
listview.setAdapter(new SearchAdapter(Search_vender.this,filteredSearchResults));
hideDialog();
}
//hideDialog();
//adapter.notifyDataSetChanged();
}
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
it works when user stat search from second character.
I have been trying to call methods on the Main Activity from another class. But, the methods are not resolved. Check out the code.
package com.example.android.andhive_glideimagelib.activity;
import android.app.ProgressDialog;
import android.media.Image;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.android.andhive_glideimagelib.R;
import com.example.android.andhive_glideimagelib.adapter.GalleryAdapter;
import com.example.android.andhive_glideimagelib.app.AppController;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private static final String endpoint = "http://api.androidhive.info/json/glide.json";
private ArrayList<Image> images;
private ProgressDialog pDialog;
private GalleryAdapter mAdapter;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
pDialog = new ProgressDialog(this);
images = new ArrayList<>();
mAdapter = new GalleryAdapter(getApplicationContext(), images);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
recyclerView.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(getApplicationContext(), recyclerView, new GalleryAdapter.ClickListener() {
#Override
public void onClick(View view, int position) {
Bundle bundle = new Bundle();
bundle.putSerializable("images", images);
bundle.putInt("position", position);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
SlideshowDialogFragment newFragment = SlideshowDialogFragment.newInstance();
newFragment.setArguments(bundle);
newFragment.show(ft, "slideshow");
}
#Override
public void onLongClick(View view, int position) {
}
}));
fetchImages();
}
private void fetchImages() {
pDialog.setMessage("Downloading json...");
pDialog.show();
JsonArrayRequest req = new JsonArrayRequest(endpoint,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
pDialog.hide();
images.clear();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i);
Image image = new Image();
image.setName(object.getString("name"));
JSONObject url = object.getJSONObject("url");
image.setSmall(url.getString("small"));
image.setMedium(url.getString("medium"));
image.setLarge(url.getString("large"));
image.setTimestamp(object.getString("timestamp"));
images.add(image);
} catch (JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
}
}
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
}
The Class,
package com.example.android.andhive_glideimagelib.model;
import java.io.Serializable;
public class Image implements Serializable {
private String name;
private String small, medium, large;
private String timestamp;
public Image() {
}
public Image(String name, String small, String medium, String large, String timestamp) {
this.name = name;
this.small = small;
this.medium = medium;
this.large = large;
this.timestamp = timestamp;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSmall() {
return small;
}
public void setSmall(String small) {
this.small = small;
}
public String getMedium() {
return medium;
}
public void setMedium(String medium) {
this.medium = medium;
}
public String getLarge() {
return large;
}
public void setLarge(String large) {
this.large = large;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
}
I can't call the methods of the Image class. Thanks for the help !
in the image class make it static method
example:
public static void setSmall(String small){
this.small=small;
}
in MainActivity
Image.setSmall("value");
I create an activity and want to insert a new realm object
it always keep on error http null if i put getNextKey();
here is my activity
package com.example.rikirikmen.billsplit;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.rikirikmen.billsplit.Adapter.BillListAdapter;
import com.example.rikirikmen.billsplit.Adapter.MenuAdapter;
import com.example.rikirikmen.billsplit.Model.Bill;
import com.example.rikirikmen.billsplit.Model.DetailMenu;
import com.example.rikirikmen.billsplit.Model.DetailPerson;
import com.example.rikirikmen.billsplit.Model.PersonInMenu;
import com.example.rikirikmen.billsplit.Model.PersonMenuObj;
import org.w3c.dom.Text;
import java.util.ArrayList;
import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmList;
import io.realm.RealmObject;
public class DialogActivity extends AppCompatActivity {
Realm realm;
private RealmList<DetailPerson> person;
private RealmList<PersonInMenu> pim;
private ListView listView;
private MenuAdapter adapter;
private TextView menuName;
private TextView menuPrice;
private TextView menuQty;
private String bill;
private Button btnOke;
private Button btnCancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_add_menu);
realm = Realm.getDefaultInstance();
bill = getIntent().getStringExtra("bill_ID");
btnOke = (Button) findViewById(R.id.btnOkMenu);
btnCancel = (Button) findViewById(R.id.btnCancelMenu);
menuName = (TextView) findViewById(R.id.txtMenuName);
menuPrice = (TextView) findViewById(R.id.txtMenuPrice);
menuQty = (TextView) findViewById(R.id.txtMenuQuantity);
listView = (ListView) findViewById(R.id.listViewMenu);
Toast.makeText(this, getNextKey(), Toast.LENGTH_SHORT).show();
person = realm.where(Bill.class).equalTo("Bill_ID", bill).findFirst().getDetailperson();
if (person.isEmpty()){
}
else{
adapter = new MenuAdapter(this,R.layout.row_menu, person,bill);
listView.setAdapter(adapter);
}
btnOke.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (menuName.getText().length()==0 || menuPrice.getText().length()==0|| menuQty.getText().length()==0){
Toast.makeText(DialogActivity.this, "Please fill the menu detail", Toast.LENGTH_SHORT).show();
}
else {
CharSequence priceText = menuPrice.getText();
int Price = Integer.parseInt(priceText.toString());
CharSequence qtyText = menuQty.getText();
int Qty = Integer.parseInt(qtyText.toString());
realm.beginTransaction();
DetailMenu menu = realm.createObject(DetailMenu.class);
menu.setMenuID(getNextKey());
menu.setMenuName(String.valueOf(menuName.getText()));
menu.setMenuPrice(Price);
menu.setQuantity(Qty);
for (int i = 0; i < adapter.getPersonMenuObjList().size(); i++) {
PersonInMenu pim = realm.createObject(PersonInMenu.class);
pim.setPersonID(adapter.getPersonMenuObjList().get(i).getPersonID());
pim.setStatus(adapter.getPersonMenuObjList().get(i).isStatus());
menu.personInMenus.add(pim);
}
realm.copyToRealmOrUpdate(menu);
realm.commitTransaction();
realm.close();
}
}
});
}
int getNextKey()
{
return realm.where(DetailMenu.class).max("MenuID").intValue() + 1;
}
}
here is my DetailMenu.class
package com.example.rikirikmen.billsplit.Model;
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import io.realm.annotations.Required;
/**
* Created by rikirikmen on 4/24/2016.
*/
public class DetailMenu extends RealmObject {
#PrimaryKey
private int MenuID;
private int Quantity;
private String MenuName;
private int MenuPrice;
public RealmList<PersonInMenu> personInMenus;
public RealmList<PersonInMenu> getPersonInMenus() {
return personInMenus;
}
public void setPersonInMenus(RealmList<PersonInMenu> personInMenus) {
this.personInMenus = personInMenus;
}
public DetailMenu() {
super();
}
public int getMenuPrice() {
return MenuPrice;
}
public void setMenuPrice(int menuPrice) {
MenuPrice = menuPrice;
}
public int getMenuID() {
return MenuID;
}
public void setMenuID(int menuID) {
MenuID = menuID;
}
public String getMenuName() {
return MenuName;
}
public void setMenuName(String menuName) {
MenuName = menuName;
}
public int getQuantity() {
return Quantity;
}
public void setQuantity(int quantity) {
Quantity = quantity;
}
}
i dont know why is my getNextKey() is not work, because i used the same way in other activity and it works. Does anyone here have the same problem with me ?
max returns a Number or null if no objects exists. So most likely no DetailMenu objects exist and you get a NullPointerException.
Use this instead:
Number max = realm.where(DetailMenu.class).max("MenuID");
return (max != null) ? max.intValue() + 1 : 0;