How to get value from listview checkbox? - android

I am having a little trouble with listview, I want to get values of listview whose checkbox are selected when button is clicked. till now i have created a listview with checkboxes and fetched all the values from mysql but i am not able to get values of listview which are checked.
This is my class
public class ListViewMultipleSelectionActivity extends Activity{
Button button;
String myJSON;
private static final String TAG_NAME = "cat_name";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
personList = new ArrayList<HashMap<String,String>>();
list1 = (ListView) findViewById(R.id.list);
button = (Button)findViewById(R.id.testbutton);
getlat();
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public void getlat(){
class GetDataJSON extends AsyncTask<String, Void, String> {
public void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
InputStream inputStream = null;
String result = null;
try {
URL url = new URL("http://xxxxxxxxxxxx/category.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder("");
String line="";
while ((line = in.readLine()) != null)
{
sb.append(line).append("\n");
}
result = sb.toString();
}
assert inputStream != null;
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line).append("\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("tagconvertstr", "["+result+"]");
System.out.println(e);
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void showList(){
try {
peoples = new JSONArray(myJSON);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name = c.getString(TAG_NAME);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
ListViewMultipleSelectionActivity.this, personList, R.layout.result,
new String[]{TAG_NAME},
new int[]{R.id.name}
);
list1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list1.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/testbutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Submit" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/testbutton"
android:layout_alignParentTop="true"/>
</RelativeLayout>
result.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/cbBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" >
</CheckBox>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:orientation="vertical"
android:layout_weight="1" >
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textStyle="bold"/>
</LinearLayout>
</LinearLayout>
i have implemented this on testbutton(Button) click please check
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checked = list1.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
if (checked.valueAt(i))
selectedItems.add((String) adapter.getItem(position));
}
String[] valuess = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
valuess[i] = selectedItems.get(i);
}
Toast.makeText(ListViewMultipleSelectionActivity.this, String.valueOf(valuess), Toast.LENGTH_SHORT).show();
}
});
this is i am getting after click
E/-->>>>: [Ljava.lang.String;#ca01299

What you can do is creating a custom class to store these values along with a custom adapter that supports it. So whenever you click the button you can call the given function to retrieve the statuses of those items. Example architecture given below:
PS: Since I don't know what you want to do with checked values, I left you there with comments which you can change with your need.
MainActivity.java
package com.rencsaridogan.stackoverflow;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<ExampleClass> objects;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
objects = new ArrayList<>();
for (int i = 0; i < 10; i++){
objects.add(new ExampleClass("Example Name " + i));
}
final ListView listView = (ListView) findViewById(R.id.listView);
final Button testButton = (Button) findViewById(R.id.testButton);
final ExampleAdapter exampleAdapter = new ExampleAdapter(this, R.layout.list_cell, objects);
listView.setAdapter(exampleAdapter);
exampleAdapter.notifyDataSetChanged();
testButton.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
getCheckedItems();
}
});
}
private void getCheckedItems(){
for (int i = 0; i < 10; i++) {
if (objects.get(i).isChecked()){
Log.i("MainActivity",i + " is checked");
/**
* Value is checked, do what you need to do here
*/
} else {
Log.i("MainActivity",i + " is NOT checked");
/**
* Value is NOT checked
*/
}
}
}
}
ExampleAdapter.java
package com.rencsaridogan.stackoverflow;
import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by rencsaridogan on 16/02/2017.
*/
public class ExampleAdapter extends ArrayAdapter<ExampleClass> {
ArrayList<ExampleClass> objects;
Listener listener;
Context context;
public ExampleAdapter(Context context, int resource, ArrayList<ExampleClass> objects) {
super(context, resource);
this.context = context;
this.objects = objects;
}
#Override public int getViewTypeCount() {
return super.getViewTypeCount();
}
#Override public int getCount() {
return objects.size();
}
#SuppressLint("InflateParams") #Override public View getView(int position, View convertView, #NonNull ViewGroup parent) {
if (convertView == null){
Log.i("ExampleAdapter","ConvertView inflated");
convertView = LayoutInflater.from(context).inflate(R.layout.list_cell, null, false);
}
Log.i("ExampleAdapter","Setting of values");
final ExampleClass data = objects.get(position);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.textView = (TextView) convertView.findViewById(R.id.textView);
viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
viewHolder.textView.setText(data.getName());
viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
data.setChecked(isChecked);
}
});
return convertView;
}
public void setListener(Listener listener) {
this.listener = listener;
}
private class ViewHolder {
TextView textView;
CheckBox checkBox;
}
public ArrayList<ExampleClass> getObjects() {
return objects;
}
public void setObjects(ArrayList<ExampleClass> objects) {
this.objects = objects;
notifyDataSetChanged();
}
#Override public long getItemId(int position) {
return super.getItemId(position);
}
public interface Listener {
void onCheckedChanged(int position);
}
}
ExampleClass.java
package com.rencsaridogan.stackoverflow;
/**
* Created by rencsaridogan on 16/02/2017.
*/
public class ExampleClass {
String name;
boolean isChecked;
public ExampleClass(String name) {
this.name = name;
}
public ExampleClass(String name, boolean isChecked) {
this.name = name;
this.isChecked = isChecked;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean checked) {
isChecked = checked;
}
}

Set checkbox object as tag to your row view that might be your 'convertView' in getView() method of your adapter.
Write on click listener on your row view.
3.Inside that click-listener to row view getTag from view that's parameter in onClick method and cast it to checkbox and then setChecked to true for that checkbox object.
code might look like this,
convertView.setTag(yourCheckBoxObject);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v.getTag();
cb.setChecked(true);
}
});
Please refer this sight for more information Getting an issue while checking the dynamically generated checkbox through list view

In your Adapter there was one #override method called getView() in that method you will get the current item which you will clicked
holder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox checkBox=(CheckBox) view;
String tagName="";
if(checkBox.isChecked()){
tagName=checkBox.getTag().toString();
deleteServices.add(tagName);
checkboxArrayList.add(checkBox);
}else {
checkboxArrayList.remove(checkBox);
tagName=checkBox.getTag().toString();
if(deleteServices.size()>0&&deleteServices.contains(tagName)){
deleteServices.remove(tagName);
}
});

