Problems with OnItemClick on a custom ListView - android

I am using a custom ListView with a custom ArrayAdapter for my custom object. I fill my ListView with parsed data from a xml file. I am able to fill the ListView with these data but I want to switch to different activities depending on which item was clicked. I can show with
int position
which item was clicked but how can I retrieve for example the name of the clicked button?
My code:
/**
* Setup
* */
#SuppressWarnings("unchecked")
private void setup() throws IOException {
device_array = new ArrayList<Device>();
//-----------------ACTIONBAR------------------------------------
//activates the default ActionBar
ActionBar actionBar = getActionBar();
actionBar.show();
// set the app icon as an action to go home
actionBar.setDisplayHomeAsUpEnabled(true);
//-------------------INTENT--------------------------------------
//get data from Intent
Intent intent = getIntent();
Name = intent.getStringExtra("Projectname");
IP = intent.getStringExtra("RouterIP");
URL = intent.getStringExtra("URL");
Port = intent.getStringExtra("Port");
//-------------------TEXTVIEWS+LISTVIEW---------------------------------------
nameproject = (TextView)findViewById(R.id.nameproject);
nameproject.setText("Projektname: "+Name);
routerip = (TextView)findViewById(R.id.routerip);
routerip.setText("KNX/IP-Router-Adresse: "+IP);
port = (TextView)findViewById(R.id.port);
port.setText(":"+Port);
url = (TextView)findViewById(R.id.url);
url.setText("URL: "+URL);
//Fill ListView
display_listview();
devices = (ListView)findViewById(R.id.deviceList);
adapter = new DeviceAdapter(this,
R.layout.listviewitem_device, device_array);
//add a view which is shown if the ListView is empty
devices.setEmptyView(findViewById(R.id.empty_list_view));
//Click on item in listview
devices.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(ProjectView.this, OnOff.class);
i.putExtra("Uniqid","From_ProjectView_Activity");
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
});
devices.setAdapter(adapter);
//-------------------- READ ARRAYLIST-------------------------------
}
/**
* Insert Controls
* */
#SuppressWarnings("unchecked")
private void display_listview() {
//------------------ READ ARRAYLIST--------------------------------
//read ArrayList which is saved local
//change path to non-root folder
String filePath = context.getFilesDir().getPath().toString()+"/"+Name;
Log.d("FilestreamfromFolder", "Filepath:"+filePath+ " Projektname:"+Name);
File f = new File(filePath);
try
{
FileInputStream fileIn = new FileInputStream(f);
ObjectInputStream in = new ObjectInputStream(fileIn);
XML = (ArrayList<Datapoint>) in.readObject();
Log.d("XML",XML.toString());
in.close();
fileIn.close();
} catch(IOException ioe)
{
ioe.printStackTrace();
return;
} catch(ClassNotFoundException c)
{
Log.d("FILESTREAM", ".Datapoint class not found.");
c.printStackTrace();
return;
}
//------------------ FILL DEVICE ARRAY FROM XML--------------------------------
for (int i=0; i<XML.size(); i++) {
if (XML.get(i).getDptID().contains(ValueTemp)) {
Datapoint d = XML.get(i);
device_array.add(new Device(d.getName().toString(), R.drawable.temperature_5));
Log.d("Temperature", d.getName().toString()+" added");
}
}
for (int i=0; i<XML.size(); i++) {
if (XML.get(i).getDptID().contains(ValueLux)) {
Datapoint d = XML.get(i);
device_array.add(new Device(d.getName().toString(), R.drawable.brightness));
Log.d("Brightness", d.getName().toString()+" added");
}
}
for (int i=0; i<XML.size(); i++) {
if (XML.get(i).getDptID().contains(PercentScaling)) {
Datapoint d = XML.get(i);
device_array.add(new Device(d.getName().toString(), R.drawable.lamp));
Log.d("Dimmer", d.getName().toString()+" added");
}
}
for (int i=0; i<XML.size(); i++) {
//check XML file for datapoint 1.001 which demontrates a on/off switch
if (XML.get(i).getDptID().contains(OnOff)) {
Datapoint d = XML.get(i);
device_array.add(new Device(d.getName().toString(), R.drawable.lamp_switch));
Log.d("OnOFF", d.getName().toString()+" added");
}
}
}
My Datapoint class:
package XMLParser;
import java.io.Serializable;
public class Datapoint implements Serializable{
/**
*
*/
private static final long serialVersionUID = 4917183601569112207L;
private String stateBased;
private String name;
private String priority;
private String mainNumber;
private String groupadress;
private String dptID;
public Datapoint(){
}
public String getMainNumber() {
return mainNumber;
}
public void setMainNumber(String mainNumber) {
this.mainNumber = mainNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStateBased() {
return stateBased;
}
public void setStateBased(String stateBased) {
this.stateBased = stateBased;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
public String getGroupadress() {
return groupadress;
}
public void setGroupadress(String group) {
this.groupadress = convert_groupadress(group);
}
public String getDptID() {
return dptID;
}
public void setDptID(String dptID) {
this.dptID = dptID;
}
#Override
public String toString() {
return "[[" + this.stateBased + "] ["+ this.name + "] [" + this.mainNumber + "]" + " [" + this.dptID
+ "] [" + this.priority + "] [" + this.groupadress + " ]]";
}
public String convert_groupadress(String groupadress) {
String groupaddress ="";
int grpadr = Integer.parseInt(groupadress);
int first = grpadr / 2048;
int first_res = grpadr-(first*2048);
int second = first_res / 256;
int second_res = first_res-(second*256);
int third = second_res / 1;
//int third_res = second_res-(third*32);
groupaddress = Integer.toString(first) +"/"+ Integer.toString(second) + "/"+ Integer.toString(third);
return groupaddress;
}
}

Calling the getItem(int position) method on your adapter will get the DataPoint for that position, so change your onItemClick method to be something like:
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
DataPoint point = (DataPoint) parent.getAdapter().getItem(position);
String pointName = point.getName();
// TODO: Launch an activity with that name or something.
}

I solved it this way:
//Click on item in listview
devices.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(device_array.get(position).getResImage()==R.drawable.brightness){
Intent i0 = new Intent(ProjectView.this, Brightness.class);
i0.putExtra("Uniqid","From_ProjectView_Activity");
i0.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i0);
}
if(device_array.get(position).getResImage()==R.drawable.temperature_5){
Intent i0 = new Intent(ProjectView.this, Temperature.class);
i0.putExtra("Uniqid","From_ProjectView_Activity");
i0.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i0);
}
if(device_array.get(position).getResImage()==R.drawable.lamp){
Intent i0 = new Intent(ProjectView.this, Dimmer.class);
i0.putExtra("Uniqid","From_ProjectView_Activity");
i0.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i0);
}
if(device_array.get(position).getResImage()==R.drawable.lamp_switch){
Intent i0 = new Intent(ProjectView.this, OnOff.class);
i0.putExtra("Uniqid","From_ProjectView_Activity");
i0.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i0);
}
}
});

