get data from recycler card view into our main activity - android

// data is fetched from card but randon data is fetched using viewholder
//how to get proper and exact data.
//here are the all codes that i am using to recycler view
1. List item
package com.example.jains.attendencemanagementsystem;
/**
* Created by jains on 6/28/2017.
*/
import android.content.Context;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.util.List;
import static com.example.jains.attendencemanagementsystem.ViewHolder.IdTextView;
import static com.example.jains.attendencemanagementsystem.ViewHolder.NameTextView;
/**
* Created by JUNED on 6/16/2016.
*/
public class RecyclerViewAdapter extends RecyclerView.Adapter<ViewHolder> {
Context context;
RadioGroup myradiogroup;
RadioButton mySelectedRadioButton;
private RadioButton lastCheckedRB = null;
List<GetDataAdapter> getDataAdapter;
public RecyclerViewAdapter(List<GetDataAdapter> getDataAdapter, Context context){
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
NameTextView.setText(getDataAdapter1.getName());
IdTextView.setText(String.valueOf(getDataAdapter1.getId()));
// holder.status.setText(String.valueOf());
/** holder.setButtonClickListener(new ButtonClickListener() {
#Override
public void onButtonClick(View v, int pos) {
Snackbar.make(v, "Student " + getDataAdapter.get(pos).getName() + getDataAdapter.get(pos).getId() + " is selected", Snackbar.LENGTH_SHORT).show();
}
});
**/
View.OnClickListener rbClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioButton checked_rb = (RadioButton) v;
if (lastCheckedRB != null) {
lastCheckedRB.setChecked(false);
}
lastCheckedRB = checked_rb;
}
};
/** View.OnClickListener save =new View.OnClickListener() {
#Override public void onClick(View v) {
String date = dateView.getText().toString();
String mySelectedText = mySelectedRadioButton.getText().toString();
String a=getDataAdapter1.getName().toString();
String b=String.valueOf(getDataAdapter1.getId());
String type = "take";
BackgroundWorker_attendance_submit backgroundWorker = new BackgroundWorker_attendance_submit(context);
backgroundWorker.execute(type, a, b, mySelectedText, date);
}
**/
holder.P.setOnClickListener(rbClick);
holder.A.setOnClickListener(rbClick);
holder.L.setOnClickListener(rbClick);
holder.S.setOnClickListener(rbClick);
// holder.button0.setOnClickListener(save);
//CLICKED
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v, int pos) {
Snackbar.make(v, "Student " + getDataAdapter.get(pos).getName() + getDataAdapter.get(pos).getId() + " is selected", Snackbar.LENGTH_SHORT).show();
}
});
}
/**
cardView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
Intent i = new Intent (view.getContext(), take_attendance.class);
i.putExtra("nn",NameTextView.getText().toString());
i.putExtra("ii",IdTextView.getText());
view.getContext().startActivity(i);
}
});
**/
#Override
public int getItemCount() {
return getDataAdapter.size();
}
}
package com.example.jains.attendencemanagementsystem;
/**
* Created by jains on 6/24/2017.
*/
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by jains on 26//2017.
*/
public class BackgroundWorker_attendance_submit extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker_attendance_submit(Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://192.168.43.216/a_record_submit.php";
if(type.equals("take")) {
try {
int University_roll = Integer.parseInt(params[1]);
String student_name= params[2];
String status=params[3];
String date =params[4];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("University_roll","UTF-8")+"="+URLEncoder.encode(String.valueOf(University_roll),"UTF-8")+"&"
+URLEncoder.encode("student_name","UTF-8")+"="+URLEncoder.encode(student_name,"UTF-8")+"&"
+URLEncoder.encode("status","UTF-8")+"="+URLEncoder.encode(String.valueOf(status),"UTF-8")+"&"
+URLEncoder.encode("date","UTF-8")+"="+URLEncoder.encode(date,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Registration Status...");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}`package com.example.jains.attendencemanagementsystem;
/**
* Created by jains on 7/1/2017.
*/
import android.view.View;
/**
* Created by Hp on 3/18/2016.
*/
public interface ItemClickListener {
void onItemClick(View v,int pos);
}`package com.example.jains.attendencemanagementsystem;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
/**
* Created by jains on 7/2/2017.
*/
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ItemClickListener itemClickListener;
ButtonClickListener buttonClickListener;
static TextView IdTextView;
static TextView NameTextView;
static RadioButton P, A, L, S;
static Button button11;
RadioGroup myradiogroup;
RadioButton mySelectedRadioButton;
static CardView cardView;
public ViewHolder(View itemView) {
super(itemView);
IdTextView = (TextView) itemView.findViewById(R.id.textView2);
NameTextView = (TextView) itemView.findViewById(R.id.textView4);
itemView.setOnClickListener(this);
P = (RadioButton) itemView.findViewById(R.id.checkBoxP);
A = (RadioButton) itemView.findViewById(R.id.checkBoxA);
L = (RadioButton) itemView.findViewById(R.id.checkBoxL);
S = (RadioButton) itemView.findViewById(R.id.checkBoxS);
//this button is submit attendance button in card
button11 = (Button) itemView.findViewById(R.id.button11);
//these are the 4 radio button and radio group
myradiogroup = (RadioGroup) itemView.findViewById(R.id.myradiogroup);
int id = myradiogroup.getCheckedRadioButtonId();
mySelectedRadioButton = (RadioButton) itemView.findViewById(id);
cardView = (CardView)itemView.findViewById(R.id.cardview1);
}
#Override
public void onClick(View v) {
this.itemClickListener.onItemClick(v, getLayoutPosition());
}
public void setItemClickListener(ItemClickListener ic) {
this.itemClickListener = ic;
}
/** #Override
public void save(View view)
{
this.buttonClickListener.onButtonClick(view ,getLayoutPosition());
}
public void setButtonClickListener(ButtonClickListener bc)
{
this.buttonClickListener=bc;
}
**/
} /**
#Override
public void onClick(View v) {
**/
package com.example.jains.attendencemanagementsystem;
/**
* Created by jains on 6/28/2017.
*/
import android.content.Context;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.util.List;
import static com.example.jains.attendencemanagementsystem.ViewHolder.IdTextView;
import static com.example.jains.attendencemanagementsystem.ViewHolder.NameTextView;
/**
1. Created by JUNED on 6/16/2016.
*/
public class RecyclerViewAdapter extends RecyclerView.Adapter<ViewHolder> {
Context context;
RadioGroup myradiogroup;
RadioButton mySelectedRadioButton;
private RadioButton lastCheckedRB = null;
List<GetDataAdapter> getDataAdapter;
public RecyclerViewAdapter(List<GetDataAdapter> getDataAdapter, Context context){
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
NameTextView.setText(getDataAdapter1.getName());
IdTextView.setText(String.valueOf(getDataAdapter1.getId()));
// holder.status.setText(String.valueOf());
/** holder.setButtonClickListener(new ButtonClickListener() {
#Override
public void onButtonClick(View v, int pos) {
Snackbar.make(v, "Student " + getDataAdapter.get(pos).getName() + getDataAdapter.get(pos).getId() + " is selected", Snackbar.LENGTH_SHORT).show();
}
});
**/
View.OnClickListener rbClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioButton checked_rb = (RadioButton) v;
if (lastCheckedRB != null) {
lastCheckedRB.setChecked(false);
}
lastCheckedRB = checked_rb;
}
};
/** View.OnClickListener save =new View.OnClickListener() {
#Override public void onClick(View v) {
String date = dateView.getText().toString();
String mySelectedText = mySelectedRadioButton.getText().toString();
String a=getDataAdapter1.getName().toString();
String b=String.valueOf(getDataAdapter1.getId());
String type = "take";
BackgroundWorker_attendance_submit backgroundWorker = new BackgroundWorker_attendance_submit(context);
backgroundWorker.execute(type, a, b, mySelectedText, date);
}
**/
holder.P.setOnClickListener(rbClick);
holder.A.setOnClickListener(rbClick);
holder.L.setOnClickListener(rbClick);
holder.S.setOnClickListener(rbClick);
// holder.button0.setOnClickListener(save);
//CLICKED
holder.setItemClickListener(new ItemClickListener() {
#Override
public void onItemClick(View v, int pos) {
Snackbar.make(v, "Student " + getDataAdapter.get(pos).getName() + getDataAdapter.get(pos).getId() + " is selected", Snackbar.LENGTH_SHORT).show();
}
});
}
/**
cardView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
Intent i = new Intent (view.getContext(), take_attendance.class);
i.putExtra("nn",NameTextView.getText().toString());
i.putExtra("ii",IdTextView.getText());
view.getContext().startActivity(i);
}
});
**/
#Override
public int getItemCount() {
return getDataAdapter.size();
}
}
2. List item
package com.example.jains.attendencemanagementsystem;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
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.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class take_attendance extends AppCompatActivity {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
ProgressBar progressBar;
TextView uni,name;
RadioButton radioButton_P,radioButton_A,radioButton_L,radioButton_S;
private DatePicker datePicker;
private Calendar calendar;
private TextView dateView;
private int year, month, day;
// SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
// String t_name= sharedPreferences.getString(Config.NAME_SHARED_PREF,"Not Available");
//TextView textView=(TextView)findViewById(R.id.showuser);
//
String GET_JSON_DATA_HTTP_URL = "http://192.168.43.216/fetch_stud.php?t_name=";
String JSON_STUDENT_NAME = "student_name";
String JSON_UNIVERSITY_ROLL = "University_roll";
Button button0;
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
RadioButton mySelectedRadioButton;
RadioGroup myradiogroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.take_attendance);
//uni=(TextView)findViewById(R.id.textView2);
//name=(TextView)findViewById(R.id.textView4);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
button0 = (Button)findViewById(R.id.button0) ;
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//button0.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.VISIBLE);
JSON_DATA_WEB_CALL();
}
});
dateView = (TextView) findViewById(R.id.textView3);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month+1, day);
}
public void save(View view)
{
saving();
}
private void saving()
{
// I want to get Student name and University Roll grom the card content which button is clicked by the user
String a= ViewHolder.IdTextView.getText().toString();
String b= ViewHolder.NameTextView.getText().toString();
String date = dateView.getText().toString();
myradiogroup=(RadioGroup)findViewById(R.id.myradiogroup);
int id = myradiogroup.getCheckedRadioButtonId();
mySelectedRadioButton = (RadioButton) findViewById(id);
String mySelectedText = mySelectedRadioButton.getText().toString();
String type = "take";
BackgroundWorker_attendance_submit backgroundWorker = new BackgroundWorker_attendance_submit(this);
backgroundWorker.execute(type, a,b,mySelectedText,date);
//Intent y= new Intent(register_main.this,teacher.class);
//startActivity(y);
// Toast.makeText(register_main.this, "Successfully Registered...!!!", Toast.LENGTH_LONG).show();
}
public void JSON_DATA_WEB_CALL(){
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
final String aa= sharedPreferences.getString(Config.NAME_SHARED_PREF,"Not Available");
final String a= GET_JSON_DATA_HTTP_URL.concat(aa);
jsonArrayRequest = new JsonArrayRequest(a,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.GONE);
// button0.setVisibility(View.GONE);
Snackbar.make(recyclerView,"Note--> Take Attendance Of All Students ",1000000000).setDuration(1000000000).show();
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setId(json.getInt(JSON_UNIVERSITY_ROLL));
GetDataAdapter2.setName(json.getString(JSON_STUDENT_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
//DATE PICKER FUNCTIONS
#SuppressWarnings("deprecation")
public void setDate(View view) {
showDialog(999);
}
#Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this,
myDateListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener myDateListener = new
DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0,
int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
// arg1 = year
// arg2 = month
// arg3 = day
showDate(arg1, arg2+1, arg3);
}
};
private void showDate(int year, int month, int day) {
dateView.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
}

Related

Array size in GetChild method is wrong in ExpandableListView

I implemented ExpandableListView using this example, the only 2 diff from my code and example code is: I implemented on dialog box instead of activity and 2nd diff is my data is coming from SQLite.
So, I successfully implemented ExpandableListView and data is coming on perfect position according to group/child pos also. There is no issue in the code.
Now, later I implemented search functionality in the same ExpandableListAdapter.
Problem: Suppose, I want to search Electricity, (which is twice in my case also "E" is matching in more than one time) So, when I search "E", it shows me a list of matches with "E" and that is good, but when I do the second letter "L" it crashes on getChild method and tells me that index is "1" and size is "1" I know it should be 2, but I don't know how is it possible? Because the same getChild method works when it shows me the ExpandableList!!
I tried to debug also, that main Group size is coming right for the first time, but later it remains zero (0).
See:
Code:
Dialog Class:
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.tekitsolutions.remindme.Adapter.CustomSpinnerAdapter;
import com.tekitsolutions.remindme.Adapter.CustomSpinnerClass;
import com.tekitsolutions.remindme.Adapter.DialogListAdapter;
import com.tekitsolutions.remindme.Adapter.ExpandableCategoryAdapter;
import com.tekitsolutions.remindme.Interface.CategoryListener;
import com.tekitsolutions.remindme.Interface.HamburgerMenuListener;
import com.tekitsolutions.remindme.Interface.ResultListener;
import com.tekitsolutions.remindme.Model.CategoryHeader;
import com.tekitsolutions.remindme.Model.CategoryResponse;
import com.tekitsolutions.remindme.Model.CustomCategory;
import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.ProvidersInfo;
import com.tekitsolutions.remindme.Model.Reminder;
import com.tekitsolutions.remindme.R;
import com.tekitsolutions.remindme.RestApi.ApiClient;
import com.tekitsolutions.remindme.RestApi.ApiInterface;
import com.tekitsolutions.remindme.Sql.DatabaseAdapter;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.content.Context.MODE_PRIVATE;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.CUSTOM_CATEGORY_ID;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.PROVIDER_CATEGORY_ID;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.PROVIDER_ID;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_CATEGORY_ACCOUNT_NUMBER;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_CATEGORY_ALIAS_NAME;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_CATEGORY_ID;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_CATEGORY_OWNER_NAME;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_CATEGORY_PROVIDER_ID;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_CATEGORY_PROVIDER_NAME;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_CATEGORY_PROVIDER_NUMBER;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_CATEGORY_SUB_PROVIDER_ID;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.SUB_PROVIDER_ID;
import static com.tekitsolutions.remindme.Utils.CommonUtils.CUSTOM_HEADER;
import static com.tekitsolutions.remindme.Utils.CommonUtils.ELECTRICITY_BILL;
import static com.tekitsolutions.remindme.Utils.CommonUtils.ELECTRICITY_BILL_ID;
import static com.tekitsolutions.remindme.Utils.CommonUtils.GAS;
import static com.tekitsolutions.remindme.Utils.CommonUtils.GAS_ID;
import static com.tekitsolutions.remindme.Utils.CommonUtils.GENERAL_HEADER;
import static com.tekitsolutions.remindme.Utils.CommonUtils.INSURANCE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.INSURANCE_ID;
import static com.tekitsolutions.remindme.Utils.CommonUtils.LANDLINE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.LANDLINE_ID;
import static com.tekitsolutions.remindme.Utils.CommonUtils.NO_CATEGORY;
import static com.tekitsolutions.remindme.Utils.CommonUtils.OTHER_HEADER;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PHONE_NUMBER;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PICK_PROVIDER_CODE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PROFILE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.RESULT_FAILED;
import static com.tekitsolutions.remindme.Utils.CommonUtils.RESULT_OKAY;
import static com.tekitsolutions.remindme.Utils.CommonUtils.WATER_BILL;
import static com.tekitsolutions.remindme.Utils.CommonUtils.WATER_BILL_ID;
public class CategoryDialog extends BaseClass implements View.OnClickListener, Callback<String>, HamburgerMenuListener, ResultListener {
private static final String TAG = CategoryDialog.class.getSimpleName();
int i = 0;
private String landlineName, getProviderName, defaultName = "", phoneNum, customCategoryName, selected = "", getConsumerNum, getAccountNum, getOwnerName;
private long tempId = 0, categoryId, getCustomCategoryId, providerId, customCategoryId = 0, subProviderId;
private boolean stop = true, insurance, isEditPayment = false, isDeletedSQLite = false, isDeletedServer = false, isClicked = false;
private ExpandableCategoryAdapter expandableCategoryAdapter;
private List<CustomCategory> categories, customCategories;
private RecyclerView dialogRecyclerView;
private ExpandableListView expandableListView;
private DatabaseAdapter dbAdapter;
private Context context;
private SharedPreferences profilePreference;
private View promptsView;
private CustomCategory customCategory;
private List<Reminder> dialogListItems;
private ImageView info, search, close;
private DialogListAdapter dialogListAdapter;
private Activity activity;
private ProviderDialog providerDialog;
private TextView categoryToolbar, title, inputInsuranceProvider, textViewError, inputBillProvider, errorView, information, subProviderError, providerError, customProviderError, consumerError, ownerError;
private EditText searchText, userInput, inputConsumerNumber, name, inputAccountNumber, inputCustomProvider;
private ProvidersInfo providersInfo;
private AlertDialog informationDialog, mDialog;
private CategoryListener categoryListener;
private General provider, subProvider;
private RelativeLayout relativeProvider, subProviderLayout, accountLayout, customLayout;
private LinearLayout spinnerLayout;
private List<General> mainInsuranceList = new ArrayList<>();
private CustomSpinnerAdapter spinnerAdapter;
private CustomSpinnerClass spinInsuranceList;
private ArrayList<CategoryHeader> headerArrayList = new ArrayList<CategoryHeader>();
private CategoryHeader categoryHeader;
public CategoryDialog(Context context, Activity activity) {
super(context, activity);
this.activity = activity;
this.context = context;
}
private void init() {
categories = new ArrayList<>();
customCategories = new ArrayList<>();
dbAdapter = RemindMe.getInstance().adapter;
search = promptsView.findViewById(R.id.search);
close = promptsView.findViewById(R.id.close);
categoryToolbar = promptsView.findViewById(R.id.category_toolbar);
searchText = promptsView.findViewById(R.id.search_text);
dialogListItems = new ArrayList<>();
profilePreference = context.getSharedPreferences(PROFILE, MODE_PRIVATE);
providerDialog = new ProviderDialog(context);
providerDialog.setResultListener(this);
getDataFromSharedPref();
}
private void search() {
searchText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
expandableCategoryAdapter.filterData(s.toString());
if (count == 0) {
if (headerArrayList.size() == 0) {
loadSomeData();
}
expandAll();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private void loadSomeData() {
categoryHeader = new CategoryHeader(GENERAL_HEADER, categories);
headerArrayList.add(categoryHeader);
categoryHeader = new CategoryHeader(OTHER_HEADER, categories);
headerArrayList.add(categoryHeader);
categoryHeader = new CategoryHeader(CUSTOM_HEADER, customCategories);
headerArrayList.add(categoryHeader);
}
public void setCategoryListener(CategoryListener listener) {
this.categoryListener = listener;
}
private void setClickListener() {
search.setOnClickListener(this);
close.setOnClickListener(this);
}
public void showCategoryDialog() {
LayoutInflater li = LayoutInflater.from(context);
promptsView = li.inflate(R.layout.row_category_dialog_layout, null);
init();
findViewById();
setClickListener();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setView(promptsView);
alertDialogBuilder.setPositiveButton(context.getString(R.string.add), null);
alertDialogBuilder.setNegativeButton(context.getString(R.string.cancel), null);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.setCancelable(false);
recyclerView();
search();
mDialog = alertDialogBuilder.create();
mDialog.setCancelable(false);
mDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
Button buttonNegative = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEGATIVE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isEditPayment = false;
showDialogBox(0);
}
});
buttonNegative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
});
mDialog.show();
}
private void findViewById() {
expandableListView = promptsView.findViewById(R.id.expandableList);
}
private void recyclerView() {
loadArrayListData();
expandableCategoryAdapter = new ExpandableCategoryAdapter(context, headerArrayList, this);
try {
expandableListView.setAdapter(expandableCategoryAdapter);
} catch (Exception exp) {
exp.printStackTrace();
}
}
//method to expand all groups
private void expandAll() {
int count = expandableCategoryAdapter.getGroupCount();
for (int i = 0; i < count; i++) {
expandableListView.expandGroup(i);
}
}
ExpandableListAdapter:
import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.tekitsolutions.remindme.Interface.HamburgerMenuListener;
import com.tekitsolutions.remindme.Model.CategoryHeader;
import com.tekitsolutions.remindme.Model.CustomCategory;
import com.tekitsolutions.remindme.R;
import com.tekitsolutions.remindme.Utils.CommonUtils;
import java.util.ArrayList;
import java.util.List;
public class ExpandableCategoryAdapter extends BaseExpandableListAdapter {
private static final String TAG = ExpandableCategoryAdapter.class.getSimpleName();
private Context context;
private List<CategoryHeader> originalList;
private List<CategoryHeader> headerList;
private HamburgerMenuListener menuInterface;
public ExpandableCategoryAdapter(Context context, List<CategoryHeader> generalList, HamburgerMenuListener menuInterface) {
this.context = context;
this.headerList = new ArrayList<CategoryHeader>();
this.headerList.addAll(generalList);
this.originalList = generalList;
this.menuInterface = menuInterface;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
List<CustomCategory> countryList = headerList.get(groupPosition).getCategoryList();
return countryList.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
Resources resources = context.getResources();
CustomCategory customCategory = (CustomCategory) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.row_general_list, null);
}
TextView name = convertView.findViewById(R.id.tv_category_item);
ImageView icon = convertView.findViewById(R.id.iv_category_icon);
Button logo = convertView.findViewById(R.id.iv_custom_category_icon);
ImageView hamburgerMenu = convertView.findViewById(R.id.hamburger_menu);
if (customCategory != null) {
if (customCategory.getCustCategoryName() != null) {
name.setText(customCategory.getCustCategoryName().trim());
}
if (customCategory.getIcon() != null && customCategory.getCustCategoryId() <= CommonUtils.WATER_BILL_ID) {
icon.setVisibility(View.VISIBLE);
logo.setVisibility(View.GONE);
hamburgerMenu.setVisibility(View.GONE);
icon.setImageResource(resources.getIdentifier(customCategory.getIcon(), "drawable",
context.getPackageName()));
} else {
icon.setVisibility(View.GONE);
logo.setVisibility(View.VISIBLE);
hamburgerMenu.setVisibility(View.VISIBLE);
logo.setText(customCategory.getCustCategoryName().substring(0, 1));
}
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
menuInterface.onClickListItem(headerList.get(groupPosition).getCategoryList().get(childPosition).getCustCategoryId());
}
});
hamburgerMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (menuInterface != null) {
menuInterface.onClickHamburger(headerList.get(groupPosition).getCategoryList().get(childPosition).getCustCategoryId());
}
}
});
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
if (headerList.get(groupPosition).getHeaderName().equals(CommonUtils.GENERAL_HEADER)) {
return CommonUtils.LANDLINE_ID;
}
if (headerList.get(groupPosition).getHeaderName().equals(CommonUtils.OTHER_HEADER)) {
return CommonUtils.WATER_BILL_ID;
}
return headerList.get(groupPosition).getCategoryList().size();
}
#Override
public Object getGroup(int groupPosition) {
return headerList.get(groupPosition);
}
#Override
public int getGroupCount() {
return headerList.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
private void showLog(String msg) {
Log.d(TAG, msg);
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View view, ViewGroup parent) {
CategoryHeader categoryHeader = (CategoryHeader) getGroup(groupPosition);
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.row_custom_category_list, null);
}
TextView heading = view.findViewById(R.id.header_view);
heading.setText(categoryHeader.getHeaderName().trim());
return view;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void filterData(String query) {
query = query.toLowerCase();
headerList.clear();
if (query.isEmpty()) {
headerList.addAll(originalList);
} else {
for (CategoryHeader categoryHeader : originalList) {
List<CustomCategory> categoryList = categoryHeader.getCategoryList();
List<CustomCategory> newList = new ArrayList<CustomCategory>();
for (CustomCategory customCategory : categoryList) {
if (customCategory.getCustCategoryName().toLowerCase().contains(query)) {
newList.add(customCategory);
}
}
if (newList.size() > 0) {
CategoryHeader nContinent = new CategoryHeader(categoryHeader.getHeaderName(), newList);
headerList.add(nContinent);
}
}
}
notifyDataSetChanged();
}
}
Solved by adding separate arraylist according to header name. Also added field/tag in databse.
private void loadSomeData() {
List<CustomCategory> generalCategories = new ArrayList<>();
generalCategories.addAll(dbAdapter.getCategoryById(null, 0, GENERAL_HEADER));
List<CustomCategory> otherCategories = new ArrayList<>();
otherCategories.addAll(dbAdapter.getCategoryById(null, 0, OTHER_HEADER));
categoryHeader = new CategoryHeader(GENERAL_HEADER, generalCategories);
headerArrayList.add(categoryHeader);
categoryHeader = new CategoryHeader(OTHER_HEADER, otherCategories);
headerArrayList.add(categoryHeader);
categoryHeader = new CategoryHeader(CUSTOM_HEADER, customCategories);
headerArrayList.add(categoryHeader);
}

How to send multiple selected check box values to a server?

I want to send multiple selected checkbox travel id value to a server.
The code is working, but the value is not updating.
When the submit button is pressed, I want all the selected checkbox values to be sent to the server and the selected check box values are updated on the server.
package com.example.fiffa.fifaa;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ViewSubmission extends AppCompatActivity{
final Context context = this;
ListView listView;
String travelid;
TextView txtvisit,txtsum,txtsystem;
Button submit,back;
String MyPREFERENCES = "loginInfo";
SharedPreferences sharedpreferences;
ProgressDialog pDialog;
String ss="";
String userid;
boolean[] present;
boolean[] absent;
String takenatt="";
double gtotal=0.0;
List<Submitconvencelistitem> rowItems;
ArrayList<Submitconvencelistitem> feedsList;
Submitconvenceadapter adapter;
int count;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_submission);
submit = (Button) findViewById(R.id.submit);
back = (Button) findViewById(R.id.backviewsub);
txtvisit=(TextView)findViewById(R.id.txtvisit);
txtsum=(TextView)findViewById(R.id.txttotal);
//txtsystem=(TextView)findViewById(R.id.txtsystem);
listView = (ListView) findViewById(R.id.lstconveynce);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent viewsub=new Intent(ViewSubmission.this,Submitconveyance.class);
startActivity(viewsub);
}
});
String viewdata = getIntent().getExtras().getString("response", "");
Log.e("viewdata", viewdata);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
//conveyncetravelid = sharedpreferences.getString("travelid", "");
//Log.e("econveyncetravelid", conveyncetravelid);
userid = sharedpreferences.getString("userId", "");
Log.e("userId", userid);
try {
//feedsList=getSubmit(false);
JSONArray js = new JSONArray(viewdata);
feedsList=new ArrayList<>();
for (int i = 0; i < js.length(); i++) {
JSONObject jObject = js.getJSONObject(i);
Submitconvencelistitem st=new Submitconvencelistitem();
String total_amount=jObject.getString("total_amount");
Log.e("total_amount",total_amount);
//String travelid = jObject.getString("travelid");
//Log.e("conveyncetravelid", travelid);
st.settravelid(jObject.optString("travelid"));
st.setsubdate(jObject.optString("startdate"));
st.setstartlocation(jObject.optString("startlocation"));
st.setendlocation(jObject.optString("endlocation"));
st.setccno(jObject.optString("cc_no"));
st.setcustomername(jObject.optString("custname"));
st.setcallstatus(jObject.optString("callstatus"));;
st.setmodeofconveynce(jObject.optString("travel_mode"));
st.setkmstravelled(jObject.optString("KM"));
st.setclaimamout(jObject.optString("total_amount"));
//st.setSelected(true);
feedsList.add(st);
/* gtotal += Double.parseDouble(feedsList.get(i).getclaimamout());
Log.e("Total", String.valueOf(gtotal));
txtsum.setText(Double.toString(gtotal));*/
//Toast.makeText(MainActivity.this,result.toString(),Toast.LENGTH_LONG).show();
/* Log.e("shams", viewdata.toString());
String startdate = js.getJSONObject(0).getString("startdate");
Log.e("startdate",startdate);
String startlocation = js.getJSONObject(0).getString("startlocation");
Log.e("startlocation",startlocation);
String endlocation = js.getJSONObject(0).getString("endlocation");
Log.e("endlocation",endlocation);
String cc_no = js.getJSONObject(0).getString("cc_no");
Log.e("cc_no",cc_no);
String custname = js.getJSONObject(0).getString("custname");
Log.e("custname",custname);
String callstatus = js.getJSONObject(0).getString("callstatus");
Log.e("callstatus",callstatus);
String travel_mode = js.getJSONObject(0).getString("travel_mode");
Log.e("travel_mode",travel_mode);
String KM = js.getJSONObject(0).getString("KM");
Log.e("KM",KM);
String total_amount = js.getJSONObject(0).getString("total_amount");
Log.e("total_amount",total_amount);
st.setsubdate(startdate);
st.setstartlocation(startlocation);
st.setendlocation(endlocation);
st.setccno(cc_no);
st.setcustomername(custname);
st.setcallstatus(callstatus);
st.setmodeofconveynce(travel_mode);
st.setkmstravelled(KM);
st.setclaimamout(total_amount);
st.setSelected(true);*//*
feedsList.add(st);*/
/* JSONObject post = js.getJSONObject(i);
Submitconvencelistitem st=new Submitconvencelistitem();
st.setsubdate(post.optString("startdate"));
st.setstartlocation(post.optString("startlocation"));
st.setendlocation(post.optString("endlocation"));
st.setccno(post.optString("cc_no"));
st.setcustomername(post.optString("custname"));
st.setcallstatus(post.optString("callstatus"));
st.setmodeofconveynce(post.optString("travel_mode"));
st.setkmstravelled(post.optString("KM"));
st.setclaimamout(post.optString(("total_amount")));
st.setSelected(true);
feedsList.add(st);*/
}
adapter = new Submitconvenceadapter(ViewSubmission.this, feedsList);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
count=adapter.getCount();
txtvisit.setText(Integer.toString(count));
}
catch (JSONException e) {
e.printStackTrace();
}
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//final List<Submitconvencelistitem> selectedItems = adapter.getSelectedItems();
//Use this data for sending to your webserver
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ViewSubmission.this);
alertDialogBuilder.setMessage("Submit the Selected Conveynce");
alertDialogBuilder.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
for (int strt=0;strt<present.length;strt++) {
if (present[strt]) {
travelid = feedsList.get(strt).gettravelid();
}
new Asyncupdate_travelforconv().execute();
}
//Toast.makeText(ViewSubmission.this,"Your conveyance has been submitted ",Toast.LENGTH_LONG).show();
}
});
alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent view=new Intent(ViewSubmission.this,Submitconveyance.class);
startActivity(view);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
//new Asncselect_travelforconvsub().execute();
}
});
}
/* private ArrayList<Submitconvencelistitem> getSubmit(boolean isSelect){
ArrayList<Submitconvencelistitem> list = new ArrayList<>();
for(int i = 0; i < feedsList.size(); i++){
Submitconvencelistitem st = new Submitconvencelistitem();
st.setSelected(isSelect);
feedsList.add(st);
}
return list;
}
*/
/*Asynctask For Insertstart travel details*/
private class Asyncupdate_travelforconv extends AsyncTask<String, Integer, String> {
String SOAP_ACTION = "http://tempuri.org/IFIFA/update_travelforconv";
String NAMESPACE = "http://tempuri.org/";
String METHOD_NAME = "update_travelforconv";
String URL = "http://migadget.aforeserve.co.in/FIFA.svc?singleWsdl";
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... strings) {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("travelid", travelid);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
//envelope.setOutputSoapObject(request);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
Object result = null;
result = (Object) envelope.getResponse();
Log.e("conveynce", String.valueOf(result));
System.out.println("APIresult:" + result.toString());
ss = result.toString();
Log.e("APIRESULT", ss);
} catch (Exception e) {
System.out.println("Error" + e);
}
return ss;
} catch (Exception ex) {
ex.printStackTrace();
return "";
}
}
#Override
protected void onPostExecute(String result) {
Log.e("APIResult", result);
Toast.makeText(getBaseContext(), "Data Updated", Toast.LENGTH_LONG).show();
}
}
/*Adapter class For Submit conveynce */
public class Submitconvenceadapter extends BaseAdapter {
ArrayList<Submitconvencelistitem> listData;
private LayoutInflater layoutInflater;
Context context;
List<Submitconvencelistitem> rowItems;
String MyPREFERENCES = "loginInfo";
String travelid;
SharedPreferences sharedpreferences;
public Submitconvenceadapter(Context ViewSubmission,ArrayList<Submitconvencelistitem> results)
{
listData = results;
context=ViewSubmission;
present=new boolean[listData.size()];
Arrays.fill(present, true);
}
#Override
public int getCount()
{
return listData.size();
}
#Override
public Object getItem(int position)
{
return listData.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
LayoutInflater layoutInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_item_submitconveynce, null);
holder = new ViewHolder();
//holder.checkbox=(CheckBox) convertView.findViewById(R.id.cb1);
holder.date = (TextView) convertView.findViewById(R.id.subdate);
holder.startlocation = (TextView) convertView.findViewById(R.id.startlocation);
holder.endlocation=(TextView)convertView.findViewById(R.id.endlocation);
holder.ccno = (TextView) convertView.findViewById(R.id.ccno);
holder.customername = (TextView) convertView.findViewById(R.id.tv_name);
holder.callstatus = (TextView)convertView.findViewById(R.id.tv_callstatus);
holder.modeofconveynce = (TextView)convertView.findViewById(R.id.tv_modconveynce);
holder.Kmtravelled = (TextView)convertView.findViewById(R.id.tv_km);
holder.claimamount = (TextView)convertView.findViewById(R.id.claim_amount);
holder.checkbox=(CheckBox)convertView.findViewById(R.id.chk1);
/*//holder.checkbox.setChecked(true);
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
listData.get(position).setSelected(isChecked);
}
});*/
convertView.setTag(holder);
holder.checkbox.setChecked(present[position]);
}
else
{
holder = (ViewHolder) convertView.getTag();
holder.checkbox.setChecked(present[position]);
}
holder.checkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (holder.checkbox.isChecked())
present[position] = true;
else
present[position] = false;
}
});
//travelid=listData.get(position).gettravelid();
//holder.travelid.setText(listData.get(position).gettravelid());
holder.date.setText(listData.get(position).getsubdate());
holder.startlocation.setText(listData.get(position).getstartlocation());
holder.endlocation.setText(listData.get(position).getendlocation());
holder.ccno.setText(listData.get(position).getccno());
holder.customername.setText(listData.get(position).getcustomername());
holder.callstatus.setText(listData.get(position).getcallstatus());
holder.modeofconveynce.setText(listData.get(position).getmodeofconveynce());
holder.Kmtravelled.setText(listData.get(position).getkmstravelled());
holder.claimamount.setText(listData.get(position).getclaimamout());
//holder.checkbox.setChecked(true);
return convertView;
}
public class ViewHolder {
CheckBox checkbox;
TextView date;
TextView startlocation;
TextView endlocation;
TextView ccno;
TextView customername;
TextView callstatus;
TextView modeofconveynce;
TextView Kmtravelled;
TextView claimamount;
TextView travelid;
}
/* public List<Submitconvencelistitem> getSelectedItems()
{
List<Submitconvencelistitem> selectedItems = new ArrayList<>();
for(Submitconvencelistitem item : listData)
{
selectedItems.add(item);
}
return selectedItems;
}*/
}
}
I am assuming that you are using php over your server.What you can do is send the comma separated travel id's over server like this:-
Put travel id's into an arraylist or array like this:-
ArrayList<String> selectedTravelId= new ArrayList<>();
selectedTravelId.add(travelId); // add travel ids
StringBuilder travelId = new StringBuilder();
for (int i = 0; i < selectedTravelId.size(); i++) {
travelId .append(selectedTravelId.get(i));
if (!(i == selectedTravelId.size() - 1)) {
travelId .append(",");
}
}// to create travelId string
travelId.toString();// to convert StringBuilder to String
After this execute your AsyncTask.
You will get a string like e.g. 1,2,134,142.Now send this travelId to sever.
At server side retrieve
Try explode:
$mytravelId = " 1,2,134,142";
$myArray = explode(',', $mytravelId );
print_r($myArray);
Output :
Array
(
[0] => 1
[1] => 2
[2] => 134
[3] => 142
)

RecyclerView datas last row display with multiple time

I don't understand why my recyclerview is only showing the last row of my database although I initialised it with 150 datas.
I searched a lot in the internet and even here on SO, but not one of the solutions is working. Can you help me to figure out why my recyclerView is only showing the last row of the database? Thanks in advance to all of you.
May be you can help me. Here is my code:
package com.example.frontaddress.matedesignc;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Customer_Activity extends AppCompatActivity {
private List<String> StateListArray =new ArrayList<String>();
private List<String> StateList =new ArrayList<String>();
private List<String> CityListArray ;
private List<String> CityList ;
private Spinner dropdown_state;
private Spinner dropdown_city;
private DBHandler DB = new DBHandler(this);
private static final String BUSINESSNAME = "bussiness_name";
private static final String MOBILE = "mobile";
private static final String ADDRESS = "address";
private static final String ID = "id";
private Toolbar toolbar;
private Customer_list_Adapter adapter;
private RecyclerView recyclerView_Customer;
//ProgressDialog pDialog = new ProgressDialog(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer_list);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
GetStateList(); }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_sub, menu);
return true; }
public void CustomerDetails(String state,String city) throws IOException {
try {
List<customer_search_information> data = null;
data = new ArrayList<>();
customer_search_information current = new customer_search_information();
Cursor RST_CSTInfo = DB.getRows("customer", "id,bussiness_name,mobile,address", " state='" + state + "' AND city='" + city + "'");
while (!RST_CSTInfo.isAfterLast()) {
current.bussiness_name = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(BUSINESSNAME));
current.state = state;
current.city = city;
current.address = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(ADDRESS));
String Mob = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(MOBILE));
current.mobile_no = Mob;
current.e_mail = "mail.isigntech#gmail.com";
current.id = RST_CSTInfo.getString(RST_CSTInfo.getColumnIndex(ID));
// displayExceptionMessage(current.id+current.bussiness_name+current.state+current.city+current.address+current.mobile+current.email);
data.add(current);
RST_CSTInfo.moveToNext();
}
recyclerView_Customer = (RecyclerView) findViewById(R.id.drawerListCustomer);
recyclerView_Customer.setHasFixedSize(true);
recyclerView_Customer.setHasFixedSize(true);
recyclerView_Customer.setLayoutManager(new LinearLayoutManager(this));
adapter = new Customer_list_Adapter(this, data);
recyclerView_Customer.setAdapter(adapter);
}catch (Exception e){ displayExceptionMessage(e.toString());}
}
private void GetStateList()
{ Cursor Customer= DB.getRows("customer","state", " 1 GROUP BY state");
while(!Customer.isAfterLast()){
String state=Customer.getString(Customer.getColumnIndex("state"));
StateList.add(state);
StateListArray.add(state);
Customer.moveToNext();
}
dropdown_state = (Spinner)findViewById(R.id.SpnSrch_State);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Customer_Activity.this, android.R.layout.simple_spinner_dropdown_item, StateListArray);
dropdown_state.setAdapter(adapter);
dropdown_state.setPrompt("Choose State ");
dropdown_state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int item = dropdown_state.getSelectedItemPosition();
String state =StateListArray.get(item);
dropdown_city=(Spinner) findViewById(R.id.SpnSrch_State);
Cursor RstCity= DB.getRows("customer","city", "state='"+state+"' GROUP BY city");
CityListArray =new ArrayList<String>();
CityList =new ArrayList<String>();
while(!RstCity.isAfterLast()){
String city=RstCity.getString(RstCity.getColumnIndex("city"));
CityList.add(city);
CityListArray.add(city);
RstCity.moveToNext();
}
dropdown_city = (Spinner)findViewById(R.id.SpnSrch_City);
ArrayAdapter<String> cityadapter = new ArrayAdapter<String>(Customer_Activity.this, android.R.layout.simple_spinner_dropdown_item, CityListArray);
dropdown_city.setAdapter(cityadapter);
dropdown_city.setPrompt("Choose City ");
dropdown_city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
int item = dropdown_state.getSelectedItemPosition();
String state =StateListArray.get(item);
item = dropdown_city.getSelectedItemPosition();
String city =CityListArray.get(item);
try {
CustomerDetails(state,city);
} catch (Exception e) {
displayExceptionMessage(e.toString());
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
displayExceptionMessage("Please Select State.");
}
});
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
displayExceptionMessage("Please Select City.");
}
});
}
public void displayExceptionMessage(String msg) {
//TextView Txterror=(TextView) findViewById(R.id.txterror);
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
#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_settings) {
return true;
}
if (id == android.R.id.home) {
// NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItementer code hereSelected(item);
}
}
Here is my custom list adapter code:
package com.example.frontaddress.matedesignc;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
/**
* Created by frontaddress on 10/08/17.
*/
public class Customer_list_Adapter extends RecyclerView.Adapter<Customer_list_Adapter.CustomerViewHolder> {
private LayoutInflater inflater;
private Context contexts;
List<customer_search_information> Cst_data = Collections.emptyList();
public Customer_list_Adapter(Context context, List<customer_search_information> data) {
inflater = LayoutInflater.from(context);
this.Cst_data = data;
// Toast.makeText(contexts, data.size(), Toast.LENGTH_LONG).show();
this.contexts = context;
}
#Override
public CustomerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.content_search_staff, parent, false);
CustomerViewHolder holder = new CustomerViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(CustomerViewHolder holder, int position) {
try {
customer_search_information current = Cst_data.get(position);
Integer Pos=position;
holder.TxtBisinessName.setText(current.bussiness_name);
holder.TxtAddress.setText(current.address);
holder.Statecity.setText(current.state + "-" + current.city);
holder.Txt_Mobile.setText(current.mobile_no.toString());
holder.TxtEmail.setText(current.e_mail);
}catch (Exception e)
{
Toast.makeText(contexts,e.toString(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return Cst_data.size();
}
class CustomerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView TxtBisinessName;
TextView TxtAddress;
TextView Txt_Mobile;
TextView Statecity;
TextView TxtEmail;
ImageView ImgPhoneCall,ImgMailTo;
public CustomerViewHolder(View itemView) {
super(itemView);
TxtBisinessName = (TextView) itemView.findViewById(R.id.Txtbusiness_name);
Txt_Mobile = (TextView) itemView.findViewById(R.id.TxtMobile);
Statecity = (TextView) itemView.findViewById(R.id.Txtstatecity);
TxtAddress = (TextView) itemView.findViewById(R.id.Txtaddress);
TxtEmail=(TextView) itemView.findViewById(R.id.TxtEmail);
ImgPhoneCall = (ImageView) itemView.findViewById(R.id.ImgCallPhone);
ImgMailTo= (ImageView) itemView.findViewById(R.id.Imgmail);
ImgPhoneCall.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
customer_search_information current = Cst_data.get(getPosition());
String MOBILE = current.mobile_no;
try {
if (ActivityCompat.checkSelfPermission(contexts,Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(contexts, "Call Permission Not Granted ", Toast.LENGTH_LONG).show();
return;
}
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:+91" + MOBILE));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
contexts.startActivity(callIntent);
}
catch (Exception e){
Toast.makeText(contexts,e.toString(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
});
/* TxtProfile.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
customer_search_information current = data.get(getPosition());
String SID = current.id;
Intent intent = new Intent(contexts, StudentProfileActivity.class);
intent.putExtra("id", SID);
contexts.startActivity(intent);
}
});*/
ImgMailTo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// TODO Auto-generated method stub
customer_search_information current = Cst_data.get(getPosition());
String EMAIL = current.e_mail;
String BName = current.bussiness_name;
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, EMAIL);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "");
emailIntent.setType("text/plain");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Hi,"+BName);
final PackageManager pm = contexts.getPackageManager();
final List<ResolveInfo> matches = pm.queryIntentActivities(emailIntent, 0);
ResolveInfo best = null;
for (final ResolveInfo info : matches)
if (info.activityInfo.packageName.endsWith(".gm") || info.activityInfo.name.toLowerCase().contains("gmail"))
best = info;
if (best != null)
emailIntent.setClassName(best.activityInfo.packageName, best.activityInfo.name);
contexts.startActivity(emailIntent);
}
catch (Exception e){ }
}
});
}
#Override
public void onClick(View v) {
int ID=v.getId();
customer_search_information current=Cst_data.get(getPosition());
String SID=current.id;
// Toast.makeText(contexts,"Item Clicked Profile: "+ v.getId(), Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(contexts, StudentProfileActivity.class);
// intent.putExtra("id", SID);
// contexts.startActivity(intent);
}
}
}
I think the problem is here , instead of
while(!RST_CSTInfo.isAfterLast()){
...
..
RST_CSTInfo.moveToNext();
}
try this ....
do(RST_CSTInfo.movetofirst()){
// your logic
}while(cursor.movetonext())

check one box multiple boxes are checked

I am using custom listViewAdapter class and I want to check one box in a single row, but it is checking multiple checks in multiple rows which is not my requirement. Please tell me how can I resolve it.
CourseActivity.java
package com.technerdshub.vusocial.Activities;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.SaveCallback;
import com.technerdshub.vusocial.DBHelper;
import com.technerdshub.vusocial.Models.Course;
import com.technerdshub.vusocial.Models.StudyProgramModel;
import com.technerdshub.vusocial.Models.User;
import com.technerdshub.vusocial.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class CourseActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ListView list;
EditText editsearch;
ArrayList arrayList = new ArrayList();
CourseViewAdapter adapter;
Course courseObject;
boolean isChecked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.course_activity);
List<Course> courseList;
DBHelper db = new DBHelper(this);
courseList = db.getAllCourses();
list = (ListView) findViewById(R.id.listview1);
for (Course c : courseList) {
arrayList.add(c);
}
adapter = new CourseViewAdapter(this, arrayList);
adapter.courseActivity = this;
list.setAdapter(adapter);
editsearch = (EditText) findViewById(R.id.searchF);
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void afterTextChanged(Editable s) {
}
});
User user = User.getInstance();
saveUserOnParse(user);
}
private void saveUserOnParse(User user) {
ParseObject parseUser = new ParseObject("UserData");
parseUser.put("name", user.getName());
parseUser.put("vuId", user.getVuId());
parseUser.put("studyProgram", user.getStudyProgram());
parseUser.put("facebookId", user.getFacebookId());
parseUser.put("facebookEmail", user.getFacebookEmail());
parseUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
// Intent i = new Intent(getContext(), StudentDashboardActivity.class);
//// i.putExtra("E-mail", "abc");
// startActivity(i);
} else {
Toast temp = Toast.makeText(CourseActivity.this, "Data is not saved.", Toast.LENGTH_SHORT);
temp.show();
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 4
if (requestCode == 2) {
courseObject = (Course) data.getExtras().getSerializable("SelectedCourse");
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) view.findViewById(R.id.checkBox);
//  TextView tv = (TextView) v.findViewById(R.id.textView1);
cb.performClick();
if (cb.isChecked()) {
// checkedValue.add(tv.getText().toString());
} else if (!cb.isChecked()) {
// checkedValue.remove(tv.getText().toString());
}
}
}
CourseViewAdapter.java
package com.technerdshub.vusocial.Activities;
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.CheckBox;
import android.widget.TextView;
import com.technerdshub.vusocial.Models.Course;
import com.technerdshub.vusocial.Models.StudyProgramModel;
import com.technerdshub.vusocial.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Created by Saroosh on 7/16/2016.
*/
public class CourseViewAdapter extends BaseAdapter {
protected CourseActivity courseActivity;
Context mContext;
LayoutInflater inflater;
private List<Course>worldpopulationlist=null;
private ArrayList<Course> arraylist;
public CourseViewAdapter(Context context, List<Course>worldpopulationlist){
mContext = context;
this.worldpopulationlist = worldpopulationlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<Course>();
this.arraylist.addAll(worldpopulationlist);
}
public class ViewHolder {
TextView courseCode;
TextView courseName;
CheckBox checkBox;
}
#Override
public int getCount() {
return worldpopulationlist.size();
}
#Override
public Course getItem(int position) {
return worldpopulationlist.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.c_list_item, null);
// Locate the TextViews in listview_item.xml
holder.courseName = (TextView) view.findViewById(R.id.course_name);
holder.courseCode = (TextView) view.findViewById(R.id.course_code);
holder.checkBox= (CheckBox) view.findViewById(R.id.checkBox);
// holder.duration = (TextView) view.findViewById(R.id.program_duration);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.courseName.setText(worldpopulationlist.get(position).getCourseName());
holder.courseCode.setText(worldpopulationlist.get(position).getCourseCode());
//holder.duration.setText(worldpopulationlist.get(position).getDuration());
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, CourseActivity.class);
// Pass all data ran
intent.putExtra("SelectedCourse", worldpopulationlist.get(position));
// Pass all data country
courseActivity.setResult(2,intent);
courseActivity.finish();
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
}
else
{
for (Course wp : arraylist)
{
if (wp.getCourseName().toLowerCase(Locale.getDefault()).contains(charText))
{
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Write all your checkbox logic inside you adapter getView method. That will work .

How to get position of a button in a listview?

I have a listview with Textview, ImageView and Button ,what i would like is to change the background of the button when its clicked , i hope you understunded my issue .
This is the Adapter .
package com.example.mahdi.chat;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import circleview.CircleImageView;
public class FeedListAdapter extends BaseAdapter {
private static final String TAG = FeedListAdapter.class.getSimpleName();
private Activity activity;
private LayoutInflater inflater;
private List<FeedItem> feedItems;
JSONParser jsonParser = new JSONParser();
private String URL = "http://10.0.3.2/social/like.php";
private String user_id;
private Button like,comment;
private static final String TAG_SUCCESS = "success";
FeedItem item;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public FeedListAdapter(Activity activity, List<FeedItem> feedItems, String user_id) {
this.activity = activity;
this.feedItems = feedItems;
this.user_id = user_id;
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
public void refresh(List<FeedItem> newlist) {
feedItems.addAll(newlist);
this.notifyDataSetChanged();
}
public List<FeedItem> getData() {
return feedItems;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.posts_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
final TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.time);
TextView statusMsg = (TextView) convertView
.findViewById(R.id.status);
TextView url = (TextView) convertView.findViewById(R.id.url);
CircleImageView profilePic = (CircleImageView) convertView
.findViewById(R.id.profile_img);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.image);
TextView nbr_likes = (TextView)convertView.findViewById(R.id.nbr_likes);
TextView nbr_comments = (TextView)convertView.findViewById(R.id.nbr_comments);
item = feedItems.get(position);
like =(Button)convertView.findViewById(R.id.like);
comment =(Button)convertView.findViewById(R.id.comment);
like.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
item = feedItems.get(position);
Map<String, String> params = new HashMap<String, String>();
params.put("post_id", item.getId());
params.put("user_id", user_id);
Toast.makeText(activity, item.getId(), Toast.LENGTH_SHORT).show();
Toast.makeText(activity, user_id, Toast.LENGTH_SHORT).show();
// making fresh volley request and getting json
CustomRequest jsonReq = new CustomRequest(Request.Method.POST,
URL,params , new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
});
comment.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
}
});
name.setText(item.getName());
nbr_likes.setText(item.getNbrLikes()+ " Likes");
nbr_comments.setText(item.getNbrComments() + " Comments");
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance());
url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// user profile pic
profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
return convertView;
}
private void parseJsonFeed(JSONObject response) {
int success;
try {
success = response.getInt(TAG_SUCCESS);
if (success == 1) {
notifyDataSetChanged();
} else {
Toast.makeText(activity, "erreur", Toast.LENGTH_SHORT).show();
}
//listAdapter.addAll(feedItems);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
FeedItem Class
package com.example.mahdi.chat;
public class FeedItem {
private String id,name, status, image, profile_img, time, url,nbr_likes,nbr_comments;
public FeedItem() {
}
public FeedItem(String id, String name, String image, String status,
String profilePic, String timeStamp, String url,String nbr_likes,String nbr_comments) {
super();
this.id = id;
this.name = name;
this.image = image;
this.status = status;
this.profile_img = profilePic;
this.time = timeStamp;
this.url = url;
this.nbr_likes = nbr_likes;
this.nbr_comments = nbr_comments;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImge() {
return image;
}
public void setImge(String image) {
this.image = image;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getProfilePic() {
return profile_img;
}
public void setProfilePic(String profilePic) {
this.profile_img = profilePic;
}
public String getTimeStamp() {
return time;
}
public void setTimeStamp(String timeStamp) {
this.time = timeStamp;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getNbrLikes() {
return nbr_likes;
}
public void setNbrLikes(String nbr_likes) {
this.nbr_likes = nbr_likes;
}
public String getNbrComments() {
return nbr_comments;
}
public void setNbrComments(String nbr_comments) {
this.nbr_comments = nbr_comments;
}
}
The problem is the button Like , i would like to change the drawable of the button when its clicked .Thanks.
EDIT :
package com.example.mahdi.chat;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import circleview.CircleImageView;
public class FeedListAdapter extends BaseAdapter {
private static final String TAG = FeedListAdapter.class.getSimpleName();
private Activity activity;
private LayoutInflater inflater;
private List<FeedItem> feedItems;
JSONParser jsonParser = new JSONParser();
private String URL = "http://10.0.3.2/social/like.php";
private String user_id;
private Button like,comment;
private static final String TAG_SUCCESS = "success";
FeedItem item;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public FeedListAdapter(Activity activity, List<FeedItem> feedItems, String user_id) {
this.activity = activity;
this.feedItems = feedItems;
this.user_id = user_id;
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
public void refresh(List<FeedItem> newlist) {
feedItems.addAll(newlist);
this.notifyDataSetChanged();
}
public List<FeedItem> getData() {
return feedItems;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.posts_row, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
final TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.time);
TextView statusMsg = (TextView) convertView
.findViewById(R.id.status);
TextView url = (TextView) convertView.findViewById(R.id.url);
CircleImageView profilePic = (CircleImageView) convertView
.findViewById(R.id.profile_img);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.image);
TextView nbr_likes = (TextView)convertView.findViewById(R.id.nbr_likes);
TextView nbr_comments = (TextView)convertView.findViewById(R.id.nbr_comments);
item = feedItems.get(position);
like =(Button)convertView.findViewById(R.id.like);
comment =(Button)convertView.findViewById(R.id.comment);
like.setTag(position);
like.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
like.setBackgroundColor(Color.BLACK);
item = feedItems.get(position);
Map<String, String> params = new HashMap<String, String>();
params.put("post_id", item.getId());
params.put("user_id", user_id);
Toast.makeText(activity, item.getId(), Toast.LENGTH_SHORT).show();
Toast.makeText(activity, user_id, Toast.LENGTH_SHORT).show();
// making fresh volley request and getting json
CustomRequest jsonReq = new CustomRequest(Request.Method.POST,
URL,params , new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
parseJsonFeed(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
});
comment.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
item = feedItems.get(position);
Intent i = new Intent(activity, Comment.class);
i.putExtra("user_id",item.getId());
i.putExtra("name",item.getName());
i.putExtra("image",item.getImge());
i.putExtra("status",item.getStatus());
i.putExtra("profile_img",item.getProfilePic());
i.putExtra("time",item.getTimeStamp());
i.putExtra("url",item.getUrl());
i.putExtra("nbr_likes",item.getNbrLikes());
i.putExtra("nbr_comments",item.getNbrComments());
activity.startActivity(i);
}
});
name.setText(item.getName());
nbr_likes.setText(item.getNbrLikes()+ " Likes");
nbr_comments.setText(item.getNbrComments() + " Comments");
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
// Chcek for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance());
url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// user profile pic
profilePic.setImageUrl(item.getProfilePic(), imageLoader);
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
return convertView;
}
private void parseJsonFeed(JSONObject response) {
int success;
try {
success = response.getInt(TAG_SUCCESS);
if (success == 1) {
notifyDataSetChanged();
} else {
Toast.makeText(activity, "erreur", Toast.LENGTH_SHORT).show();
}
//listAdapter.addAll(feedItems);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Assuming the button is within the listview.
First define a click listener on the button in the getView function of the adapter:
likebutton.setOnClickListener(likeButtonClickListener);
Then define the onclick listener:
private OnClickListener likeButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
View parentRow = (View) v.getParent();
ListView listView = (ListView) parentRow.getParent();
final int position = listView.getPositionForView(parentRow);
}
};
There is also another way by setting the tag in the getView function:
likebutton.setTag(position);
likebutton.setOnClickListener(likeButtonClickListener);
In the button click listener, we will get the tag and find the position value.
private OnClickListener likeButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
}
};
Edit: to explain the solution of the link i mentioned in comments.
He declares a final boolean variable mHighlightedPositions which provides info if the highlighted position in the listview is selected or not.
If this variable returns true the line in the listview is selected, so what you can do is.
Declare a variable "NUM_OF_ITEMS" as integer and the "mHighlightedPositions" as a boolean in your adapter:
private int NUM_OF_ITEMS;
private final boolean[] mHighlightedPositions = new boolean[NUM_OF_ITEMS];
With this you can define if a item in the listview is selected or not and apply the background/color to your button like he did:
...
if(mHighlightedPositions[position]) {
holder.likebutton.setBackgroundResource(R.drawable.icon_yellow_star_large);
}else {
holder.likebutton.setBackgroundResource(0);
}
...
If you want to follow his example you also need to declare a ViewHolder.
holder = new ViewHolder();
The position of the items will be returned by the position variable:
int position = (Integer)view.getTag();
See below example from the link:
#Override
public void onClick(View view) {
int position = (Integer)view.getTag(); // gets current position
Log.d(TAG, "Button row pos click: " + position);
...
...
if(mHighlightedPositions[position]) { // current position is given
button.setBackgroundResource(0);
mHighlightedPositions[position] = false;
}else {
button.setBackgroundResource(R.drawable.icon_yellow_star_large);
mHighlightedPositions[position] = true;
}
}

Categories

Resources