Related

Android - How to handle ratingBar in custom adapter?

I have a TextView and RatingBar in ListView, and i want to save value of RatingBar on each list in ListView, it is possible with custom adapter??
the code I use to do likes:
PertanyaanAdapter.java
package flix.yudi.pertanyaan3;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RatingBar;
import android.widget.TextView;
import java.util.List;
class PertanyaanAdapter extends ArrayAdapter<Pertanyaan> {
private AppCompatActivity activity;
private List<Pertanyaan> movieList;
PertanyaanAdapter(AppCompatActivity context, int resource, List<Pertanyaan> objects) {
super(context, resource, objects);
this.activity = context;
this.movieList = objects;
}
#Override
public Pertanyaan getItem(int position) {
return movieList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_listview, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
//holder.ratingBar.getTag(position);
}
holder.ratingBar.setOnRatingBarChangeListener(onRatingChangedListener(position));
holder.ratingBar.setTag(position);
holder.ratingBar.setRating(getItem(position).getRatingStar());
holder.movieName.setText(getItem(position).getAsk());
return convertView;
}
private RatingBar.OnRatingBarChangeListener onRatingChangedListener(final int position) {
return new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
Pertanyaan item = getItem(position);
assert item != null;
item.setRatingStar(v);
Log.i("Adapter", "star: " + v);
}
};
}
private static class ViewHolder {
private RatingBar ratingBar;
private TextView movieName;
ViewHolder(View view) {
ratingBar = (RatingBar) view.findViewById(R.id.rate_img);
movieName = (TextView) view.findViewById(R.id.text);
}
}
}
Pertanyaan.java
package flix.yudi.pertanyaan3;
public class Pertanyaan {
private float ratingStar;
private String ask;
Pertanyaan(int ratingStar, String ask) {
this.ratingStar = ratingStar;
this.ask = ask;
}
float getRatingStar() {
return 0;
}
void setRatingStar(float ratingStar) {
this.ratingStar = ratingStar;
}
public String getAsk() {
return ask;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<Pertanyaan> listPertanyaan;
ArrayAdapter<Pertanyaan> adapter2;
ProgressDialog pDialog;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.list_view);
listPertanyaan = new ArrayList<>();
getpertanyaan get= new getpertanyaan();
get.execute();
adapter2 = new PertanyaanAdapter(this, R.layout.item_listview, listPertanyaan);
listView.setAdapter(adapter2);
}
protected void onStart() {
super.onStart();
}
private class getpertanyaan extends AsyncTask<Void, Void, Integer> {
ArrayList<Pertanyaan> list;
protected void onPreExecute() {
pDialog=new ProgressDialog(MainActivity.this);
pDialog.setTitle("Nama Dosen");
pDialog.setMessage("Menampilkan nama dosen... Mohon tunggu...!");
pDialog.setCancelable(false);
pDialog.show();
super.onPreExecute();
list = new ArrayList<>();
}
#Override
protected Integer doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://flix.16mb.com/send_data.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
//convert response to string
try {
BufferedReader reader = null;
if (is != null) {
reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
}
String line;
if (reader != null) {
while ((line = reader.readLine()) != null) {
result += line;
}
}
if (is != null) {
is.close();
}
//result=sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
list.add(new Pertanyaan(0,jsonObject.getString("ask")));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Integer result) {
if (pDialog.isShowing())
pDialog.dismiss();
listPertanyaan.addAll(list);
adapter2.notifyDataSetChanged();
}
}
}
but when I run the app, the RatingBar is untouchable, just each list of ListView is touch however I want to tap the RatingBar.
did I doing something wrong? help me please.
EDIT :
item_listview.xml
<RatingBar
android:id="#+id/rate_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text"
android:numStars="5"
android:stepSize="1"
style="#style/Widget.AppCompat.RatingBar.Indicator" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold" />
the RatingBar is read-only because of the style you are using.
style="#style/Widget.AppCompat.RatingBar.Indicator"
sets the attribute android:isIndicator to true which makes behave it, in the way are experiencing. You can either get rid of the line, or try to force android:isIndicator to false in your item_listview.xml

My list view is not showing anything i have use array adapter and no error in logcat