Use the view , you are using to inflate the data in listview.
as i was using a textview.
here what i used,
TextView tv = (TextView) v.findViewById(R.id.contacts_name);
String savedname = tv.getText().toString();
here v is the argument that we get in the method
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3)
{ // do something
}

Related

How to get edit text values from a listview

I am not able to get edittext value from dynamic listview. When I am scrolling listview, entered values in edit text is going invisible
Below is My Activity file -
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_servic_homepage);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
url = getResources().getString(R.string.webservice);
aq = new AQuery(ServicHomepage.this);
cd = new ConnectionDetector(ServicHomepage.this);
findviewbyId();
progressdialog();
if (cd.isConnectingToInternet()) {
getintentData();
} else {
Toast.makeText(ServicHomepage.this, "CheckIternet connection", Toast.LENGTH_SHORT).show();
}
}
private void progressdialog() {
pd = new ProgressDialog(ServicHomepage.this);
pd.setMessage("Loading...");
}
public void findviewbyId() {
recyclerview = (ListView) findViewById(R.id.service_recycler_view);
update_descrptn = (TextView) findViewById(R.id.update_descrptn);
uploadimages = (TextView) findViewById(R.id.uploadimages);
}
public void getintentData() {
SharedPreferences prefs = getSharedPreferences(Constants.PREFS_NAME, 0);
catid = prefs.getString(Constants.CATID, "");
subcatid = prefs.getString(Constants.SUBCATID, "");
user_id = prefs.getString(Constants.USERID, "");
isappointment = prefs.getString(Constants.IS_APPOINTMENT, "");
clicklistener();
}
public void clicklistener() {
uploadimages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), GalleryAlbumActivity.class);
startActivity(i);
}
});
update_descrptn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ServicHomepage.this, "" + serv_adapter.getItem(POSITION), Toast.LENGTH_SHORT).show();
for (int i = 0; i < serv_adapter.getCount(); i++) {
View view = serv_adapter.getView(i,null,null);
EditText edittext = (EditText)view.findViewById(R.id.et_amount);
EditText et_description = (EditText)view.findViewById(R.id.et_description);
String str = edittext.getText().toString();
String str1 = et_description.getText().toString();
Toast.makeText(ServicHomepage.this, str + "==" + str1, Toast.LENGTH_SHORT).show();
}
updateList();
}
});
}
private void updateList() {
String substring = null, msgString = "";
String MAIN_CART = null;
MAIN_CART = "{\"service\":[%s]}";
String temstring = "";
for (int i = 0; i < arrayList.size(); i++) {
substring = "{\"title\":\"" + arrayList.get(i).getTitle() + "\",\"subcatid\":\"" + arrayList.get(i).getSubcatid()
+ "\",\"amount\":\"" + "" + "\",\"description\":\"" + "" + "\"}" + ",";
temstring = temstring + substring;
}
temstring = temstring.substring(0, temstring.length() - 1);
msgString = msgString + String.format(MAIN_CART, temstring);
Log.e("msgString=============", msgString);
}
This is the method where all the items are adding in the list
public String parseanimcat(String object) {
try {
JSONObject json = new JSONObject(object);
JSONObject jsonobj = json.getJSONObject("data");
status1 = jsonobj.getString("status");
message = jsonobj.getString("message");
arrayList = new ArrayList<>();
JSONArray jarray = jsonobj.getJSONArray("dataFound");
for (int i = 0; i <= jarray.length(); i++) {
JSONObject jobj = jarray.getJSONObject(i);
String category = jobj.getString("category");
String subsubcat_id = jobj.getString("subsubcat_id");
Toast.makeText(ServicHomepage.this, category + "==" + subsubcat_id, Toast.LENGTH_SHORT).show();
model = new Data_Model();
model.setTitle(category);
model.setSubcatid(subsubcat_id);
arrayList.add(model);
}
} catch (JSONException e) {
e.printStackTrace();
}
return object;
}
This is my adapter class-
private class service_list_adapter extends ArrayAdapter<Data_Model>{
private ArrayList<Data_Model> array_list;
Context context;
String[] etValArr;
ViewHolder holder;
String[] totalValue;
Data_Model model;
HashMap<String, String> hm = new HashMap<>();
ArrayList<HashMap<String, String>> list = new ArrayList<>();
public service_list_adapter(Context context,int resourceId,ArrayList<Data_Model> arrayList) {
super(context,resourceId,arrayList);
this.context = context;
this.array_list = arrayList;
etValArr = new String[array_list.size()];
totalValue = new String[array_list.size()];
}
private class ViewHolder {
public TextView serv_title;
public EditText serv_descrptn, serv_amount;
}
public View getView(int position, View convertView, ViewGroup parent) {
model = array_list.get(position);
POSITION = position;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.serv_cat_rowitem, null);
holder = new ViewHolder();
holder.serv_title = (TextView) convertView.findViewById(R.id.serv_txt);
holder.serv_descrptn = (EditText) convertView.findViewById(R.id.et_description);
holder.serv_amount = (EditText) convertView.findViewById(R.id.et_amount);
convertView.setTag(holder);
holder.serv_title.setTag(position);
holder.serv_descrptn.setTag(position);
holder.serv_amount.setTag(position);
} else
holder = (ViewHolder) convertView.getTag();
holder.serv_title.setText(model.getTitle());
holder.serv_descrptn.setText(model.getServdescription());
holder.serv_amount.setText(model.getServamount());
holder.serv_amount.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
model.setServamount(s.toString());
}
});
holder.serv_descrptn.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
model.setServdescription(s.toString());
}
});
return convertView;
}
}
be more specific exactly which editText value you want.
you can implement onScrollListner on list and save the value of the editText on that event and later use it

