i'm doing a spinner that retrieves its items from an API, i checked Postman results but there's no error there and somehow i cant even click the spinner or the spinner just doesnt drop down, here's the codes, i checked all other solutions already but not quite like this
Spinner xml:
<Spinner
android:id="#+id/select_plan_spinner"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginLeft="10dp"
android:layout_weight="1"
android:background="#drawable/sos_edit_bg"
android:gravity="center"
android:spinnerMode="dropdown"
android:textColor="#color/white_new"
android:visibility="visible"></Spinner>
Spinner:
plan_spinner = (Spinner) findViewById(R.id.select_plan_spinner);
plan_spinner:
plan_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
plan_id = PLAN_ID.get(position);
Double price = PLAN_PRICE.get(position);
planprice = price;
Log.e("planprice", "planprice>>" + planprice);
if (plan_id != 0) {
int pos = position - 1;
String view_route = feeditem.get(pos).getIMEI();
if (view_route.equals("0")) {
view_route = "No";
} else {
view_route = "yes";
}
desc.setText("Description: " +
feeditem.get(pos).getMessage() + "\n View Route History: " + view_route);
} else {
desc.setText("Please select plan");
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
API:
private void Get_plan_list() {
// TODO Auto-generated method stub
pDialog = new ProgressDialog(Select_plan.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
StringRequest req = new StringRequest(Request.Method.POST, Config.YOUR_API_URL + "planlist",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.dismiss();
// response
Log.e("Responsesearch", response);
try {
JSONObject obj = new JSONObject(response);
int success = obj.getInt("success");
if (success == 1) {
JSONArray array = obj.getJSONArray("planlist");
for (int i = 0; i < array.length(); i++) {
JSONObject jsobj = array.getJSONObject(i);
int p_id = jsobj.getInt("plan_id");
plan_name = jsobj.getString("plan_name");
planprice = jsobj.getDouble("plan_price");
timeperoide = jsobj.getString("view_route");
allow_devices = jsobj.getString("allowed_device");
description = jsobj.getString("description");
UserData detail = new UserData();
detail.setID(p_id);
detail.setName(plan_name);
detail.setEmail(allow_devices);
detail.setMessage(description);
detail.setIMEI(timeperoide);
detail.setMobile(String.valueOf(planprice));
feeditem.add(detail);
PLAN_ID.add(p_id);
PLAN_PRICE.add(planprice);
PLAN_NAME.add(plan_name + "( USD " + planprice + ")");
ArrayAdapter<String> data2 = new ArrayAdapter<String>(Select_plan.this,
R.layout.spinner_item, PLAN_NAME);
plan_spinner.setAdapter(data2);
// for auto set spinner Value
Log.e("plan_id_intent", "plan_id_intent>>" + plan_id_intent);
if (plan_id_intent == null) {
} else {
int position = Integer.parseInt(plan_id_intent);
int index = PLAN_ID.indexOf(position);
plan_spinner.setSelection(index);
}
}
} else if (success == 0) {
String msg = obj.getString("text");
Toast.makeText(getApplicationContext(), "" + msg, Toast.LENGTH_LONG).show();
} else if (success == 2) {
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("Error.Response", e.toString());
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
// error
Log.e("Error.Response", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
// for response time increase
req.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
req.setShouldCache(false);
AppController.getInstance().addToRequestQueue(req);
}
Related
I'm trying to fill an ArrayList with this method GetList()
and I can see that I got 2 records added.
but when I tried to get those records with this method LoadQst() I got 0 records in that ArrayList
this is my code,
public class GameActivity extends AppCompatActivity {
TextView texto1,texto2;
String Option1,Option2;
int CurrentQst,CurrentQstId,int1,int2;
private RequestQueue mQueue;
Question qst = new Question();
public final List<Question> Questions = new ArrayList<Question>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
texto1 = (TextView) findViewById(R.id.red);
texto2 = (TextView) findViewById(R.id.blue);
CurrentQst=0;
mQueue = Volley.newRequestQueue(GameActivity.this);
texto1.setText("");
GetList();
LoadQst();
texto1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GetList();
}
});
}
private void GetList() {
String url = "*********/api/get_all_products.php";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("products");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject employee = jsonArray.getJSONObject(i);
qst = new Question();
String option1 = employee.getString("option1");
qst.id=employee.getInt("id");
qst.option1=employee.getString("option1");
qst.option2=employee.getString("option2");
qst.vote1=employee.getInt("vote1");
qst.vote2=employee.getInt("vote2");
boolean added = Questions.add(qst);
if (added)
{
texto1.append("added\n");
} else
{
texto1.append("not added\n");
}
}
for (int i = 0; i < Questions.size(); i++) {
texto1.append("option " + Questions.get(i).option1 + "\n");
}
texto1.append(" size "+Questions.size()); //here i get size of 2
//Collections.shuffle(Questions);
} catch (JSONException e) {
e.printStackTrace();
texto1.setText(e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
private void LoadQst()
{
try {
Question CurrentQuestion ;
texto2.setText(String.valueOf(Questions.size()));//here i got an error size 0
// CurrentQuestion = (Question)Questions.get(CurrentQst);
//texto1.setText(CurrentQuestion.option1);
//texto2.setText(CurrentQuestion.option1);
// int1=CurrentQuestion.vote1;
//int2=CurrentQuestion.vote2;
//CurrentQstId=CurrentQuestion.id;
}catch (Exception e)
{
texto2.append(e.getMessage());
}
}
}
when I check if I got something in my Questions
I got 2 results
for (int i = 0; i < Questions.size(); i++) {
texto1.append("option " + Questions.get(i).option1 + "\n");
}
but when I call this Questions ArrayList in this method LoadQst() I get 0 results.
should I switch from ArrayList to another method?
you're to suggest any type of solutions
Please, can you take a look?
This is because of JsonObjectRequest onResponse method in Asynchronous. The LoadQst method executes before the onResponse method.
Call your LoadQst method inside onResponse instead of calling in onCreate.
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("products");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject employee = jsonArray.getJSONObject(i);
qst = new Question();
String option1 = employee.getString("option1");
qst.id=employee.getInt("id");
qst.option1=employee.getString("option1");
qst.option2=employee.getString("option2");
qst.vote1=employee.getInt("vote1");
qst.vote2=employee.getInt("vote2");
boolean added = Questions.add(qst);
if (added)
{
texto1.append("added\n");
} else
{
texto1.append("not added\n");
}
}
for (int i = 0; i < Questions.size(); i++) {
texto1.append("option " + Questions.get(i).option1 + "\n");
}
texto1.append(" size "+Questions.size()); //here i get size of 2
//Collections.shuffle(Questions);
LoadQst(); // Call here.
} catch (JSONException e) {
e.printStackTrace();
texto1.setText(e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
I am getting data from the server through web service and showing in recycle view.Every request I am getting 5 item from the server. I debug my code and checked that when I scroll to end of recycleview then new data is getting from the server but it's not adding in the end of recycleview. How can I solve that?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeline);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
listView = (RecyclerView) findViewById(R.id.listview);
listView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
listView.setLayoutManager(layoutManager);
//Adding an scroll change listener to recyclerview
listView.setOnScrollChangeListener(this);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
cd = new ConnectionDetector(this);
isInternetPresent = cd.isConnectingToInternet();
db = new SQLiteHandler(this);
// session manager
session = new SessionManager(this);
/*pref = getApplicationContext().getSharedPreferences("MayahudiPref", 0);
editor = pref.edit();*/
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
id = user.get("id");
token = user.get("token");
getData();
adapter = new TimeLineListAdapter(timeLineItems, this);
listView.setAdapter(adapter);
}
public void getTimeLineData(final String token, final String page) {
timeLineItems = new ArrayList<>();
String tag_string_req = "req_register";
// making fresh volley request and getting json
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.timeline, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
String message = jObj.getString("message");
if(error){
totalPages = jObj.getInt("totalPages");
pageCount = jObj.getInt("page");
int limit = jObj.getInt("limit");
parseJsonFeed(response);
}
}catch (Exception e){
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("page", page);
params.put("limit", "5");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void parseJsonFeed(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray feedArray = jsonObj.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
TimeLineItem item = new TimeLineItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
item.setLname(feedObj.getString("lname"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImge(image);
item.setStatus(feedObj.getString("story_text"));
item.setProfilePic(feedObj.getString("profile_pic"));
item.setTimeStamp(feedObj.getString("time_stamp"));
item.setIsLike(feedObj.getInt("is_like"));
item.setTotalLikes(feedObj.getString("total_likes"));
item.setTotalComment(feedObj.getString("total_comments"));
/*// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setUrl(feedUrl);*/
timeLineItems.add(item);
}
// notify data changes to list adapater
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
//This method will get data from the web API
private void getData() {
//Adding the method to the queue by calling the method getDataFromServer
getTimeLineData(token , String.valueOf(requestCount));
//Incrementing the request counter
requestCount++;
}
//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
#Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//Ifscrolled at last then
if (isLastItemDisplaying(listView)) {
//Calling the method getdata again
getData();
}
}
I think you create a new items list each time you call getTimeLineData():
timeLineItems = new ArrayList<>();
First check if you already have a list:
if (timeLineItems == null) {
timeLineItems = new ArrayList<>();
}
RecylerView article_list;
article_list.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
visibleitemcount = linearLayoutManager.getChildCount();
total_itemcount = linearLayoutManager.getItemCount();
pastVisiblecount = linearLayoutManager.findFirstVisibleItemPosition();
Log.d(TAG, "Total : " + total_itemcount + "Visible : " + visibleitemcount + "Past : " + pastVisiblecount);
if (loading) {
if (visibleitemcount + pastVisiblecount >= total_itemcount) {
loading = false;
getHealthyLivingfromUrl(5, 0);
}
}
}
});
private void getHealthyLivingfromUrl(int limit, int offset) {
//get the data code
article_list.setAdapter(articleAdapter);
if (total_itemcount!=0 && total_itemcount > visibleitemcount) {
linearLayoutManager.setSmoothScrollbarEnabled(true);
linearLayoutManager.scrollToPosition(total_itemcount-visibleitemcount);
}
loading = true;
}
Why are you using POST method to obtain data ? Everytime you obtaining data you are creating new array, onCreate you assign to adapter an array. Then you create one, but no assign. I think you should create in adapter class, addItems(List items) method and every time you are getting data you use this method (inside this method you can notifi data has changed). That's all.
Why does Log.d("Test", "" + ListOfAttractions3.size() + ""); Return 0 when Log.d("Test2", "" + ListOfAttractions3.size() + ""); returns 2 even thoughDatabseRequest(); is called first? Some how Log 2 is also printed last but I can't see why?
Code:
public class Testlist extends Activity {
List<Attractions> ListOfAttractions3 = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testlist);
DatabseRequest();
Log.d("Test", "" + ListOfAttractions3.size() + "");
}
/*private void reFreshDisplay(){
ListView listView2 = (ListView) findViewById(R.id.listView2);
ArrayAdapter<Attractions> adapter = new ArrayAdapter<Attractions>(this, android.R.layout.simple_list_item_1, ListOfAttractions3);
listView2.setAdapter(adapter);
adapter.notifyDataSetChanged();
}*/
private void DatabseRequest(){
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
int i = 0;
while(i < jsonArray.length()) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
boolean success;
if (jsonObject.getBoolean("success")) success = true;
else success = false;
if (success) {
String attractionname = jsonObject.getString("attractionname");
double lng = jsonObject.getDouble("longitude");
double lat = jsonObject.getDouble("latitude");
int Rating = jsonObject.getInt("rating");
Attractions attraction = new Attractions(attractionname, lng, lat, Rating);
ListOfAttractions3.add(attraction);
Log.d("Test2", "" + ListOfAttractions3.size() + "");
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Testlist.this);
builder.setMessage("Connection to server Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
i++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
AttractionRequest attractionRequest = new AttractionRequest(responseListener);
RequestQueue queue2 = Volley.newRequestQueue(Testlist.this);
queue2.add(attractionRequest);
}
}
I am working on a project and below my code basically takes an array of objects and sets the Id to each object, However, when I click on my objects I would like to get that Id. I tried a local variable and I could only get the Id of the last object, how do I do this? I would like to get the value of String Answerid = currentQuestions.getString("id"); into my OnDown clicklistener.
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_ANSWER, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listblogs = parseJSONResponseQuestion(response);
mAdapterQuestion.setBloglist(listblogs);
System.out.println(response);
System.out.println("it worked!!!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
});
mRequestQueue.add(request);
}
String globalVar = " ";
private ArrayList<Blogs> parseJSONResponseQuestion(JSONArray response) {
if (!response.equals("")) {
ArrayList<Blogs> blogsArrayList = new ArrayList<>();
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String text = currentQuestions.getString("text");
String questionId = currentQuestions.getString("questionId");
String votes = currentQuestions.getString("votes");
String Answerid = currentQuestions.getString("id");
System.out.println(response.length() + "length");
data.append(text + Answerid + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setMtext(text);
blogs.setVotes(votes);
blogs.setId(Answerid);
System.out.print(Answerid);
listblogs.add(blogs);
}
System.out.println(data.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
return listblogs;
}
public void OnDown(View view) {
System.out.println("VOTED Down");
final RequestQueue mrequestQueue = VolleySingleton.getInstance().getRequestQueue();
final String PUT_VOTE_UP = "someURL";
StringRequest PostVoteUp = new StringRequest(Request.Method.PUT, PUT_VOTE_UP, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response + "reponse");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println("************Answer" + error + "error");
}
});
mrequestQueue.add(PostVoteUp);
System.out.println("VOTED DOWN");
}
}
Your click listener OnDown(View view) gets a view that was clicked. That's the only way you can identify what was clicked.
You should use View.getTag() to get the id:
Object obj = view.getTag();
The question is where can you add this code to set it:
View view = ...; // new View()?
view.setTag(object);
I am making check-boxes programmatically. and I want to get value of checked check-boxes when click on button... how can i do this....
I am getting value of checkboxes from database.
Here is my working code..
public class Loyaltyprogram extends Activity {
SessionManager session;
EditText mpv, discount;
Button save;
String finalresult, getFlag, statusEmp, accessName, emp_id, bus_id,
preferences, bus_type_id, emp_access_name, responseString, success,
name, id, pref, per_amout, percentage, datediff, dateNo, minpvalue , discountonit;
Toast tag;
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
ProgressDialog pDialog;
int a;
String[] idsplit, namesplit, prefsplit;
List<String> testArrayList;
LinearLayout llmain;
LinearLayout[] lLayout;
Integer count1 = 0;
Context mContext;
TextView tvo;
CheckBox cb;
StringBuffer result = new StringBuffer();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.loyaltyprogram);
tvo = (TextView) findViewById(R.id.tvother);
mpv = (EditText) findViewById(R.id.et_minpurchase);
discount = (EditText) findViewById(R.id.et_discount);
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
new Homedatanew().execute();
llmain = (LinearLayout) findViewById(R.id.linearLayoutMain);
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"Check your internet connection", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
save = (Button) findViewById(R.id.button);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
minpvalue = mpv.getText().toString();
discountonit = discount.getText().toString();
for(int t = 0; t<idsplit.length; t++)
{
if(cb.isChecked())
{
System.out.println(idsplit[t]);
}
}
}
});
}
class Homedatanew extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Loyaltyprogram.this);
pDialog.setMessage("loading data..");
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://10.0.2.2/amardeep/android_api/checkbox.php");
try {
session = new SessionManager(getApplicationContext());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// id
bus_id = user.get(SessionManager.KEY_B_ID);
bus_type_id = user.get(SessionManager.KEY_B_TYPE_ID);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("bus_type_id",
"BT101"));
nameValuePairs.add(new BasicNameValuePair("bus_id", "B101"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
response.getStatusLine().getStatusCode();
HttpEntity getResponseEntity = response.getEntity();
responseString = EntityUtils.toString(getResponseEntity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return responseString;
}
#SuppressLint("NewApi")
protected void onPostExecute(String resultStr) {
try {
JSONObject json = new JSONObject(responseString);
JSONArray jArray = json.getJSONArray("customer");
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
success = json_data.getString("success");
id = json_data.getString("id");
name = json_data.getString("name");
pref = json_data.getString("pref");
per_amout = json_data.getString("per_amount");
percentage = json_data.getString("percentage");
datediff = json_data.getString("dateDiff");
dateNo = json_data.getString("dateNo");
if (percentage.equals("null")) {
percentage = "";
}
if (per_amout.equals("null")) {
per_amout = "";
}
if((datediff.equals("No"))&&(dateNo.equals("No")))
{
count1 = 1;
}
else if((datediff.equals("YES"))&&(dateNo.equals("No")))
{
count1 = 2;
}
else
{
count1 = 0;
}
idsplit = id.split(",");
a = idsplit.length;
namesplit = name.split(",");
prefsplit = pref.split(",");
testArrayList = new ArrayList<String>(
Arrays.asList(prefsplit));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (success.equals("1")) {
mpv.setText(per_amout);
discount.setText(percentage);
if ((count1.equals(1)) || (count1.equals(2))) {
mpv.setEnabled(true);
discount.setEnabled(true);
} else {
mpv.setEnabled(false);
discount.setEnabled(false);
save.setEnabled(false);
}
int b = (a / 5);
int c = (a % 5);
if (c != 0) {
b = b + 1;
}
lLayout = new LinearLayout[b];
for (int j = 0; j < b; j++) {
int x = 0;
x = x + (j * 5);
lLayout[j] = new LinearLayout(Loyaltyprogram.this);
lLayout[j].setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
lLayout[j].setOrientation(LinearLayout.VERTICAL);
llmain.addView(lLayout[j]);
for (int i = x; i < x + 5; i++) {
if (x > a) {
break;
} else {
if (testArrayList.contains(idsplit[i])) {
cb = new CheckBox(Loyaltyprogram.this);
cb.setText(namesplit[i] + (i + 1));
cb.setId(i + 1);
cb.setChecked(true);
cb.setTextColor(Color.BLACK);
cb.setTextSize(12f);
cb.setButtonDrawable(R.drawable.checkbox);
cb.setPadding(35, 5, 25, 5);
if (count1.equals(1)) {
cb.setEnabled(true);
} else {
cb.setEnabled(false);
}
lLayout[j].addView(cb);
} else {
cb = new CheckBox(Loyaltyprogram.this);
cb.setText(namesplit[i] + (i + 1));
cb.setId(i + 1);
cb.setTextColor(Color.BLACK);
cb.setTextSize(12f);
cb.setButtonDrawable(R.drawable.checkbox);
cb.setPadding(35, 5, 25, 5);
if (count1.equals(1)) {
cb.setEnabled(true);
} else {
cb.setEnabled(false);
}
lLayout[j].addView(cb);
}
}
}
}
} else {
Toast.makeText(getApplicationContext(), "data empty",
Toast.LENGTH_LONG).show();
mpv.setEnabled(true);
discount.setEnabled(true);
}
pDialog.dismiss();
}
}
}
Just do this inside the loop and if , else condition
cb.setTag(i+99); // set the tag values so that you can refer to them later.
cb.setOnCheckedChangeListener(handleCheck(cb)); // here pass the checkbox object.
Then this is handleCheck method
private OnCheckedChangeListener handleCheck (final CheckBox chk)
{
return new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(!isChecked){
Toast.makeText(getApplicationContext(), "You unchecked " + chk.getTag(),
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "You checked " + chk.getTag(),
Toast.LENGTH_LONG).show();
}
}
};
}
Hope this gives you some idea. Happy coding :)