I am not getting anything in the listview when i am running this code.
I am trying to get value from server in text view,i am getting value from server in payload object.but still my list view is not showing anything and there is no error in logcat.
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.zalonstyles.app.zalon.Model.Services;
import com.zalonstyles.app.zalon.Model.ViewHolder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
This is the class where i am getting data from server
public class popup_massage extends AppCompatActivity {
public static final String URL = "http://52.41.72.46:8080/service/get_category";
public final String serviceid = "6";
private ListView mainListView;
private Button check;
private List<Services> massagelist = new ArrayList<>();
private Services massageservice[];
private Context context;
public ArrayAdapter<Services> listAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup_massage);
SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String value=(mSharedPreference.getString("AppConstant.AUTH_TOKEN", "DEFAULT"));
Log.e("accesslog",value);
mainListView = (ListView) findViewById(R.id.listView4);
check = (Button) findViewById(R.id.button4);
final JSONObject params = new JSONObject();
try {
params.put("service_id",serviceid);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("access_token", value);
} catch (JSONException e) {
e.printStackTrace();
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>(){
#Override
public void onResponse(String response) {
Log.v("updateUPVolleyRes1",response);
try {
JSONObject jobject = new JSONObject(response);
JSONArray payload = jobject.getJSONArray("payload");
Log.e("payloaddata", String.valueOf(payload));
for (int i = 0; i < payload.length(); i++) {
try{
JSONObject obj = payload.getJSONObject(i);
Services service = new Services();
service.setName(obj.getString("name"));
service.setcategotry_id(obj.getString("id"));
massagelist.add(service);
}finally {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("updateUPVolleyErr", error.toString());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params1 = new HashMap<String, String>();
params1.put("payload", params.toString());
Log.v("updateUPVolleyParams", params1.toString());
return params1;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
mainListView
.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View item,
int position, long id)
{
Services massageservice = listAdapter.getItem(position);
Log.e("CHECKADAPTOR", String.valueOf(massageservice));
massageservice.toggleChecked();
ViewHolder viewHolder =(ViewHolder) item
.getTag();
viewHolder.getCheckBox().setChecked(massageservice.isChecked());
}
});
//Services[] massageService = (Services[]) getLastNonConfigurationInstance();ArrayList<Services> massagelist = new ArrayList<Services>();
//massagelist.addAll(Arrays.asList(massageService));
// Set our custom array adapter as the ListView's adapter.
listAdapter = new massageArrayAdapter(this,massagelist);
mainListView.setAdapter(listAdapter);
check.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
for (int i = 0; i < listAdapter.getCount(); i++)
{
Services massage = listAdapter.getItem(i);
if (massage.isChecked())
{
Toast.makeText(getApplicationContext(),
massage.getName() + " is Checked!!",
Toast.LENGTH_SHORT).show();
Log.v("My Custom Tag", massage.getName());
}
}
}
});
}
//arrayadapter class//
private static class massageArrayAdapter extends ArrayAdapter<Services>
{
private LayoutInflater inflater;
public massageArrayAdapter(Context context, List<Services> massagelist)
{
super(context, R.layout.customlist_massage, R.id.massagetextview, massagelist);
// Cache the LayoutInflate to avoid asking for a new one each time.
inflater = LayoutInflater.from((Context) context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
// services to display
Services massage = (Services) this.getItem(position);
// The child views in each row.
CheckBox checkBox;
TextView textView;
// Create a new row view
if (convertView == null)
{
convertView = inflater.inflate(R.layout.customlist_massage,null );
// Find the child views.
textView = (TextView) convertView
.findViewById(R.id.massagetextview);
checkBox = (CheckBox) `enter code here`convertView.findViewById(R.id.checkBox4);
// Optimization: Tag the row with it's child views, so we don't
// have to
// call findViewById() later when we reuse the row.
convertView.setTag(new ViewHolder(textView, checkBox));
// If CheckBox is toggled, update the planet it is tagged with.
checkBox.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
CheckBox cb = (CheckBox) v;
Services massage = (Services) cb.getTag();
massage.setChecked(cb.isChecked());
}
});
}
// Reuse existing row view
else
{
// Because we use a ViewHolder, we avoid having to call
// findViewById().
ViewHolder viewHolder = (ViewHolder) convertView
.getTag();
checkBox = viewHolder.getCheckBox();
textView = viewHolder.getTextView();
}
// Tag the CheckBox with the service it is displaying,
// access the planet in onClick() when the CheckBox is toggled.
checkBox.setTag(massage);
// Display planet data
checkBox.setChecked(massage.isChecked());
textView.setText(massage.getName());
return convertView;
}
}
}
My Service class used to store services
public class Services
{
private String name = "";
private boolean checked = false;
private String categotry_id="";
public Services()
{
}
public Services(String name)
{
this.name = name;
}
public Services(String name, boolean checked,String categotry_id)
{
this.name = name;
this.categotry_id = categotry_id;
this.checked = checked;
}
public Services(String name,String categotry_id)
{
this.name = name;
this.categotry_id = categotry_id;
}
public String getCategory_id(String id)
{
return categotry_id;
}
public void setcategotry_id(String categotry_id)
{
this.name = categotry_id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public boolean isChecked()
{
return checked;
}
public void setChecked(boolean checked)
{
this.checked = checked;
}
public String toString()
{
return name;
}
public void toggleChecked()
{
checked = !checked;
}
}
View holder class for storing views
public class ViewHolder
{
private CheckBox checkBox;
private TextView textView;
public ViewHolder()
{
}
public ViewHolder(TextView textView, CheckBox checkBox)
{
this.checkBox = checkBox;
this.textView = textView;
}
public CheckBox getCheckBox()
{
return checkBox;
}
public void setCheckBox(CheckBox checkBox)
{
this.checkBox = checkBox;
}
public TextView getTextView()
{
return textView;
}
public void setTextView(TextView textView)
{
this.textView = textView;
}
}
my xml class where list view is there
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#3F51B5">
<ListView
android:id="#+id/listView4"
android:layout_width="match_parent"
android:layout_height="0px"
android:background="#fff"
android:layout_weight="1" >
</ListView>
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="313dp"
android:text="Continue" />
</LinearLayout>
Please help me through this I need to submit this by tomorrow.
Use this
convertView = inflater.inflate(R.layout.customlist_massage,null ,false );
Instead this
convertView = inflater.inflate(R.layout.customlist_massage,null );
Why you are extending the adapter class ArrayAdapter.
If You want to show something on listview you have to extend it to BaseAdapter OR Recyclerview Adapter.
You dont have any getCount() method in ArrayAdapter see this example::
public class Adapter extends BaseAdapter {
LayoutInflater li;
ArrayList<String> title, details;
Context con;
DataBaseHelper db;
TextView txttitle, txtdetails, txtDate;
Intent in;
public static int i = 1;
View view;
public Adapter (Context cont, ArrayList<String> news_id, ArrayList<String> news) {
this.title = news_id;
this.details = news;
this.con = cont;
li = (LayoutInflater) con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
System.out.println("title.size() " + title.size());
return title.size();
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
if (arg1 == null) {
arg1 = li.inflate(R.layout.adapter_daycare, null);
txttitle = (TextView) arg1.findViewById(R.id.title);
txtdetails = (TextView) arg1.findViewById(R.id.details);
txtDate = (TextView) arg1.findViewById(R.id.txtdate);
view = (View) arg1.findViewById(R.id.view);
}
String date = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
System.out.println(" formattedDate " + date);
txttitle.setText(title.get(arg0).toString());
txtdetails.setText(details.get(arg0).toString());
txtDate.setText(date);
return arg1;
}
}

How to send selected messages using checkbox to a particular no?

first i'm fetching all messages to my app to be store in listview then I'm selecting messages from listview using checkboxes and wish to send these selected sms to a single number that is predefined and wish to use the selected sms as body of message to be send to single no. but the problem is that the message sent contains complete listview messages not the selected one. So please someone correct me where i'm wrong in code as i wish to send only selected messages not the complete listview items(messages)
public class MainActivity extends Activity implements OnItemClickListener, OnClickListener{
Button send;
ListView listViewSMS;
Cursor cursor;
SMSListAdapter smsListAdapter;
Context context;
SharedPreferences prefs=null;
ArrayAdapter<SMSListModel> adapter;
List<SMSListModel> list = new ArrayList<SMSListModel>();
TextView textViewSMSSender, textViewSMSBody;
int i;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
listViewSMS=(ListView)findViewById(R.id.lvSMS);
send = (Button)findViewById(R.id.btnproperty);
send.setOnClickListener(this);
textViewSMSSender=(TextView)findViewById(R.id.tvSMSSend);
textViewSMSBody=(TextView)findViewById(R.id.tvSMSBody);
cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
smsListAdapter = new SMSListAdapter(this,getModel());
listViewSMS.setAdapter(smsListAdapter);
listViewSMS.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
TextView label = (TextView) v.getTag(R.id.tvSMSSend);
CheckBox checkbox = (CheckBox) v.getTag(R.id.cbSelect);
Toast.makeText(v.getContext(), label.getText().toString()+" "+isCheckedOrNot(checkbox), Toast.LENGTH_LONG).show();
}
private String isCheckedOrNot(CheckBox checkbox) {
if(checkbox.isChecked())
return "is checked";
else
return "is not checked";
}
private List<SMSListModel> getModel() {
if(cursor.getCount()>0){
for(i=0;i<cursor.getCount();i++){
if(cursor.moveToPosition(i)){
list.add(new SMSListModel(cursor.getString(cursor.getColumnIndex("address")),cursor.getString(cursor.getColumnIndex("body"))));
}
}
}
return list;
}
#Override
public void onClick(View v) {
if( v == send){
mDialog();
}
public void mDialog(){
// Show The Dialog with Selected SMS
AlertDialog dialog = new AlertDialog.Builder(context).create();
dialog.setTitle("Message App");
dialog.setIcon(android.R.drawable.ic_dialog_info);
dialog.setMessage("Count : ");
dialog.setButton(DialogInterface.BUTTON_POSITIVE, "ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
String phoneNo = "111";
if(list.size()>0){
for(i=0;i<list.size();i++){
if(list.get(i).isSelected()){
try{
SmsManager smsManager = SmsManager.getDefault();
StringBuilder builder = new StringBuilder();
for(SMSListModel p: list){
builder.append(p.toString());
builder.append('\n');
}
String sms = builder.toString();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",Toast.LENGTH_LONG).show();
}
catch (Exception e){
Toast.makeText(getApplicationContext(),"SMS faild, please try again later!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
dialog.dismiss();
}
}
}
}
});
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "SMS not Sent",Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
dialog.show();
}
public class SMSListAdapter extends ArrayAdapter<SMSListModel> {
private final List<SMSListModel> list;
private final Activity mContext;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
public SMSListAdapter(Activity context,List<SMSListModel> list)
{
super(context, R.layout.listview_each_item, list);
mContext = context;
this.list = list;
}
static class ViewHolder {
protected TextView textAddress;
protected TextView textBody;
protected CheckBox checkbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = mContext.getLayoutInflater();
convertView = inflator.inflate(R.layout.listview_each_item, null);
viewHolder = new ViewHolder();
viewHolder.textAddress = (TextView) convertView.findViewById(R.id.tvSMSSend);
viewHolder.textBody = (TextView) convertView.findViewById(R.id.tvSMSBody);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.cbSelect);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.tvSMSSend, viewHolder.textAddress);
convertView.setTag(R.id.tvSMSBody, viewHolder.textBody);
convertView.setTag(R.id.cbSelect, viewHolder.checkbox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkbox.setTag(position); // This line is important.
viewHolder.textAddress.setText(list.get(position).getAddress());
viewHolder.textBody.setText(list.get(position).getBody());
viewHolder.checkbox.setChecked(list.get(position).isSelected());
return convertView;
}
public class SMSListModel {
private String address;
String body;
private boolean selected;
public SMSListModel(String address, String body) {
this.address = address;
this.body = body;
}
public String getAddress() {
return address;
}
public String getBody() {
return body;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public String toString(){
return body;
}}
May I know why you want to select multiple rows. I mean what exact action you want to perform by selecting multiple rows?
Here is the updated code for you. Please let me know in case you didn't get any code:
---------------
package com.example.multiselectlist;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnItemClickListener, OnClickListener{
Button btnDelete;
ListView listViewSMS;
Cursor cursor;
SMSListAdapter smsListAdapter;
Context context;
ArrayAdapter<SMSListModel> adapter;
List<SMSListModel> list = new ArrayList<SMSListModel>();
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
listViewSMS=(ListView)findViewById(R.id.lvSMS);
btnDelete = (Button)findViewById(R.id.buttonDelete);
cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
smsListAdapter = new SMSListAdapter(this,getModel());
listViewSMS.setAdapter(smsListAdapter);
listViewSMS.setOnItemClickListener(this);
btnDelete.setOnClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
TextView label = (TextView) v.getTag(R.id.tvSMSSend);
CheckBox checkbox = (CheckBox) v.getTag(R.id.cbSelect);
Toast.makeText(v.getContext(), label.getText().toString()+" "+isCheckedOrNot(checkbox), Toast.LENGTH_LONG).show();
}
private String isCheckedOrNot(CheckBox checkbox) {
if(checkbox.isChecked())
return "is checked";
else
return "is not checked";
}
private List<SMSListModel> getModel() {
if(cursor.getCount()>0){
for(int i=0;i<cursor.getCount();i++){
if(cursor.moveToPosition(i)){
list.add(new SMSListModel(cursor.getString(cursor.getColumnIndex("address")),cursor.getString(cursor.getColumnIndex("body"))));
}
}
}
return list;
}
#Override
public void onClick(View v) {
int id = v.getId();
switch(id){
case R.id.buttonDelete:
if(list.size()>0){
for(int i=0;i<list.size();i++){
if(list.get(i).isSelected()){
list.remove(i);
}
}
smsListAdapter = new SMSListAdapter(this,list);
smsListAdapter.notifyDataSetChanged();
listViewSMS.setAdapter(smsListAdapter);
}
break;
case R.id.buttonSend:
String contactNum = "+123456789";
String messageList = "";
if(list.size()>0){
for(int i=0;i<list.size();i++){
if(list.get(i).isSelected()){
if(messageList.equals(""))
messageList = list.get(i).getBody();
else
messageList = messageList+";"+list.get(i).getBody();
}
}
Log.v("messageList",""+messageList);
Uri sendSmsTo = Uri.parse("smsto:" + contactNum);
Log.d("sendSmsTo",""+sendSmsTo);
Intent intent = new Intent(android.content.Intent.ACTION_SENDTO, sendSmsTo);
intent.putExtra("sms_body", messageList);
startActivityForResult(intent, 100);
}
}
}
}
SMSListModel class:
package com.example.multiselectlist;
public class SMSListModel {
private String address;
String body;
private boolean selected;
public SMSListModel(String address, String body) {
this.address = address;
this.body = body;
}
public String getAddress() {
return address;
}
public String getBody() {
return body;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
SMSListAdapter class:
package com.example.multiselectlist;
import java.util.List;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
public class SMSListAdapter extends ArrayAdapter<SMSListModel> {
private final List<SMSListModel> list;
private final Activity mContext;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
public SMSListAdapter(Activity context,List<SMSListModel> list)
{
super(context, R.layout.listview_each_item, list);
mContext = context;
this.list = list;
}
static class ViewHolder {
protected TextView textAddress;
protected TextView textBody;
protected CheckBox checkbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = mContext.getLayoutInflater();
convertView = inflator.inflate(R.layout.listview_each_item, null);
viewHolder = new ViewHolder();
viewHolder.textAddress = (TextView) convertView.findViewById(R.id.tvSMSSend);
viewHolder.textBody = (TextView) convertView.findViewById(R.id.tvSMSBody);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.cbSelect);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.tvSMSSend, viewHolder.textAddress);
convertView.setTag(R.id.tvSMSBody, viewHolder.textBody);
convertView.setTag(R.id.cbSelect, viewHolder.checkbox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkbox.setTag(position); // This line is important.
viewHolder.textAddress.setText(list.get(position).getAddress());
viewHolder.textBody.setText(list.get(position).getBody());
viewHolder.checkbox.setChecked(list.get(position).isSelected());
return convertView;
}
}
xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/buttonDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Delete" />
<ListView
android:id="#+id/lvSMS"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/buttonDelete" >
</ListView>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<CheckBox
android:id="#+id/cbSelect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/tvSMSSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/cbSelect"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/cbSelect"
android:text="9998698700" />
<TextView
android:id="#+id/tvSMSBody"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/tvSMSSend"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/tvSMSSend"
android:text="body" />
</RelativeLayout>
You can always use:
yourListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
To choose multiple items, remember that its interface depend on you creating it.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="#color/white" />
<item
android:state_selected="true"
android:drawable="#drawable/list_item_bg_selected" />
<item
android:drawable="#color/list_bg" />
</selector>

How to get the check box selected position

How to get the selected position in checkbox itemId.
I have two item Veg and non-veg item. I want the result for veg Items only. I show the screen in veg items .But it is not working for veg list checked items.
Response
|1|Amaretto cookies|True
is itemId
food item
True/False.
Based on True or False I need to check the check boxes and retrieve the checked items
Veg items:
|21|1|Amaretto cookies|True|2|Amish White Bread|True|6|Caesar Salad|True|10|Guacamole|True|13|Macaroni and Cheese|True|16|Pancakes|True|17|Pasta|True|18|Ribollita|True|20|Pizza|True|21|Seven Layer Taco Dip|True|22|Shrimp Bisque|True|23|Spicy Bean Salsa|True|24|Sopapilla Cheesecake|True|25|Sopapilla Cheesecake Pie|True|26|Vegetarian Tortilla Stew|True|561|food|True|563|asdf|True|574|veg|True|579|a|True|593|hjg|True|619|hhy|True|
Non- Veg items:
|12|3|Barbeque|False|4|Buffalo Chicken Wings|False|5|Burgers|False|7|Classic Lasagna|False|8|Chicken Chow Mein|False|9|Fried Chicken|False|11|Japanese sushi|False|12|Mezze|False|14|Mutton Pepper Gravy|False|15|Paella Valenciana|False|19|Phad Thai Recipe|False|578|Pizza|False|
Url:
String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/mmealitems.aspx?uname="+LoginForm.str1+"&occasion="+occasionval;
Code:
httpclass obj = new httpclass();
result = obj.server_conn(user_url);
System.out.println(result);
if (result != null)
{
token = new StringTokenizer2(result, "");
}
value = new ArrayList<String>();
while (token.hasMoreTokens())
{
value.add(token.nextToken());
}
value.add(Integer.toString(value.size()));
Integer k=null;
table=new Hashtable<Integer,ArrayList<String>>();
itemId = new ArrayList<String>();
stritem = new ArrayList<String>();
vegitems = new ArrayList<String>();
nonvegitems = new ArrayList<String>();
int id=0,c=0,n=value.size();
for(int j=0; j<n; j++)
{
z = value.get(j);
String[] mystring = z.split("<br>");
int arraysize = mystring.length;
for(int a=0; a<arraysize-1;a++)
{
str2.add(mystring[0]);
str3.add(mystring[1]);
}
}
for(int g=0; g<str2.size();g++)
{
String name = str2.get(g);
token2 = new StringTokenizer2(name, "|", false);
while (token2.hasMoreTokens())
{
vegitems.add(token2.nextToken());
}
}
for(int x=1;x<vegitems.size();x++)
{
itemId.add(vegitems.get(x));
x=x+1;
stritem.add(vegitems.get(x));
x=x+1;
status.add(vegitems.get(x));
}
setListAdapter(new IconicAdapter(this));
selection = (TextView) findViewById(R.id.selection);
getListView().setTextFilterEnabled(true);
save.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tru = new StringBuffer();
fals = new StringBuffer();
for (int i = 0; i<status.size();i++)
{
if (status.get(i).equals("True"))
tru.append(itemId.get(i)+",");
else
fals.append(itemId.get(i)+",");
}
boolean netvalue = false;
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/minsertmealchoiceNew.aspx?uname="+username+"&occasion="+occasionval+
"&choice="+tru+fals+"&ownchoice=&category=";
httpclass obj = new httpclass();
result = obj.server_conn(user_url);
StringTokenizer st = new StringTokenizer(result, "|");
result = st.nextToken();
if ((result.equals("Engagement 1&")) || (result.equals("Wedding 1&")) || (result.equals("Reception 1&")))
{
#SuppressWarnings("rawtypes")
class IconicAdapter extends ArrayAdapter
{
Activity context;
#SuppressWarnings("unchecked")
IconicAdapter(Activity context)
{
super(context, R.layout.rsvp_mealsse, stritem);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = context.getLayoutInflater();
View row = inflater.inflate(R.layout.rsvp_mealsse,null);//viewappointlist, null);
TextView index = (TextView) row.findViewById(R.id.index);
index.setText(String.valueOf(position+1)+".");
TextView label = (TextView) row.findViewById(R.id.title);
label.setText(stritem.get(position));
CheckBox check=(CheckBox)row.findViewById(R.id.check);
check.setId(Integer.parseInt(itemId.get(position)));
if(status.get(position).equals("True"))
check.setChecked(true);
else
check.setChecked(false);
check.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
int ind=itemId.indexOf(String.valueOf(buttonView.getId()));
status.set(ind, String.valueOf(isChecked));
}
});
return (row);
}
}
Snap :
This is what it should look like.False items are checked in the snap
Above shows the full code of my project.
These are my requirements:
It is all about event planner for Food. The invited guests can select and save the interested food items such as pizza, Caesar salad, Ameretocokies etc from the items list and mail to the inviter so that the inviter can view the saved items and arrange for the selected items.
I picked the solution from Romain Guy's solution #
https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
I have used a ViewHolder pattern for smooth scrolling and performance. I have used a SparseBooleanArray to get checked items.
I assume you want the items whose corresponding check boxes are checked.
Also check this to understand listview re-cycles views
How ListView's recycling mechanism works
public class dsds extends Activity
{
ListView lv;
String result = null;
StringTokenizer2 token = null,token2=null;;
ArrayList<String> value,value2 = null;
ArrayList<String> str = null;
ArrayList<String> str2 = null;
ArrayList<String> newstatus=null;
Hashtable<Integer, String> checkstatus=null;
ArrayList<String>stateId=null;
StringBuffer tru,fals;
private SparseBooleanArray mCheckStates;
String z;
ArrayList<Holder> ha = new ArrayList<Holder>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
str2 = new ArrayList<String>();
stateId = new ArrayList<String>();
newstatus=new ArrayList<String>();
lv = (ListView) findViewById(R.id.listView1);
Button b= (Button) findViewById(R.id.button1);
new TheTask().execute();
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder result = new StringBuilder();
for(int i=0;i<str2.size();i++)
{
if(mCheckStates.get(i)==true)
{
result.append(str2.get(i));
result.append("\n");
}
}
Toast.makeText(dsds.this, result, 1000).show();
}
});
}
class TheTask extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/mmealitems.aspx?uname=abcdefg&occasion=Engagement");
try
{
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
if (_response != null)
{
//alertbox("",result);
String[] mystring = _response.split("<br>"); // splt by break
token = new StringTokenizer2(mystring[0], "|", false);// split by |
token2 = new StringTokenizer2(mystring[1], "|", false);
}
/////// for veg
value = new ArrayList<String>();
while (token.hasMoreTokens())
{
value.add(token.nextToken());
}
for(int i=1;i<value.size()-1;i=i+3)
{
// Log.i("....Veg ids.......",""+value.get(i));
stateId.add(value.get(i));
}
for(int i=2;i<value.size()-1;i=i+3)
{
str2.add(value.get(i));
// Log.i("....Veg ids.......",""+value.get(i));
}
for(int i=3;i<=value.size()-1;i=i+3)
{
newstatus.add(value.get(i));
// Log.i("....Veg ids.......",""+value.get(i));
}
// add all to list of Holder
for(int h=0;h<str2.size();h++)
{
Holder holder = new Holder();
holder.setTitle(str2.get(h));
holder.setId(stateId.get(h));
if(newstatus.get(h).equals("False"))
{
holder.setCheck(true);
}
else
{
holder.setCheck(false);
}
ha.add(holder);
}
}catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
lv.setAdapter(new IconicAdapter(dsds.this));
}
}
#SuppressWarnings("rawtypes")
class IconicAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener
{
Activity context;
LayoutInflater mInflater;
#SuppressWarnings("unchecked")
IconicAdapter(Activity context)
{
super(context, R.layout.list_item, str2);
mCheckStates = new SparseBooleanArray(str2.size());
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if(convertView==null)
{
convertView=mInflater.inflate(R.layout.list_item,parent,false);
holder = new ViewHolder();
holder.tv1 = (TextView) convertView.findViewById(R.id.textView1);
holder.tv2 = (TextView) convertView.findViewById(R.id.textView2);
holder.cb = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Holder hol = ha.get(position);
holder.tv1.setText(hol.getId().toString());
holder.tv2.setText(hol.getTitle().toString());
if(hol.isCheck()==true)
{
holder.cb.setChecked(mCheckStates.get(position, true));
holder.cb.setTag(position);
}
else
{
holder.cb.setChecked(mCheckStates.get(position, false));
holder.cb.setTag(position);
}
holder.cb.setOnCheckedChangeListener(this);
return convertView;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
static class ViewHolder
{
TextView tv1,tv2;
CheckBox cb;
}
}
Holder class
public class Holder {
String title;
String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
boolean check;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isCheck() {
return check;
}
public void setCheck(boolean check) {
this.check = check;
}
}
text.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
<ListView
android:id="#+id/listView1"
android:layout_above="#id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
list_tiem.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="33dp"
android:layout_marginTop="40dp"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView1"
android:layout_centerHorizontal="true"
android:text="TextView" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView2"
android:layout_alignBottom="#+id/textView2"
android:layout_alignParentRight="true"
android:text="CheckBox" />
</RelativeLayout>
Snap
Now 1 and 2 are checked and when you click the button at the bottom you see the selected text. I checked 1 and 2 manually. However it depends on the response ie True or False. Right now all veg items are true.
Note: The list displays only veg items
If you are using list-view and you want to check list-view item then you can use below code.
int len = mListView.getCount();
SparseBooleanArray checked = mListView.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)){
..... // Your code whatever you want to do with selected item..
}
else{
....
}