Dynamic ListView scroll TextView changed automatically

when i click + button increment the price and click - button decrease the price it's work perfectly but when i scroll listview the value of tvPrices (TextView) is changed.
What should i do for the stay increment price?
here is my adapter
public class ListAdapter extends BaseAdapter {
public ArrayList<Integer> quantity = new ArrayList<Integer>();
public ArrayList<Integer> price = new ArrayList<Integer>();
private String[] listViewItems, prices, static_price;
TypedArray images;
View row = null;
static String get_price, get_quntity;
int g_quntity, g_price, g_minus;
private Context context;
CustomButtonListener customButtonListener;
static HashMap<String, String> map = new HashMap<>();
public ListAdapter(Context context, String[] listViewItems, TypedArray images, String[] prices) {
this.context = context;
this.listViewItems = listViewItems;
this.images = images;
this.prices = prices;
for (int i = 0; i < listViewItems.length; i++) {
quantity.add(0);
price.add(0);
}
}
public void setCustomButtonListener(CustomButtonListener customButtonListner) {
this.customButtonListener = customButtonListner;
}
#Override
public int getCount() {
return listViewItems.length;
}
#Override
public String getItem(int position) {
return listViewItems[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ListViewHolder listViewHolder;
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.activity_custom_listview, parent, false);
listViewHolder = new ListViewHolder();
listViewHolder.tvProductName = (TextView) row.findViewById(R.id.tvProductName);
listViewHolder.ivProduct = (ImageView) row.findViewById(R.id.ivproduct);
listViewHolder.tvPrices = (TextView) row.findViewById(R.id.tvProductPrice);
listViewHolder.btnPlus = (ImageButton) row.findViewById(R.id.ib_addnew);
listViewHolder.edTextQuantity = (EditText) row.findViewById(R.id.editTextQuantity);
listViewHolder.btnMinus = (ImageButton) row.findViewById(R.id.ib_remove);
static_price = context.getResources().getStringArray(R.array.Price);
row.setTag(listViewHolder);
} else {
row = convertView;
listViewHolder = (ListViewHolder) convertView.getTag();
}
listViewHolder.ivProduct.setImageResource(images.getResourceId(position, -1));
try {
listViewHolder.edTextQuantity.setText(quantity.get(position) + "");
} catch (Exception e) {
e.printStackTrace();
}
listViewHolder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, listViewHolder.edTextQuantity, 1);
quantity.set(position, quantity.get(position) + 1);
price.set(position, price.get(position) + 1);
row.getTag(position);
get_price = listViewHolder.tvPrices.getText().toString();
g_price = Integer.valueOf(static_price[position]);
get_quntity = listViewHolder.edTextQuantity.getText().toString();
g_quntity = Integer.valueOf(get_quntity);
map.put("" + listViewHolder.tvProductName.getText().toString(), " " + listViewHolder.edTextQuantity.getText().toString());
listViewHolder.tvPrices.setText("" + g_price * g_quntity);
// Log.d("A ", "" + a);
// Toast.makeText(context, "A" + a, Toast.LENGTH_LONG).show();
// Log.d("Position ", "" + position);
// System.out.println(+position + " Values " + map.values());
ShowHashMapValue();
listViewHolder.tvPrices.setText("" + g_price * g_quntity);
}
}
});
listViewHolder.btnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, listViewHolder.edTextQuantity, -1);
if (quantity.get(position) > 0)
quantity.set(position, quantity.get(position) - 1);
get_price = listViewHolder.tvPrices.getText().toString();
g_minus = Integer.valueOf(get_price);
g_price = Integer.valueOf(static_price[position]);
int minus = g_minus - g_price;
if (minus >= g_price) {
listViewHolder.tvPrices.setText("" + minus);
}
map.put("" + listViewHolder.tvProductName.getText().toString(), " " + listViewHolder.edTextQuantity.getText().toString());
ShowHashMapValue();
}
}
});
listViewHolder.tvProductName.setText(listViewItems[position]);
listViewHolder.tvPrices.setText(prices[position]);
return row;
}
private void ShowHashMapValue() {
/**
* get the Set Of keys from HashMap
*/
Set setOfKeys = map.keySet();
/**
* get the Iterator instance from Set
*/
Iterator iterator = setOfKeys.iterator();
/**
* Loop the iterator until we reach the last element of the HashMap
*/
while (iterator.hasNext()) {
/**
* next() method returns the next key from Iterator instance.
* return type of next() method is Object so we need to do DownCasting to String
*/
String key = (String) iterator.next();
/**
* once we know the 'key', we can get the value from the HashMap
* by calling get() method
*/
String value = map.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
}
}
In onclick, after you decrement the value call notifyDataSetChanged()
notifyDataSetChanged
but its a costly operation, since it refreshes complete list

Not able to see files while opening file browser using AndroidFileBrowser Library

I am trying to make a File browser for which I am taking help of this library.
Now according their code I am trying to implement, it's opening the desired location in the cell, however I am only able to see directories not files. As instructed I have chosen the option to choose Files only still I am not able to see Files there. Below is the code I am using
Intent fileExploreIntent = new Intent(FileBrowserActivity.INTENT_ACTION_SELECT_DIR,
null, getActivity(), FileBrowserActivity.class
);
startActivityForResult(fileExploreIntent,1);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 1) {
if(resultCode == getActivity().RESULT_OK) {
String newDir = data.getStringExtra(FileBrowserActivity.returnDirectoryParameter);
Toast.makeText( getActivity(), "Received path from file browser:"+newDir, Toast.LENGTH_LONG).show();
} else {//if(resultCode == this.RESULT_OK) {
Toast.makeText( getActivity(),"Received NO result from file browser",Toast.LENGTH_LONG).show();
}//END } else {//if(resultCode == this.RESULT_OK) {
}//if (requestCode == REQUEST_CODE_PICK_FILE_TO_SAVE_INTERNAL) {
super.onActivityResult(requestCode, resultCode, data);
}
Code for FileBrowserActivity is
public class FileBrowserActivity extends Activity {
// Intent Action Constants
public static final String INTENT_ACTION_SELECT_DIR = "com.afixi.xmppclientandroid.SELECT_DIRECTORY_ACTION";
public static final String INTENT_ACTION_SELECT_FILE = "com.afixi.xmppclientandroid.SELECT_FILE_ACTION";
// Intent parameters names constants
public static final String startDirectoryParameter = "com.afixi.xmppclientandroid.directoryPath";
public static final String returnDirectoryParameter = "com.afixi.xmppclientandroid.directoryPathRet";
public static final String returnFileParameter = "com.afixi.xmppclientandroid.filePathRet";
public static final String showCannotReadParameter = "com.afixi.xmppclientandroid.showCannotRead";
public static final String filterExtension = "com.afixi.xmppclientandroid.filterExtension";
// Stores names of traversed directories
ArrayList<String> pathDirsList = new ArrayList<String>();
// Check if the first level of the directory structure is the one showing
// private Boolean firstLvl = true;
private static final String LOGTAG = "F_PATH";
private List<Item> fileList = new ArrayList<Item>();
private File path = null;
private String chosenFile;
// private static final int DIALOG_LOAD_FILE = 1000;
ArrayAdapter<Item> adapter;
private boolean showHiddenFilesAndDirs = true;
private boolean directoryShownIsEmpty = false;
private String filterFileExtension = null;
// Action constants
private static int currentAction = -1;
private static final int SELECT_DIRECTORY = 1;
private static final int SELECT_FILE = 2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// In case of
// ua.com.vassiliev.androidfilebrowser.SELECT_DIRECTORY_ACTION
// Expects com.mburman.fileexplore.directoryPath parameter to
// point to the start folder.
// If empty or null, will start from SDcard root.
setContentView(R.layout.ua_com_vassiliev_filebrowser_layout);
// Set action for this activity
Intent thisInt = this.getIntent();
currentAction = SELECT_DIRECTORY;// This would be a default action in
// case not set by intent
if (thisInt.getAction().equalsIgnoreCase(INTENT_ACTION_SELECT_FILE)) {
Log.d(LOGTAG, "SELECT ACTION - SELECT FILE");
currentAction = SELECT_FILE;
}
showHiddenFilesAndDirs = thisInt.getBooleanExtra(
showCannotReadParameter, true);
filterFileExtension = thisInt.getStringExtra(filterExtension);
setInitialDirectory();
parseDirectoryPath();
loadFileList();
this.createFileListAdapter();
this.initializeButtons();
this.initializeFileListView();
updateCurrentDirectoryTextView();
Log.d(LOGTAG, path.getAbsolutePath());
}
private void setInitialDirectory() {
Intent thisInt = this.getIntent();
String requestedStartDir = thisInt
.getStringExtra(startDirectoryParameter);
if (requestedStartDir != null && requestedStartDir.length() > 0) {// if(requestedStartDir!=null
File tempFile = new File(requestedStartDir);
if (tempFile.isDirectory())
this.path = tempFile;
}// if(requestedStartDir!=null
if (this.path == null) {// No or invalid directory supplied in intent
// parameter
if (Environment.getExternalStorageDirectory().isDirectory()
&& Environment.getExternalStorageDirectory().canRead())
path = Environment.getExternalStorageDirectory();
else
path = new File("/");
}// if(this.path==null) {//No or invalid directory supplied in intent
// parameter
}// private void setInitialDirectory() {
private void parseDirectoryPath() {
pathDirsList.clear();
String pathString = path.getAbsolutePath();
String[] parts = pathString.split("/");
int i = 0;
while (i < parts.length) {
pathDirsList.add(parts[i]);
i++;
}
}
private void initializeButtons() {
Button upDirButton = (Button) this.findViewById(R.id.upDirectoryButton);
upDirButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d(LOGTAG, "onclick for upDirButton");
loadDirectoryUp();
loadFileList();
adapter.notifyDataSetChanged();
updateCurrentDirectoryTextView();
}
});// upDirButton.setOnClickListener(
Button selectFolderButton = (Button) this
.findViewById(R.id.selectCurrentDirectoryButton);
if (currentAction == SELECT_DIRECTORY) {
selectFolderButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d(LOGTAG, "onclick for selectFolderButton");
returnDirectoryFinishActivity();
}
});
} else {// if(currentAction == this.SELECT_DIRECTORY) {
selectFolderButton.setVisibility(View.GONE);
}// } else {//if(currentAction == this.SELECT_DIRECTORY) {
}// private void initializeButtons() {
private void loadDirectoryUp() {
// present directory removed from list
String s = pathDirsList.remove(pathDirsList.size() - 1);
// path modified to exclude present directory
path = new File(path.toString().substring(0,
path.toString().lastIndexOf(s)));
fileList.clear();
}
private void updateCurrentDirectoryTextView() {
int i = 0;
String curDirString = "";
while (i < pathDirsList.size()) {
curDirString += pathDirsList.get(i) + "/";
i++;
}
if (pathDirsList.size() == 0) {
((Button) this.findViewById(R.id.upDirectoryButton))
.setEnabled(false);
curDirString = "/";
} else
((Button) this.findViewById(R.id.upDirectoryButton))
.setEnabled(true);
long freeSpace = getFreeSpace(curDirString);
String formattedSpaceString = formatBytes(freeSpace);
if (freeSpace == 0) {
Log.d(LOGTAG, "NO FREE SPACE");
File currentDir = new File(curDirString);
if(!currentDir.canWrite())
formattedSpaceString = "NON Writable";
}
((Button) this.findViewById(R.id.selectCurrentDirectoryButton))
.setText("Select\n[" + formattedSpaceString
+ "]");
((TextView) this.findViewById(R.id.currentDirectoryTextView))
.setText("Current directory: " + curDirString);
}// END private void updateCurrentDirectoryTextView() {
private void showToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
private void initializeFileListView() {
ListView lView = (ListView) this.findViewById(R.id.fileListView);
lView.setBackgroundColor(Color.LTGRAY);
LinearLayout.LayoutParams lParam = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
lParam.setMargins(15, 5, 15, 5);
lView.setAdapter(this.adapter);
lView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
chosenFile = fileList.get(position).file;
File sel = new File(path + "/" + chosenFile);
Log.d(LOGTAG, "Clicked:" + chosenFile);
if (sel.isDirectory()) {
if (sel.canRead()) {
// Adds chosen directory to list
pathDirsList.add(chosenFile);
path = new File(sel + "");
Log.d(LOGTAG, "Just reloading the list");
loadFileList();
adapter.notifyDataSetChanged();
updateCurrentDirectoryTextView();
Log.d(LOGTAG, path.getAbsolutePath());
} else {// if(sel.canRead()) {
showToast("Path does not exist or cannot be read");
}// } else {//if(sel.canRead()) {
}// if (sel.isDirectory()) {
// File picked or an empty directory message clicked
else {// if (sel.isDirectory()) {
Log.d(LOGTAG, "item clicked");
if (!directoryShownIsEmpty) {
Log.d(LOGTAG, "File selected:" + chosenFile);
returnFileFinishActivity(sel.getAbsolutePath());
}
}// else {//if (sel.isDirectory()) {
}// public void onClick(DialogInterface dialog, int which) {
});// lView.setOnClickListener(
}// private void initializeFileListView() {
private void returnDirectoryFinishActivity() {
Intent retIntent = new Intent();
retIntent.putExtra(returnDirectoryParameter, path.getAbsolutePath());
this.setResult(RESULT_OK, retIntent);
this.finish();
}// END private void returnDirectoryFinishActivity() {
private void returnFileFinishActivity(String filePath) {
Intent retIntent = new Intent();
retIntent.putExtra(returnFileParameter, filePath);
this.setResult(RESULT_OK, retIntent);
this.finish();
}// END private void returnDirectoryFinishActivity() {
private void loadFileList() {
try {
path.mkdirs();
} catch (SecurityException e) {
Log.e(LOGTAG, "unable to write on the sd card ");
}
fileList.clear();
if (path.exists() && path.canRead()) {
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String filename) {
File sel = new File(dir, filename);
boolean showReadableFile = showHiddenFilesAndDirs
|| sel.canRead();
// Filters based on whether the file is hidden or not
if (currentAction == SELECT_DIRECTORY) {
return (sel.isDirectory() && showReadableFile);
}
if (currentAction == SELECT_FILE) {
// If it is a file check the extension if provided
if (sel.isFile() && filterFileExtension != null) {
return (showReadableFile && sel.getName().endsWith(
filterFileExtension));
}
return (showReadableFile);
}
return true;
}// public boolean accept(File dir, String filename) {
};// FilenameFilter filter = new FilenameFilter() {
String[] fList = path.list(filter);
this.directoryShownIsEmpty = false;
for (int i = 0; i < fList.length; i++) {
// Convert into file path
File sel = new File(path, fList[i]);
Log.d(LOGTAG,
"File:" + fList[i] + " readable:"
+ (Boolean.valueOf(sel.canRead())).toString());
int drawableID = R.drawable.file_icon;
boolean canRead = sel.canRead();
// Set drawables
if (sel.isDirectory()) {
if (canRead) {
drawableID = R.drawable.folder_icon;
} else {
drawableID = R.drawable.folder_icon_light;
}
}
fileList.add(i, new Item(fList[i], drawableID, canRead));
}// for (int i = 0; i < fList.length; i++) {
if (fileList.size() == 0) {
// Log.d(LOGTAG, "This directory is empty");
this.directoryShownIsEmpty = true;
fileList.add(0, new Item("Directory is empty", -1, true));
} else {// sort non empty list
Collections.sort(fileList, new ItemFileNameComparator());
}
} else {
Log.e(LOGTAG, "path does not exist or cannot be read");
}
// Log.d(TAG, "loadFileList finished");
}// private void loadFileList() {
private void createFileListAdapter() {
adapter = new ArrayAdapter<Item>(this,
android.R.layout.select_dialog_item, android.R.id.text1,
fileList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// creates view
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view
.findViewById(android.R.id.text1);
// put the image on the text view
int drawableID = 0;
if (fileList.get(position).icon != -1) {
// If icon == -1, then directory is empty
drawableID = fileList.get(position).icon;
}
textView.setCompoundDrawablesWithIntrinsicBounds(drawableID, 0,
0, 0);
textView.setEllipsize(null);
// add margin between image and text (support various screen
// densities)
// int dp5 = (int) (5 *
// getResources().getDisplayMetrics().density + 0.5f);
int dp3 = (int) (3 * getResources().getDisplayMetrics().density + 0.5f);
// TODO: change next line for empty directory, so text will be
// centered
textView.setCompoundDrawablePadding(dp3);
textView.setBackgroundColor(Color.LTGRAY);
return view;
}// public View getView(int position, View convertView, ViewGroup
};// adapter = new ArrayAdapter<Item>(this,
}// private createFileListAdapter(){
private class Item {
public String file;
public int icon;
public boolean canRead;
public Item(String file, Integer icon, boolean canRead) {
this.file = file;
this.icon = icon;
}
#Override
public String toString() {
return file;
}
}// END private class Item {
private class ItemFileNameComparator implements Comparator<Item> {
public int compare(Item lhs, Item rhs) {
return lhs.file.toLowerCase().compareTo(rhs.file.toLowerCase());
}
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Log.d(LOGTAG, "ORIENTATION_LANDSCAPE");
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
Log.d(LOGTAG, "ORIENTATION_PORTRAIT");
}
// Layout apparently changes itself, only have to provide good onMeasure
// in custom components
// TODO: check with keyboard
// if(newConfig.keyboard == Configuration.KEYBOARDHIDDEN_YES)
}// END public void onConfigurationChanged(Configuration newConfig) {
public static long getFreeSpace(String path) {
StatFs stat = new StatFs(path);
long availSize = (long) stat.getAvailableBlocks()
* (long) stat.getBlockSize();
return availSize;
}// END public static long getFreeSpace(String path) {
public static String formatBytes(long bytes) {
// TODO: add flag to which part is needed (e.g. GB, MB, KB or bytes)
String retStr = "";
// One binary gigabyte equals 1,073,741,824 bytes.
if (bytes > 1073741824) {// Add GB
long gbs = bytes / 1073741824;
retStr += (new Long(gbs)).toString() + "GB ";
bytes = bytes - (gbs * 1073741824);
}
// One MB - 1048576 bytes
if (bytes > 1048576) {// Add GB
long mbs = bytes / 1048576;
retStr += (new Long(mbs)).toString() + "MB ";
bytes = bytes - (mbs * 1048576);
}
if (bytes > 1024) {
long kbs = bytes / 1024;
retStr += (new Long(kbs)).toString() + "KB";
bytes = bytes - (kbs * 1024);
} else
retStr += (new Long(bytes)).toString() + " bytes";
return retStr;
}// public static String formatBytes(long bytes){
}// END public class FileBrowserActivity extends Activity {