updating onlistitemclick listview from async just really confused

Ok this is my first every android app so don't bash me. I am very open to suggestion if I am doing anything wrong or weird so please don't be shy. I'm have a little bit of trouble updating my listview after I click on an item. Anyways here's the code... I just don't understand how it works I think...
[ MainActivity.java ]
package com.mycompany.myapp2;
import android.app.*;
import android.os.*;
import android.text.method.*;
import android.view.*;
import android.widget.*;
import android.content.*;
import java.util.*;
import java.io.*;
public class MainActivity extends ListActivity
{
public CustomAdapter adapterMain;
private FtpConnectionTask ftpTask;
private LayoutInflater mInflater;
private Vector<RowData> data;
private TextView textView;
#Override
public void onCreate( Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.txtView);
textView.setMovementMethod(new ScrollingMovementMethod());
xBins(textView);
}
/*public void addItems( ListView parent )
{
CustomAdapter adapter = (CustomAdapter) parent.getAdapter();
RowData rd = new RowData("item4", "description4");
data.add(rd);
rd = new RowData("item5", "description5");
data.add(rd);
rd = new RowData("item6", "description6");
data.add(rd);
CustomAdapter adapter = new CustomAdapter(this, R.layout.row, R.id.item, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}*/
public void onListItemClick( ListView parent, View v, int position, long id )
{
ftpTask.row = ftpTask.adapter.getItem(position);
String ftpItem = ftpTask.row.mItem;
if ( ftpTask.row.mDescription == "dir" )
{
String[] args = new String[] { ftpItem };
Object[] aObject = new Object[] { "cd", args, this };
//ftpTask.adapter.clear();
//ftpTask.processCmd(aObject);
}
}
private class RowData
{
protected String mItem;
protected String mDescription;
RowData( String item, String description )
{
mItem = item;
mDescription = description;
}
#Override
public String toString( )
{
return mItem + " " + mDescription;
}
}
private class CustomAdapter extends ArrayAdapter<RowData>
{
public CustomAdapter( Context context, int resource,
int textViewResourceId, List<RowData> objects )
{
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView( int position, View convertView, ViewGroup parent )
{
ViewHolder holder = null;
//widgets displayed by each item in your list
TextView item = null;
TextView description = null;
//data from your adapter
RowData rowData= getItem(position);
//we want to reuse already constructed row views...
if ( null == convertView )
{
convertView = mInflater.inflate(R.layout.row, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
//
holder = (ViewHolder) convertView.getTag();
item = holder.getItem();
item.setText(rowData.mItem);
description = holder.getDescription();
description.setText(rowData.mDescription);
return convertView;
}
}
/**
* Wrapper for row data.
*
*/
private class ViewHolder
{
private View mRow;
private TextView description = null;
private TextView item = null;
public ViewHolder( View row )
{
mRow = row;
}
public TextView getDescription( )
{
if ( null == description )
{
description = (TextView) mRow.findViewById(R.id.description);
}
return description;
}
public TextView getItem( )
{
if ( null == item )
{
item = (TextView) mRow.findViewById(R.id.item);
}
return item;
}
}
public void xBins( View view )
{
IrcConnectionTask task = new IrcConnectionTask();
task.execute(new Object[] { "irc.efnet.pl", 6667, "sgd5", this });
}
}
[ IrcConnectionTask.java ]
package com.mycompany.myapp2;
import android.os.*;
import java.io.*;
import java.net.*;
public class IrcConnectionTask extends AsyncTask<Object, String, String>
{
MainActivity callerActivity;
private Socket socket;
#Override
protected String doInBackground(Object... params)
{
String response = "";
String host = (String)params[0];
Integer port = (Integer)(params[1]);
String nick = (String)params[2];
callerActivity = (MainActivity)params[3];
try
{
socket = new Socket(host, port);
String msg1 = "NICK " + nick;
String msg2 = "USER sur 8 * :be";
String messages[] = { msg1, msg2 };
InputDumper task = new InputDumper();
task.execute(new Object[] { socket, messages, nick, callerActivity});
}
catch ( UnknownHostException e )
{
e.printStackTrace();
}
catch ( IOException e )
{
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result)
{
//textView.setText(result);
}
#Override
protected void onProgressUpdate(String result)
{
//textView.setText(result);
}
}
[ InputDumper.java ]
package com.mycompany.myapp2;
import android.os.*;
import android.text.*;
import java.io.*;
import java.net.*;
import android.widget.*;
public class InputDumper extends AsyncTask<Object, String, String>
{
MainActivity callerActivity;
private String response = "";
private Integer i = 0;
private Boolean Connected = false;
protected String doInBackground(Object... params)
{
try
{
Socket socket = (Socket)params[0];
String messages[] = (String[])params[1];
String nickname = (String)params[2];
callerActivity = (MainActivity) params[3];
//Pattern pattern = Pattern.compile("USERNAME: (.*)");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg;
while ((msg = bufferedReader.readLine()) != null)
{
if (msg.indexOf("USERNAME:") > 0)
{
new FtpConnectionTask().execute(new Object[] { nickname, "emulation", callerActivity });
publishProgress("FTP CONNECTION STARTED!!!");
}
if (msg.startsWith("PING"))
{
String PONG = "PONG " + msg.substring(msg.indexOf(":"));
new OutputWriter().execute(new Object[] { socket, PONG, callerActivity });
Connected = true;
}
else if (i == 4)
{
for (String message : messages)
{
new OutputWriter().execute(new Object[] { socket, message, callerActivity });
}
}
else if (i == 13) //msg.endsWith("servers"))
{
new OutputWriter().execute(new Object[] { socket, "JOIN #xbins", callerActivity });
}
else if (i == 20)
{
new OutputWriter().execute(new Object[] { socket, "PRIVMSG #xbins :!list", callerActivity });
}
response += msg;
publishProgress(msg);
i++;
}
}
catch (IOException e )
{
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result)
{
//textView.setText(result);
}
private TextView textView;
#Override
protected void onProgressUpdate(String... progress)
{
textView = (TextView) callerActivity.findViewById(R.id.txtView);
textView.append(Html.fromHtml("<font color='green'>" + progress[0] + "</font><br />"));
final int scrollAmount = textView.getLayout().getLineTop(textView.getLineCount())
- textView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
textView.scrollTo(0, scrollAmount);
else
textView.scrollTo(0, 0);
}
}
[ OutputWriter.java ]
package com.mycompany.myapp2;
import android.os.*;
import android.text.*;
import java.io.*;
import java.net.*;
import android.widget.*;
public class OutputWriter extends AsyncTask<Object, String, String>
{
MainActivity callerActivity;
private String response = "";
protected String doInBackground(Object... params)
{
try
{
Socket socket = (Socket)params[0];
String message = (String)params[1];
callerActivity = (MainActivity)params[2];
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bufferedWriter.write(message + "\n\r");
bufferedWriter.flush();
publishProgress(message);
}
catch (IOException e )
{
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result)
{
//textView.setText(result);
}
private TextView textView;
#Override
protected void onProgressUpdate(String... progress)
{
textView = (TextView) callerActivity.findViewById(R.id.txtView);
textView.append(Html.fromHtml("<font color='red'>" + progress[0] + "</font><br />"));
final int scrollAmount = textView.getLayout().getLineTop(textView.getLineCount())
- textView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
textView.scrollTo(0, scrollAmount);
else
textView.scrollTo(0, 0);
}
}
[ FtpConnectionTask.java ]
package com.mycompany.myapp2;
import android.os.*;
import android.text.*;
import android.util.*;
import android.widget.*;
import java.io.*;
import org.apache.commons.io.*;
import org.apache.commons.net.ftp.*;
import java.util.*;
import android.view.*;
import android.content.*;
import android.app.*;
public class FtpConnectionTask extends AsyncTask<Object, String, String>
{
public static CustomAdapter adapter;
public static RowData row;
MainActivity callerActivity;
private LayoutInflater mInflater;
public Vector<RowData> data;
private FTPClient mFTPClient = new FTPClient();
protected String doInBackground( Object... params )
{
try
{
if ( mFTPClient.isConnected() )
{
Log.v("TESTING", "Is connected");
String cmd = (String)params[0];
String[] args = (String[])params[1];
callerActivity = (MainActivity) params[2];
if (cmd == "cd")
{
mFTPClient.changeWorkingDirectory(args[0].toString());
String[] names = mFTPClient.listNames();
listRemote(names);
}
}
else
{
String user = (String)params[0];
String pass = (String)params[1];
callerActivity = (MainActivity) params[2];
mFTPClient.connect("distribution.xbins.org");
mFTPClient.login(user, pass);
mFTPClient.enterLocalActiveMode();
mFTPClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
publishProgress("WORKING DIR: " + mFTPClient.printWorkingDirectory());
publishProgress("LOGGED IN");
String[] names = mFTPClient.listNames();
listRemote(names);
FTPFile[] remoteFiles = mFTPClient.listFiles();
for ( FTPFile remoteFile : remoteFiles ) //int i = 0; i < remoteFiles.length; i++)
{
if ( remoteFile.getType() == FTPFile.FILE_TYPE )
{
String name = remoteFile.getName();
long length = remoteFile.getSize();
String readableLength = FileUtils.byteCountToDisplaySize(length);
publishProgress(name + ":\t\t" + readableLength);
}
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
final void listRemote(final String... params)
{
callerActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
mInflater = (LayoutInflater) callerActivity.getSystemService(callerActivity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for ( String name : params )
{
row = new RowData(name, "dir");
data.add(row);
}
adapter = new CustomAdapter(callerActivity, R.layout.row, R.id.item, data);
callerActivity.setListAdapter(adapter);
callerActivity.getListView().setTextFilterEnabled(true);
}
});
}
private TextView textView;
#Override
protected void onProgressUpdate( String... progress )
{
textView = (TextView) callerActivity.findViewById(R.id.txtView);
textView.append(Html.fromHtml("<font color='yellow'>" + progress[0] + "</font><br />"));
final int scrollAmount = textView.getLayout().getLineTop(textView.getLineCount())
- textView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if ( scrollAmount > 0 )
textView.scrollTo(0, scrollAmount);
else
textView.scrollTo(0, 0);
}
public class RowData
{
protected String mItem;
protected String mDescription;
RowData( String item, String description )
{
mItem = item;
mDescription = description;
}
#Override
public String toString( )
{
return mItem + " " + mDescription;
}
}
public class CustomAdapter extends ArrayAdapter<RowData>
{
public CustomAdapter( Context context, int resource,
int textViewResourceId, List<RowData> objects )
{
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView( int position, View convertView, ViewGroup parent )
{
ViewHolder holder = null;
//widgets displayed by each item in your list
TextView item = null;
TextView description = null;
//data from your adapter
RowData rowData= getItem(position);
//we want to reuse already constructed row views...
if ( null == convertView )
{
convertView = mInflater.inflate(R.layout.row, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
//
holder = (ViewHolder) convertView.getTag();
item = holder.getItem();
item.setText(rowData.mItem);
description = holder.getDescription();
description.setText(rowData.mDescription);
return convertView;
}
}
/**
* Wrapper for row data.
*
*/
public class ViewHolder
{
private View mRow;
private TextView description = null;
private TextView item = null;
public ViewHolder( View row )
{
mRow = row;
}
public TextView getDescription( )
{
if ( null == description )
{
description = (TextView) mRow.findViewById(R.id.description);
}
return description;
}
public TextView getItem( )
{
if ( null == item )
{
item = (TextView) mRow.findViewById(R.id.item);
}
return item;
}
}
}
[ row.xml]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#00000000">
<TextView
android:id="#+id/item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"/>
<TextView
android:id="#+id/description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false" />
</LinearLayout>
[ main.xml ]
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
android:id="#+id/txtView"
android:maxLines = "5"
android:scrollbars = "vertical" />
<ListView
android:id="#android:id/list"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_below="#+id/txtView" />
</RelativeLayout>

Categories

Resources