Get the value of clicked Item of a custom listview?

I have created a Custom listview and set data by parsing a link and sorted them inside the list. Now when I am going to make a click and get the value of the individual object of a row I can't get the object of clicked row.
public class MainActivity extends Activity implements OnChildClickListener,
OnItemClickListener {
private ExpandableListView mExpandableListView;
private List<GroupEntity> mGroupCollection;
String URL;
ArrayList<EventParsingClass> EventObject_Collection = new ArrayList<EventParsingClass>();
ArrayList<Date> DateArray = new ArrayList<Date>();
ArrayList<ArrayList<EventParsingClass>> arrayOfEventDescription = new ArrayList<ArrayList<EventParsingClass>>();
MyListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.event_mainactivity);
prepareResource();
initPage();
URL = "http://..............";
ParsingWithURL(URL);
}
private void ParsingWithURL(String uRL2) {
// TODO Auto-generated method stub
new JSONPARSINGFOREVENTSTREAM().execute(URL);
}
private class JSONPARSINGFOREVENTSTREAM extends
AsyncTask<String, Void, String> {
private final String TAG_ID = "id";
private final String TAG_Title = "title";
private final String TAG_Description = "description";
private final String TAG_StartDate = "start_datetime";
private final String TAG_EndDate = "end_datetime";
private final String TAG_City = "place_city";
private final String TAG_Club = "place_club";
private final String TAG_AgeLimit = "event_agelimit";
private static final String TAG_Event_streamable = "data";
EventParsingClass EPC;
JSONArray streamable = null;
ProgressDialog pDialog;
#SuppressLint("SimpleDateFormat")
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
Log.d("************PARAMS", arg0[0]);
JSONParser jparser = new JSONParser();
JSONObject json = jparser.getJSONFromUrl(arg0[0]);
try {
streamable = json.getJSONArray(TAG_Event_streamable);
for (int i = 0; i < streamable.length(); i++) {
EPC = new EventParsingClass();
JSONObject c = streamable.getJSONObject(i);
EPC.setId(c.getString(TAG_ID));
EPC.setPlace_city(c.getString(TAG_City));
EPC.setPlace_club(c.getString(TAG_Club));
EPC.setTitle(c.getString(TAG_Title));
EPC.setDescription(c.getString(TAG_Description));
EPC.setSratdate_time(c.getString(TAG_StartDate));
EPC.setEnddate_time(c.getString(TAG_EndDate));
EPC.setEvent_agelimit(c.getString(TAG_AgeLimit));
long difference = EPC.geEnddate_time_date().getTime()
- EPC.getSratdate_time_date().getTime();
int day_difference = (int) (difference / (1000 * 3600 * 24));
// Log.d("Difference", "" + day_difference);
if (day_difference == 0) {
AddDay(EPC.getSratdate_time_date());
} else {
if (DateArray.size() == 0) {
DateArray.add(EPC.getSratdate_time_date());
long startday = EPC.getSratdate_time_date()
.getTime();
for (int k = 1; k <= day_difference; k++) {
long constructedday = startday
+ (1000 * 3600 * 24) * k;
Date Constructed_value = new Date(
constructedday);
DateArray.add(Constructed_value);
}
} else {
AddDay(EPC.getSratdate_time_date());
long startday = EPC.getSratdate_time_date()
.getTime();
for (int k = 1; k <= day_difference; k++) {
long constructedday = startday
+ (1000 * 3600 * 24) * k;
Date Constructed_value = new Date(
constructedday);
AddDay(Constructed_value);
}
}
}
EventObject_Collection.add(EPC);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
private void AddDay(Date value) {
// TODO Auto-generated method stub
if (DateArray.size() == 0) {
DateArray.add(value);
} else {
boolean b = true;
for (Date s : DateArray) {
if (s.equals(value)) {
b = false;
break;
}
}
if (b) {
DateArray.add(value);
}
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.d("+++++++++++++++++++++++number of Items in List", ""
+ DateArray.size());
AddDetailedItemToListView();
AddHeaderItemsToListView();
pDialog.dismiss();
}
private void AddDetailedItemToListView() {
// TODO Auto-generated method stub
for (Date s : DateArray) {
ArrayList<EventParsingClass> constructed_arrayfor_items = new ArrayList<EventParsingClass>();
for (int g = 0; g < EventObject_Collection.size(); g++) {
EventParsingClass EVPC = EventObject_Collection.get(g);
long new_startdate = EVPC.getSratdate_time_date().getTime();
long new_endtdate = EVPC.geEnddate_time_date().getTime();
long date = s.getTime();
if (date >= new_startdate && date <= new_endtdate) {
Log.d("^^^^^^^^^^^ Value Of Date ", "" + s);
Log.d("^^^^^^^^^^^ Value Of StartDay ",
"" + EVPC.getSratdate_time_date());
Log.d("^^^^^^^^^^^ Value Of EndDay ",
"" + EVPC.geEnddate_time_date());
constructed_arrayfor_items.add(EVPC);
}
}
arrayOfEventDescription.add(constructed_arrayfor_items);
Log.d("^^^^^^^^^^^^^^^^^^^arrayOfEventDescription", ""
+ arrayOfEventDescription);
}
}
private void AddHeaderItemsToListView() {
// TODO Auto-generated method stub
ListView lv = (ListView) findViewById(R.id.list_evevnt);
LayoutInflater i = LayoutInflater.from(MainActivity.this);
List<Item> items = new ArrayList<Item>();
int length_of_datearray = DateArray.size();
Log.d("!!!!!!!!!!!!!!!", "" + DateArray.size());
Log.d("EEEEEEEEEEEEEEEEEEEE", "" + arrayOfEventDescription.size());
for (ArrayList<EventParsingClass> It : arrayOfEventDescription) {
Log.d("", "" + It.size());
for (EventParsingClass oETC : It) {
Log.d("*******" + oETC.getTitle(),
"" + oETC.getSratdate_time_date());
}
}
for (int m = 0; m < length_of_datearray; m++) {
String day_of_header = (String) android.text.format.DateFormat
.format("EEEE", DateArray.get(m));
String month_of_header = (String) android.text.format.DateFormat
.format("MMM", DateArray.get(m));
String date_of_header = (String) android.text.format.DateFormat
.format("dd", DateArray.get(m));
String total_header = day_of_header + " " + month_of_header
+ " " + date_of_header;
items.add(new Header(i, "" + total_header));
ArrayList<EventParsingClass> Arraylist_for_loop = arrayOfEventDescription
.get(m);
for (int h = 0; h < Arraylist_for_loop.size(); h++) {
String description = Arraylist_for_loop.get(h).getId();
String title = Arraylist_for_loop.get(h).getTitle();
String place_city = Arraylist_for_loop.get(h)
.getPlace_city();
String age_limit = Arraylist_for_loop.get(h)
.getEvent_agelimit();
String dayOfTheWeek = (String) android.text.format.DateFormat
.format("EEEE", Arraylist_for_loop.get(h)
.getSratdate_time_date());
String DayofWeek = dayOfTheWeek;
if (!(dayOfTheWeek == day_of_header)) {
DayofWeek = day_of_header;
}
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String Today = sdf.format(d);
String Value_of_today = "";
if (Today.contentEquals(DayofWeek)) {
Value_of_today = "Today";
}
items.add(new EventItem(i, Value_of_today, DayofWeek,
"12:00", title, description, place_city, "10",
age_limit));
}
}
MyListAdapter adapter = new MyListAdapter(MainActivity.this, items);
lv.setAdapter(adapter);
lv.setOnItemClickListener(MainActivity.this);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.show();
}
}
private void prepareResource() {
mGroupCollection = new ArrayList<GroupEntity>();
for (int i = 1; i < 3; i++) {
GroupEntity ge = new GroupEntity();
ge.Name = "City " + i;
for (int j = 1; j < 4; j++) {
GroupItemEntity gi = ge.new GroupItemEntity();
gi.Name = "Venu" + j;
ge.GroupItemCollection.add(gi);
}
mGroupCollection.add(ge);
}
}
private void initPage() {
mExpandableListView = (ExpandableListView) findViewById(R.id.expandableListView);
ExpandableListAdapter adapter = new ExpandableListAdapter(this,
mExpandableListView, mGroupCollection);
mExpandableListView.setAdapter(adapter);
mExpandableListView.setOnChildClickListener(this);
}
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
Toast.makeText(getApplicationContext(), childPosition + "Clicked",
Toast.LENGTH_LONG).show();
return true;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
EventParsingClass obj = (EventParsingClass) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), obj.getPlace_city() + "Clicked",Toast.LENGTH_LONG).show();
}
}
How can I proceed in these two scenarios?
EventParsingClass EPSP= ??? and
EPSP.getid= ??
fetch[0]="XXX"
fetch[1]="YYY"
fetch[2]="ZZZ"
lv.setOnItemClickListener(MainActivity.this);
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
Toast.makeText(getApplicationContext(), fetch[position] + "Clicked",
Toast.LENGTH_LONG).show();
}
just declare fetch[position] to get the value of clicked item. hope this will give you some solution.
Use int position to find out values from your data list (array list or what ever you used).
lv.setOnItemClickListener(MainActivity.this);
public void onItemClick(AdapterView<?> parent, View view, int position,long id)
Toast.makeText(getApplicationContext(), EPSP.getid(position) + "Clicked",Toast.LENGTH_LONG).show();
}
EventItem item = (EventItem) parent.getItemAtPosition(position);
Now you have a hold of EventItem. So you can start using the get methods of your EventItem class in order to get whatever you want from it.
I got the solution:
EventParsingClass new_method(int value) {
int item_count = 0;
for (int i = 0; i < arrayOfEventDescription.size(); i++) {
ArrayList<EventParsingClass> Arraylist_for_loop = arrayOfEventDescription
.get(i);
item_count++;
for (int j = 0; j < Arraylist_for_loop.size(); j++) {
if (value == item_count) {
return Arraylist_for_loop.get(j);
}
item_count++;
}
}
return null;
}
And call it from here:
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
EventParsingClass newObject = new_method(arg2);
if (newObject == null) {
} else {
Log.d("Generated Value Id : ", "" + newObject.getId());
Toast.makeText(getApplicationContext(),
"Item Clicked" + arg2 + "-----" + newObject.getTitle(),
Toast.LENGTH_LONG).show();
}
}

Check/Uncheck all the CheckedTextView in a ListView custom adapter

I have such a custom adapter:
adapter = new ArrayAdapter<Item>(this,
R.layout.file_manager, R.id.checkedTextItem,
fileList)
{
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// creates view
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.item, null);
view.setFocusable(false);
CheckedTextView textView = (CheckedTextView) view
.findViewById(R.id.checkedTextItem);
// put the image on the text view
textView.setCompoundDrawablesWithIntrinsicBounds(
fileList[position].icon, 0, 0, 0);
textView.setTextColor(Color.WHITE);
textView.setText(fileList[position].file);
if(fileList[position].file.equalsIgnoreCase("select all") & (fileList[position].check == true))
{
for(int i =0;i<fileList.length;i++)
{
fileList[i].setItemCheck(true);
chosenFile = fileList[i].file;
File sel = new File(path + "/" + chosenFile);
if (sel.isFile())
resFiles.add(sel);
}
resFiles.remove(position);
}
else if(fileList[position].file.equalsIgnoreCase("select all") & (fileList[position].check == false))
{
{
for(int i =0;i<fileList.length;i++)
{
fileList[i].setItemCheck(false);
}
}
}
if(fileList[position].icon == R.drawable.directory_icon)
textView.setCheckMarkDrawable(null);
else if(fileList[position].icon == R.drawable.directory_up)
textView.setCheckMarkDrawable(null);
if(fileList[position].check == true)
textView.setChecked(true);
else
textView.setChecked(false);
// add margin between image and text (support various screen
// densities)
int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
textView.setCompoundDrawablePadding(dp5);
textView.setFocusable(false);
return view;
}
};
I have a class Item, where I created boolean field check:+
public class Item {
public String file;
public int icon;
public boolean check;
public Item(String file, Integer icon, boolean check) {
this.file = file;
this.icon = icon;
this.check = check;
}
public String getItemFile()
{
return file;
}
public int getItemIcon()
{
return icon;
}
public boolean getItemCheck()
{
return check;
}
public void setItemCheck(boolean check)
{
this.check = check;
}
public void setItemFile(String file)
{
this.file = file;
}
public void setItemIcon(int icon)
{
this.icon = icon;
}
public void toggle()
{
check = !check;
}
#Override
public String toString() {
return file + " "+ icon+ " "+ check;
}
}
And my listView setOnItemClickListener where I set the check state of the item, which was clicked with the toggle() method of the Item class
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng)
{
//String selectedFromList = (lv.getItemAtPosition(myItemInt).toString());
myView.setFocusable(false);
chosenFile = fileList[myItemInt].file;
File sel = new File(path + "/" + chosenFile);
Log.i("path",sel.toString());
if (sel.isDirectory()) {
firstLvl = false;
str.add(chosenFile);
fileList = null;
path = new File(sel + "");
loadFileList();
lv.setAdapter(adapter);
}
else if (chosenFile.equalsIgnoreCase("up") && !sel.exists()) {
// present directory removed from list
String s = str.remove(str.size() - 1);
// path modified to exclude present directory
path = new File(path.toString().substring(0,
path.toString().lastIndexOf(s)));
fileList = null;
// if there are no more directories in the list, then
// its the first level
if (str.isEmpty()) {
firstLvl = true;
}
loadFileList();
lv.setAdapter(adapter);
}
else
{
fileList[myItemInt].toggle();
if (fileList[myItemInt].check == true)
resFiles.add(sel);
else
resFiles.remove(sel);
adapter.notifyDataSetChanged();
Log.i(fileList[myItemInt].file,Boolean.toString(fileList[myItemInt].check));
}
}
});
I want to implement ability to check all the CheckedTextView. I try to do it in my getView() method of the adapter. I can check all the items, but problem is in uncheck. Because when I call fileList[i].setItemCheck(false); at the statement when check state of 'select all' item is false I can't check all the items by clicking. How can I implement this in some better way?
I solved it by changing the setOnItemClickListener method. The problem was is that I tried to check all the items in my loadFileList() method, which determines all the checkable state, but I should handle single checking and all checking in different parts of code. Now I do it in else statement of setOnItemClickListener...It looks like this:
else
{
fileList[myItemInt].toggle();
if(fileList[myItemInt].file.equalsIgnoreCase("select all") & (fileList[myItemInt].check == true))
{
String selectAllFile = fileList[myItemInt].file;
File all = new File(path + "/" + selectAllFile);
for(int i =0;i<fileList.length;i++)
{
chosenFile = fileList[i].file;
File select = new File(path + "/" + chosenFile);
fileList[i].setItemCheck(true);
if (select.isFile())
{
resFiles.add(select);
resFiles.remove(all);
}
}
adapter.notifyDataSetChanged();
}
else if(fileList[myItemInt].file.equalsIgnoreCase("select all") & (fileList[myItemInt].check == false))
{
for(int i =0;i<fileList.length;i++)
{
fileList[i].setItemCheck(false);
}
adapter.notifyDataSetChanged();
}
if (fileList[myItemInt].check == true)
{
resFiles.add(sel);
if(fileList[myItemInt].file.equalsIgnoreCase("select all"))
{
String selectAllFile = fileList[myItemInt].file;
File all = new File(path + "/" + selectAllFile);
resFiles.remove(all);
}
}
else
resFiles.remove(sel);
adapter.notifyDataSetChanged();
Log.i(fileList[myItemInt].file,Boolean.toString(fileList[myItemInt].check));
}
}
});

Categories

Resources