Am displaying random checkboxes from remote server and if a user checks a checkbox then am storing that value in sqlite database and on the next loading am checking whether that value is present in database or not and if its present then bydefault it will check the checkbox. my problem is everytime i try to insert a value to sqlite it always takes the first checked checkbox value. But if I use a toast to check my code am getting the respective checkbox value. but that doesn't work with sqlite
Here is how am displaying a checkbox and setting on clicklistener
rl = (LinearLayout) getView().findViewById(R.id.linearmain);
HashMap<String, String> resultp = new HashMap<String, String>();
sqlcon = new SQLController(context);
sqlcon.open();
CheckBox[] cb = new CheckBox[arraylist.size()];
Cursor c = sqlcon.readEntry();
int rows = c.getCount();
int cols = c.getColumnCount();
for(int i = 0; i < arraylist.size(); i++) {
resultp = arraylist.get(i);
cb[i] = new CheckBox(getActivity());
cb[i].setText(resultp.get(Fltrsubfragment.SUB));
cb[i].setId(i);
cb[i].setOnClickListener(handleOnClick(cb[i]));
rl.addView(cb[i]);
for ( int ikv = 0; ikv < rows; ikv++) {
// inner for loop
for (int j = 0; j < cols; j++) {
String iv;
iv=c.getString(j);
if(iv==null){
Toast.makeText(context, " Empty " + rows, Toast.LENGTH_LONG).show();
}
else if(iv.equals(cb[i].getText().toString())){
cb[i].setChecked(true);
Toast.makeText(context, " Checked " + rows, Toast.LENGTH_LONG).show();
}
else{
cb[i].setChecked(false);
}
}
}
View.OnClickListener handleOnClick(final CheckBox button) {
return new View.OnClickListener() {
public void onClick(View v) {
if(button.isChecked()){
if(barraylist.contains(button.getText().toString())){
Toast.makeText(context, " Already added " + button.getText().toString(), Toast.LENGTH_LONG).show();
}
else {
brandarraylist.add(button.getText().toString());
name=button.getText().toString();
new MyAsync().execute();
Toast.makeText(context, " Stored " + button.getText().toString(), Toast.LENGTH_LONG).show();
}
}
else{
if(barraylist.contains(button.getText().toString()))
{
barraylist.remove(button.getText().toString());
name=button.getText().toString();
new MyAsyncS().execute();
sqlcon.deleteTData(button.getText().toString());
Toast.makeText(context, "Removed this " + button.getText().toString(), Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(context, "Unchecked this " + button.getText().toString(), Toast.LENGTH_LONG).show();
}
}
}
};
AsyncTask code to insert value
private class MyAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
PD = new ProgressDialog(context);
PD.setMessage("Loading...");
PD.setCancelable(false);
PD.show();
}
#Override
protected Void doInBackground(Void... params) {
if(name==null){
return null;
}
// inserting data
else{
sqlcon = new SQLController(context);
sqlcon.open();
sqlcon.insertData(name);
sqlcon.close();
// BuildTable();
return null;
}
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
PD.dismiss();
}
}
here is the insertData code
public void insertData(String name) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(MyDbHelper.LT_VAL, name);
database.insert(MyDbHelper.LTE, null, cv);
}
Please suggest where am making the mistake.
Inside new MyAsync().execute(); put name:
I recommend using .trim() on all user input. You could easily chain this to:
name=button.getText().toString().trim();
new MyAsync().execute(name);
Then get it by using:
#Override
protected String doInBackground(String... params) {
String name = params[0];
We ruled out context by changing the code to:
#Override
protected String doInBackground(String ... params) {
String name = params[0];
if(name==null){
return null;
}else{
return name;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
sqlcon = new SQLController(context);
sqlcon.open();
sqlcon.insertData(result);
sqlcon.close();
// BuildTable();
PD.dismiss();
}
Related
I am creating a listview where i get my items from my azure database through an SQL query with a where statement. My code runs but when i try to search something a toast shows at the bottom of my screen with [], Here is my code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.srail, container, false);
search = (Button)rootView.findViewById(R.id.btnSearch);
Esearch = (EditText)rootView.findViewById(R.id.srch);
list = (ListView)rootView.findViewById(R.id.raill);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckLogin checkLogin = new CheckLogin();
checkLogin.execute("");
List<Map<String,String>> MyData = new ArrayList();
String[] fromwhere = { "NAME","PRICE","RANGE","SUPPLIER","SIZE" };
int[] viewswhere = {R.id.Name_txtView , R.id.price_txtView,R.id.Range_txtView,R.id.size_txtView,R.id.supplier_txtView};
ADAhere = new SimpleAdapter(getActivity(), MyData,R.layout.list_products, fromwhere, viewswhere);
list.setAdapter(ADAhere);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String,Object> obj=(HashMap<String,Object>)ADAhere.getItem(position);
String ID=(String)obj.get("A");
Toast.makeText(getActivity(), ID, Toast.LENGTH_SHORT).show();
}
});
}
});
return rootView;
}
public class CheckLogin extends AsyncTask<String, String, String> {
String z = "";
Boolean isSuccess = false;
ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(getActivity(), "Searching...",
"Listview Loading! Please Wait...", true);
}
#Override
protected void onPostExecute(String r) {
progress.dismiss();
Toast.makeText(getActivity(), r, Toast.LENGTH_SHORT).show();
if (isSuccess) {
Toast.makeText(getActivity(), "Search Successfull", Toast.LENGTH_LONG).show();
//finish();
}
}
#Override
protected String doInBackground(String... strings) {
String Search = search.getText().toString();
if (Search.trim().equals(""))
z = "Please Search something";
else {
List<Map<String, String>> data = null;
data = new ArrayList<Map<String, String>>();
try {
ConnectionHelper conStr = new ConnectionHelper();
connect = conStr.connectionclass(); // Connect to database
if (connect == null) {
z = "Check Your Internet Access!";
} else {
// Change below query according to your own database.
String query = "select * from cc_rail where rail_name='" + Search.toString() + "' OR RAIL_UNIT_PRICE= '" + Search.toString() + "' OR RAIL_RANGE= '" + Search.toString() + "' OR RAIL_SUPPLIER='" + Search.toString() + "' OR RAIL_SIZE='" + Search.toString() + "'";
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Map<String, String> datanum = new HashMap<String, String>();
datanum.put("NAME", rs.getString("RAIL_NAME"));
datanum.put("PRICE", rs.getString("RAIL_UNIT_PRICE"));
datanum.put("RANGE", rs.getString("RAIL_RANGE"));
datanum.put("SUPPLIER", rs.getString("RAIL_SUPPLIER"));
datanum.put("SIZE", rs.getString("RAIL_SIZE"));
data.add(datanum);
}
z = " successful";
isSuccess = true;
connect.close();
}
} catch (Exception ex) {
isSuccess = false;
z = ex.getMessage();
}
return String.valueOf(data);
}
return z;
}
}
}
You're using this MyData variable as the data source for you adapter:
List<Map<String,String>> MyData = new ArrayList();
...
ADAhere = new SimpleAdapter(getActivity(), MyData,R.layout.list_products, fromwhere, viewswhere);
...
list.setAdapter(ADAhere);
And yet you're not adding anything neither to the direct data source MyData nor through the adapter ADAhere.
EDIT:
What you can do to fix this is, make your data variable global (move it to before onCreateView():
List<Map<String,String>> MyData = new ArrayList();
Then inside your asynctask you call add to add data to it:
while (rs.next()) {
Map<String, String> datanum = new HashMap<String, String>();
datanum.put("NAME", rs.getString("RAIL_NAME"));
datanum.put("PRICE", rs.getString("RAIL_UNIT_PRICE"));
datanum.put("RANGE", rs.getString("RAIL_RANGE"));
datanum.put("SUPPLIER", rs.getString("RAIL_SUPPLIER"));
datanum.put("SIZE", rs.getString("RAIL_SIZE"));
MyData.add(datanum);
}
ADAhere.notifyDatasetChanged()
Then simply call ADAhere.notifyDatasetChanged() when you're done loading data into MyData.
I have custom alert dailog with list and check i am trying to store selected checkbox in pref,how to store selected item in shared preference,i am able to select values from list?can any one help me with this?
class LoadAlldata extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
ArrayAdapter<String> adapterallstates;
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TestCountry.this);
pDialog.setMessage("Please..");
pDialog.setIndeterminate(true);
// pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(true);
pDialog.show();
}
protected ArrayList<HashMap<String, String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
statedata = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(STATE_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
jsonObj = new JSONArray(jsonStr);
// state_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(STATE_ID, c.getString(STATE_ID));
map.put(STATE_NAME, c.getString(STATE_NAME));
statedata.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return statedata;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
pDialog.dismiss();
final String[] arrallstates = new String[statedata.size()];
checked_state=new boolean[statedata.size()];
for (int index = 0; index < statedata.size(); index++) {
HashMap<String, String> map = statedata.get(index);
arrallstates[index] = map.get(STATE_NAME);
}
txtvw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View w) {
new AlertDialog.Builder(TestCountry.this)
.setTitle("Choose a Days")
.setMultiChoiceItems(arrallstates, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// TODO Auto-generated method stub
//storing the checked state of the items in an array
checked_state[which] = isChecked;
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String display_checked_days = "";
for (int i = 0; i < arrallstates.length; i++) {
if (checked_state[i] == true) {
display_checked_days = display_checked_days + " " + arrallstates[i];
}
}
Toast.makeText(TestCountry.this, "The selected is" + display_checked_days, Toast.LENGTH_SHORT).show();
//clears the array used to store checked state
for (int i = 0; i < checked_state.length; i++) {
if (checked_state[i] == true) {
checked_state[i] = false;
}
}
//used to dismiss the dialog upon user selection.
dialog.dismiss();
}
}).create().show();;
}
});
}
}
First write a method to setSelection mannually in Adapter.
private int selectedItem = -1;
public void setSelectedItem(int position) {
selectedItem = position;
notifyDataSetChanged();
} // Here selectedItem is global variable
In onBindViewHolder add this code :
if (position == selectedItem){
viewHolder.chkSelected.setChecked(stList.get(position));
viewHolder.chkSelected.setTag(stList.get(position));
} else {
viewHolder.chkSelected.setChecked(stList.get(position).isselected());
viewHolder.chkSelected.setTag(stList.get(position));
}
From your Activity you have to call setSelectedItem(position) from your adapter insance. For getting position you have already know the chekbox Id so you can get position of that Id from List.
To get position from List:
private int getSelectedItem(List<String> stList, String name) {
int pos = -1;
for(int i=0; i<stList.size(); i++) {
if(name.equals(stList.get(i)){
pos = i;
break;
}
}
return pos;
}
Try like this:
First make model class with getter setter:
private boolean checked;
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
And in Adapter Class in getview write Code like this.
FilterModelClass model=stList.get(position);
viewHolder.chkbox.setOnCheckedChangeListener(new CheckUpdateListener(model));
Make class like below to handle checkedChangedListener
/*******************
* Checkbox Checked Change Listener
********************/
private final class CheckUpdateListener implements CompoundButton.OnCheckedChangeListener {
private final FilterModelClass model;
private CheckUpdateListener(FilterModelClass model) {
this.model = model;
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.i("onCheckedChanged", "isChecked: " + isChecked);
model.setChecked(isChecked);
notifyDataSetChanged();
}
}
int globalPosition ;
..............
buttonAllData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new UploadBulkData(globalPosition).execute();
}
});
........
class UploadBulkData extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
int dataPosition;
public UploadBulkData(int position){
this.dataPosition = position;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UploadActivity.this);
pDialog.setMessage("Uploading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
.......
String url = "http://web/uploadBulk.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("UserData", st));
String resultServer = getHttpPost(url,params);
Log.d("Entire string::", " " + resultServer);
/*** Default Value ***/
strStatusID = "0";
strError = "";
JSONObject jsonObject;
try {
jsonObject = new JSONObject(resultServer);
strStatusID = jsonObject.getString("StatusID");
strError = jsonObject.getString("Message");
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
fileNameDB=ImageList.get(globalPosition).toString().substring
(strPath.lastIndexOf('/')+1, strPath.length());
if(strStatusID.equals("1"))
{
Toast.makeText(UploadActivity.this, "Data Uploaded Successfully", Toast.LENGTH_SHORT).show();
long saveImge = myDbbv.InsertData(fileNameDB);
Log.d("fileNameDB:UP", String.valueOf(saveImge));
}
else
{
Toast.makeText(UploadActivity.this, "Unable to upload Data", Toast.LENGTH_SHORT).show();
}
if (file_url != null){
Toast.makeText(UploadActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
And in getView i am using something like this:
public View getView(final int position, View convertView, ViewGroup parent) {
holder.dataImageView.setImageResource(R.drawable.bullet_button);
try {
// check data exist or not
boolean strDataExistU = myDbbv.Exists(fileNameDB);
if(strDataExistU)
{
holder.dataImageView.setImageResource(R.drawable.online);
}
else
{
boolean strDataExist = myDb.Exists(fileNameDB);
if(strDataExist)
{
holder.dataImageView.setImageResource(R.drawable.local);
}
else
{
holder.dataImageView.setImageResource(R.drawable.default);
}
}
} catch (Exception e) {
}
}
As you can see in getView(...) method, I am using three different kind of drawables (namely:- online, local, default)
Where online shows data has been uploaded to online server, local shows this has been added to local database and default..(neither uploaded to server nor stored to local database)
Problem:
Whenever I am doing bulk upload, getting online drawable only for the last row item in a list, whereas I have uploaded whole list item data to server
I just want to show online drawable for all the list items, those I have uploaded to server, else my code works just fine...
Almost complete code:
public class UploadActivity extends Activity {
int globalPosition ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
ImageButton buttonAllData = (ImageButton) findViewById(R.id.btnMenus);
buttonAllData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new UploadBulkData(globalPosition).execute();
}
});
/*** Get Images from SDCard ***/
ImageList = getSD();
// ListView and imageAdapter
lstView = (ListView) findViewById(R.id.listView1);
lstView.setAdapter(new ImageAdapter(this));
totalItems = ""+ lstView.getAdapter().getCount();
}
public static List <String> getSD()
{
List <String> it = new ArrayList <String>();
String string = "/mnt/sdcard/Pictures/Joseph/";
f = new File (string+ CameraLauncherActivity.folder+ "/");
files = f.listFiles ();
/***
* to show last taken image on top using lastModified
* to sort data
* to refresh data after (remove or update)
*/
Arrays.sort(files, new Comparator<Object>()
{
public int compare(Object o1, Object o2) {
if (((File)o1).lastModified() > ((File)o2).lastModified()) {
return -1;
} else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
return +1;
} else {
return 0;
}
}
});
// <<<<<<<<< END >>>>>>>>>>>
for (int i = 0; i < files.length; i++)
{
file = files[i];
Log.d("Count",file.getPath());
it.add (file.getPath());
}
return it;
}
static class ViewHolder {
public ViewHolder(View convertView) {
// TODO Auto-generated constructor stub
}
TextView imageNameTextView;
ImageView sdCardImageView, statusImageView, dataImageView;
ProgressBar uploadProgressBar;
ImageButton uploadImageButton, dataImageButton;
boolean isUploading = false;
}
public class ImageAdapter extends BaseAdapter
{
public ImageAdapter(Context c)
{
}
public int getCount() {
// TODO Auto-generated method stub
return ImageList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Avoid unneccessary calls to findViewById() on each row, which is expensive!
holder = null;
// If this item is to be synced
if(flags.get(position)) {
startUpload(position);
// Mark as synced
flags.put(position, false);
}
/*
* If convertView is not null, we can reuse it directly, no inflation required!
* We only inflate a new View when the convertView is null.
*/
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_upload, null);
holder = new ViewHolder(convertView);
// Create a ViewHolder and store references to the children views
holder.imageNameTextView = (TextView) convertView.findViewById(R.id.ColImgName);
holder.sdCardImageView = (ImageView) convertView.findViewById(R.id.ColImgPath);
holder.statusImageView = (ImageView) convertView.findViewById(R.id.ColStatus);
holder.uploadProgressBar = (ProgressBar) convertView.findViewById(R.id.progressBar);
holder.uploadImageButton = (ImageButton) convertView.findViewById(R.id.btnUpload);
holder.dataImageButton = (ImageButton) convertView.findViewById(R.id.btnData);
holder.dataImageView = (ImageView) convertView.findViewById(R.id.dataExist);
// The tag can be any Object, this just happens to be the ViewHolder
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
strPath = ImageList.get(position).toString();
// Get File Name
fileName = strPath.substring( strPath.lastIndexOf('_')+1, strPath.length() );
file = new File(strPath);
#SuppressWarnings("unused")
long length = file.length();
holder.imageNameTextView.setText(fileName);
fileName=ImageList.get(position).toString().substring
(strPath.lastIndexOf('_')+1, strPath.length());
fileNameDB=ImageList.get(position).toString().substring
(strPath.lastIndexOf('/')+1, strPath.length());
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bm = BitmapFactory.decodeFile(strPath,options);
holder.sdCardImageView.setImageBitmap(bm);
if(holder.isUploading) {
holder.uploadProgressBar.setVisibility(View.VISIBLE);
} else {
holder.uploadProgressBar.setVisibility(View.GONE);
}
holder.dataImageView.setImageResource(R.drawable.bullet_button);
try {
// check data exist or not
boolean strDataExistU = myDbbv.Exists(fileNameDB);
if(strDataExistU)
{
holder.dataImageView.setImageResource(R.drawable.online);
}
else
{
// check data exist or not
boolean strDataExist = myDb.Exists(fileNameDB);
if(strDataExist)
{
holder.dataImageView.setImageResource(R.drawable.database);
}
else
{
holder.dataImageView.setImageResource(R.drawable.default);
}
}
} catch (Exception e) {
// TODO: handle exception
}
fileName = ImageList.get(position).toString().substring
(strPath.lastIndexOf('/')+1, strPath.length());
try {
boolean strExist = myDbb.Exists(fileName);
if(strExist)
{
holder.statusImageView.setImageResource(R.drawable.onl);
}
else
{
holder.statusImageView.setImageResource(R.drawable.bullet_button);
}
} catch (Exception e) {
// TODO: handle exception
}
// btnData
holder.dataImageButton.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
// Print
globalPosition = position;
fileName=ImageList.get(position).toString().substring
(strPath.lastIndexOf('_')+1, strPath.length());
fileNameDB=ImageList.get(position).toString().substring
(strPath.lastIndexOf('/')+1, strPath.length());
showDialog(DIALOG_LOGIN);
}
});
return convertView;
}
}
class UploadData extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UploadActivity.this);
pDialog.setMessage("Uploading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
String url = "http://web/uploadData.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sImageName", fileNameDB));
Log.d("sImageName::", fileNameDB);
String resultServer = getHttpPost(url,params);
Log.d("Entire string::", " " + resultServer);
/*** Default Value ***/
strStatusID = "0";
strError = "";
JSONObject c;
try {
c = new JSONObject(resultServer);
strStatusID = c.getString("StatusID");
strError = c.getString("Error");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
try {
fileName=ImageList.get(globalPosition).toString().substring
(strPath.lastIndexOf('_')+1, strPath.length());
fileNameDB=ImageList.get(globalPosition).toString().substring
(strPath.lastIndexOf('/')+1, strPath.length());
// prepare save data
if(strStatusID.equals("0"))
{
Toast.makeText(getApplicationContext(), "Unable to upload Data",
Toast.LENGTH_LONG).show();
}
else if (strStatusID.equals("1"))
{
Toast.makeText(getApplicationContext(), "Data Uploaded Successfully!",
Toast.LENGTH_SHORT).show();
// Save Data
long saveImge = myDbbv.InsertData(fileNameDB);
Log.d("fileNameDB:UP", String.valueOf(saveImge));
} else {
Toast.makeText(getApplicationContext(), "Unable to upload Data",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
// TODO: handle exception
}
if (file_url != null){
Toast.makeText(UploadActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
});
cancelButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
closeButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
}
}
class UploadBulkData extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
int dataPosition;
//constructor to pass position of row, on which button was clicked to class
public UploadBulkData(int position){
this.dataPosition = position;
}
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UploadActivity.this);
pDialog.setMessage("Uploading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
String url = "http://web/uploadBulk.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("EventData", st));
String resultServer = getHttpPost(url,params);
Log.d("Entire string::", " " + resultServer);
/*** Default Value ***/
strStatusID = "0";
strError = "";
JSONObject jsonObject;
try {
jsonObject = new JSONObject(resultServer);
strStatusID = jsonObject.getString("StatusID");
strError = jsonObject.getString("Message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
// Prepare Save Data
if(strStatusID.equals("1"))
{
Toast.makeText(UploadActivity.this, "Data Uploaded Successfully", Toast.LENGTH_SHORT).show();
fileNameDB=ImageList.get(dataPosition).toString().substring
(strPath.lastIndexOf('/')+1, strPath.length());
// Save Data
long saveImge = myDbbv.InsertData(fileNameDB);
Log.d("fileNameDB:UP", String.valueOf(saveImge));
}
else
{
Toast.makeText(UploadActivity.this, "Unable to upload Data", Toast.LENGTH_SHORT).show();
}
if (file_url != null){
Toast.makeText(UploadActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
Issue is in holder.dataImageButton.setOnClickListener method block, position value you are assigning to globalPosition (globalPosition = position;) is the one passed to getView method (getView is called every time view is recycled). So you should set position to holder.dataImageButton tag and retrieve from it inside your setOnClickListener method block.
So set the position in holder.dataImageButton tag
holder.dataImageButton.setTag(position);
after your code line
holder.dataImageView.setImageResource(R.drawable.bullet_button);
and modify your setOnClickListener method as
holder.dataImageButton.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
// Print
globalPosition = (Integer)v.getTag(); //modified
fileName=ImageList.get(position).toString().substring
(strPath.lastIndexOf('_')+1, strPath.length());
fileNameDB=ImageList.get(position).toString().substring
(strPath.lastIndexOf('/')+1, strPath.length());
showDialog(DIALOG_LOGIN);
}
});
It appears that in both UploadData and UploadBulkData the exact same code is used for updating the uploaded database: myDbbv.InsertData(fileNameDB). This would have the effect of only marking the last file of UploadBulkData as being uploaded, which is consistent with the problematic behavior you are seeing.
Try updating myDbbv for each file being uploaded in UploadData and see if it helps.
There could be multiple customizable ways to achieve this. One of them is already answered. Correct me if I'm wrong about your requirement, you need to be notified when the list reached its last item. Afterwards, you're going to perform an operation with the last item index.
[UPDATE]
For this solution: You have to migrate to Recycler View as it's more flexible, fast and optimised for bulk data.
int findFirstVisibleItemPosition();
int findFirstCompletelyVisibleItemPosition();
int findLastVisibleItemPosition(); // This function could be the one you're looking for.
int findLastCompletelyVisibleItemPosition();
Usage:
// In Java
GridLayoutManager layoutManager = ((GridLayoutManager)mRecyclerView.getLayoutManager());
int firstVisiblePosition = layoutManager.findFirstVisibleItemPosition();
Reference: https://stackoverflow.com/a/25053500/16176653
I am creating an application where in i need to have endless scrolling listview. I dnt want to use any library in my application. I have seen some examples on line that help in achieving such listview,but my doubt is how can i have an endless listview when my data are coming from server and are getting parsed in the Asynctask. How can i load 10 items at a time from my asynctask on scroll? I want to know to implement a endless listview on asyntask.
Do i call my asynctask in the onScroll() or not???
public class EndlessScrollExample extends ListActivity {
public JSONArray jsonarray,jsondatearray;
public String url;
public String selectedvalue;
public String TAG = "TAG Event Display";
public String SuggestCity;
public String SuggestState;
public String suggestCountry;
public String event_id,address;
String lat;
String lng;
public String event_name;
public String dateKey;
public String datetime,timenew;
Calendar cal;
public SharedPreferences prefs;
public Editor editor;
public String access_token,id,username;
public static ArrayList<EventsBean> arrayEventsBeans = new ArrayList<EventsBean>();
ArrayList<DateBean> sortArray = new ArrayList<DateBean>();
public SAmpleAdapter adapter;
public ImageView img_menu,img_calender;
public ListView listview;
public EventsBean eventsbean;
int counter = 0;
int currentPage = 0;
FetchEventValues fetchValues;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setTheme(android.R.style.Theme);
setContentView(R.layout.sample_endless);
listview = (ListView)findViewById(android.R.id.list);
try {
// Preferences values fetched from the preference of FBConnection class.
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
access_token = prefs.getString("access_token", null);
id = prefs.getString("uid", null);
username = prefs.getString("username", null);
if(access_token == null && id == null && username == null)
{
Toast.makeText(getApplicationContext(), "FaceBook Login was not successful" +
"/nPlease Relogin.", Toast.LENGTH_SHORT).show();
}
else
{
Log.i(TAG, "VALUES::" + access_token+ " " + id + " " +username);
url = "my Url";
}
} catch (NullPointerException e) {
Log.i(TAG, "User Not Logged IN " + e.getMessage());
// TODO Auto-generated catch block
e.printStackTrace();
}
fetchValues = new FetchEventValues();
fetchValues.execute();
listview = getListView();
listview.setOnScrollListener(new EndlessScrollListener());
}
// AsyncTask Class called in the OnCreate() when the activity is first started.
public class FetchEventValues extends AsyncTask<Integer, Integer, Integer>
{
ProgressDialog progressdialog = new ProgressDialog(EndlessScrollExample.this);
#SuppressLint("SimpleDateFormat")
#SuppressWarnings("unchecked")
#Override
protected Integer doInBackground(Integer... params) {
currentPage++;
// Creating JSON Parser instance
JsonParser jParser = new JsonParser();
// getting JSON string from URL
//arrayEventsBeans.clear();
JSONObject jsonobj = jParser.getJSONFromUrl(url);
Log.i(TAG, "URL VALUES:" + url);
try{
// Code to get the auto complete values Autocomplete Values
JSONArray jsonAarray = jsonobj.getJSONArray(Constants.LOCATIONS);
eventsbean = new EventsBean();
Log.e(TAG, "Location Array Size:" + jsonAarray.length());
for(int j = 0 ; j < jsonAarray.length() ; j++)
{
if(!jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_CITY) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_STATE) && !jsonAarray.getJSONObject(j).isNull(Constants.LOCATION_COUNTRY))
{
JSONObject job = jsonAarray.getJSONObject(j);
if(job.has(Constants.LOCATION_STATE))
{
SuggestCity = job.getString(Constants.LOCATION_CITY);
eventsbean.setLocation_city(job.getString(Constants.LOCATION_CITY));
SuggestState = job.getString(Constants.LOCATION_STATE);
eventsbean.setLocation_state(job.getString(Constants.LOCATION_STATE));
suggestCountry = job.getString(Constants.LOCATION_COUNTRY);
eventsbean.setLocation_country(job.getString(Constants.LOCATION_COUNTRY));
}
}
}
// JSON object to fetch the events in datewise format
JSONObject eventobject = jsonobj.getJSONObject("events");
arrayEventsBeans = new ArrayList<EventsBean>();
// #SuppressWarnings("unchecked")
Iterator<Object> keys = eventobject.keys();
while (keys.hasNext()) {
String datestring = String.valueOf(keys.next());
if (datestring.trim().length() > 0) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter.parse(datestring);
DateBean dateBean = new DateBean(date);
sortArray.add(dateBean);
}
// JSONArray jsonArray = eventobject.getJSONArray(datestring);
//System.out.println(" --"+jsonArray);
}
System.out.println("size:"+sortArray.size());
System.out.println("==========sorting array======");
Collections.sort(sortArray,new CompareDate());
//reverse order
//Collections.reverse(sortArray);
for(DateBean d : sortArray){
dateKey = new SimpleDateFormat("yyyy-MM-dd").format(d.getDate());
System.out.println(dateKey);
Date today = new Date();
Date alldates = d.getDate();
/// Calendar alldates1 = Calendar.getInstance();
JSONArray jsonArray = eventobject.getJSONArray(dateKey);
System.out.println(" --"+jsonArray);
for (int i = 0 ; i < jsonArray.length() ; i++)
{
if ((today.compareTo(alldates) < 0 || (today.compareTo(alldates)== 0)))
// if (alldates1 > cal) alldates.getTime() >= today.getTime()
{
String currentTimeStr = "7:04 PM";
Date userDate = new Date();
String userDateWithoutTime = new SimpleDateFormat("yyyyMMdd").format(userDate);
String currentDateStr = userDateWithoutTime + " " + currentTimeStr;
Date currentDate = new SimpleDateFormat("yyyyMMdd h:mm a").parse(currentDateStr);
if (userDate.compareTo(currentDate) >= 0) {
System.out.println(userDate + " is greater than or equal to " + currentDate);
} else {
System.out.println(userDate + " is less than " + currentDate);
}
JSONObject jsonobjname = jsonArray.getJSONObject(i);
EventsBean eventsbean = new EventsBean();
JSONObject jobjectpicture = jsonobjname.getJSONObject(Constants.PICTURE);
JSONObject jobjeventpicture = jobjectpicture.getJSONObject(Constants.DATA);
eventsbean.setUrl(jobjeventpicture.getString(Constants.URL));
if(jsonobjname.has(Constants.OWNER))
{
JSONObject owner_obj = jsonobjname.getJSONObject(Constants.OWNER);
eventsbean.setOwner_id(owner_obj.getString(Constants.OWNER_ID));
eventsbean.setOwner_name(owner_obj.getString(Constants.OWNER_NAME));
String owner_name = owner_obj.getString(Constants.OWNER_NAME);
Log.i(TAG, "Owner:" + owner_name);
}
if(!jsonobjname.isNull(Constants.COVER))
{
JSONObject objectcover = jsonobjname.getJSONObject(Constants.COVER);
eventsbean.setCover_id(objectcover.getString(Constants.COVER_ID));
eventsbean.setSource(objectcover.getString(Constants.SOURCE));
String cover_url = objectcover.getString(Constants.SOURCE);
Log.i(TAG, "Cover Url:" + cover_url);
eventsbean.setOffset_y(objectcover.getString(Constants.OFFSET_Y));
eventsbean.setOffset_x(objectcover.getString(Constants.OFFSET_X));
}
eventsbean.setName(jsonobjname.getString(Constants.NAME));
eventsbean.setEvent_id(jsonobjname.getString(Constants.EVENT_ID));
eventsbean.setStart_time(jsonobjname.getString(Constants.START_TIME));
eventsbean.setDescription(jsonobjname.getString(Constants.DESCRIPTION));
eventsbean.setLocation(jsonobjname.getString(Constants.LOCATION));
if(!jsonobjname.isNull(Constants.IS_SILHOUETTE))
{
eventsbean.setIs_silhouette(jsonobjname.getString(Constants.IS_SILHOUETTE));
}
eventsbean.setPrivacy(jsonobjname.getString(Constants.PRIVACY));
datetime = jsonobjname.getString(Constants.START_TIME);
if(!jsonobjname.isNull(Constants.VENUE))
{
JSONObject objectvenue = jsonobjname.getJSONObject(Constants.VENUE);
if(objectvenue.has(Constants.VENUE_NAME))
{
eventsbean.setVenue_name(objectvenue.getString(Constants.VENUE_NAME));
event_name = objectvenue.getString(Constants.VENUE_NAME);
Log.i(TAG, "Event Venue Name:" + event_name);
}
else
{
eventsbean.setLatitude(objectvenue.getString(Constants.LATITUDE));
eventsbean.setLongitude(objectvenue.getString(Constants.LONGITUDE));
eventsbean.setCity(objectvenue.getString(Constants.CITY));
eventsbean.setState(objectvenue.getString(Constants.STATE));
eventsbean.setCountry(objectvenue.getString(Constants.COUNTRY));
eventsbean.setVenue_id(objectvenue.getString(Constants.VENUE_ID));
eventsbean.setStreet(objectvenue.getString(Constants.STREET));
address = objectvenue.getString(Constants.STREET);
eventsbean.setZip(objectvenue.getString(Constants.ZIP));
}
}
arrayEventsBeans.add(eventsbean);
Log.i(TAG, "arry list values:" + arrayEventsBeans.size());
}
}
}
}catch(Exception e){
Log.e(TAG , "Exception Occured:" + e.getMessage());
}
return null;
}
class CompareDate implements Comparator<DateBean>{
#Override
public int compare(DateBean d1, DateBean d2) {
return d1.getDate().compareTo(d2.getDate());
}
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Integer result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
if(this.progressdialog.isShowing())
{
this.progressdialog.dismiss();
}
if(adapter == null)
{
adapter = new SAmpleAdapter(EndlessScrollExample.this, 0, arrayEventsBeans);
listview.setAdapter(adapter);
}
else
{
adapter.notifyDataSetChanged();
}
//currentPage++;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
this.progressdialog.setMessage("Loading....");
this.progressdialog.setCanceledOnTouchOutside(false);
this.progressdialog.show();
}
public int setPage(int currentPage) {
return currentPage;
// TODO Auto-generated method stub
}
}
public class EndlessScrollListener implements OnScrollListener {
private int visibleThreshold = 0;
private int currentPage = 0;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (listview.getLastVisiblePosition() >= listview.getCount() - visibleThreshold) {
currentPage++;
fetchValues.setPage(currentPage);
fetchValues.execute();
}
}
}
}
}
Thanks in advance.
ListView already supports OnScrollListener, so you have to override it and check the condition(in onScroll()), whether it is reached to the end of the list or not.If yes, then add a footer(optional) and fire the async task. After reciving the result notify the adapter. You could check solution on this link, it works on the same concept.
here are few examples of what you are looking for:
http://mobile.dzone.com/news/android-tutorial-dynamicaly
https://github.com/johannilsson/android-pulltorefresh
My code is following ...
public class NameListActivity extends Activity implements TextWatcher {
private Button add = null;
private AutoCompleteTextView editAuto = null;
private Button chfrlist = null;
private ImageView im = null;
String access_token = new String();
private ImageView infobtn = null;
private PopupWindow popupWindow;
private View view;
private ProgressDialog pd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_name_list);
access_token = MainService.readToken();
add = (Button) findViewById(R.id.add_button);
editAuto = (AutoCompleteTextView) findViewById(R.id.editAuto);
chfrlist = (Button) findViewById(R.id.chfrlistbutton);
im = (ImageView) findViewById(R.id.helpact);
im.setOnClickListener(new ImageListener());
infobtn = (ImageView) findViewById(R.id.informbtn);
initPopupWindow();
infobtn.setOnClickListener(new infobtnListener());
editAuto.addTextChangedListener(this);
add.setOnClickListener(new addListener());
chfrlist.setOnClickListener(new ChfrListListener());
}
public class addListener implements OnClickListener {
public void onClick(View v) {
addTask task = new addTask();
task.execute();
editAuto.setText("");
}
}
public void afterTextChanged(Editable arg0) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
onTextChangedTask task = new onTextChangedTask();
task.execute();
}
public class onTextChangedTask extends AsyncTask<Void, Void, Void> {
ArrayAdapter<String> adapter = null;
String[] userName = null;
String q = null;
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = null;
ArrayList<String> userNameArrayList = new ArrayList<String>();
Weibo weibo = new Weibo();
#Override
protected void onPreExecute() {
weibo.setToken(access_token);
q = editAuto.getText().toString();
System.out.println("start onTextChanged");
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
if (q.length() != 0) {
System.out.println("q is " + q);
String s1 = "https://api.weibo.com/search/suggestions/users.json";
try {
jsonArray = Weibo.client.get(s1,
new PostParameter[] { new PostParameter("q", q) })
.asJSONArray();
} catch (Throwable e) {
System.out.println("这里有个神马异常呢 。。。" + e);
}
System.out.println("return length is " + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
try {
jsonObject = jsonArray.getJSONObject(i);
String sname = jsonObject.getString("screen_name");
userNameArrayList.add(sname);
} catch (JSONException e) {
e.printStackTrace();
}
}
userName = (String[]) userNameArrayList
.toArray(new String[userNameArrayList.size()]);
adapter = new ArrayAdapter<String>(NameListActivity.this,
android.R.layout.simple_dropdown_item_1line, userName);
}
return null;
}
#Override
protected void onPostExecute(Void v) {
System.out.println("post");
editAuto.setAdapter(adapter);
}
}
void showToast(String s) {
Toast toast = Toast.makeText(getApplicationContext(), s,
Toast.LENGTH_LONG);
toast.show();
}
public class addTask extends AsyncTask<Void, Void, Void> {
String s = null;
boolean flag = false;
User user = null;
Weibo weibo = new Weibo();
String screen_name = null;
protected void onPreExecute() {
Toast tt = Toast.makeText(getApplicationContext(), "正在将用户添加到备份名单",
Toast.LENGTH_LONG);
tt.setGravity(Gravity.CENTER, 0, 0);
tt.show();
weibo.setToken(access_token);
screen_name = editAuto.getText().toString();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
if (screen_name.length() != 0) {
Users um = new Users();
try {
user = new User(Weibo.client.get(
"https://api.weibo.com/users/show.json",
new PostParameter[] { new PostParameter(
"screen_name", screen_name) })
.asJSONObject());
} catch (Throwable e) {
e.printStackTrace();
flag = true;
s = new String("您输入的这个用户好像不存在唉");
}
if (user != null) {
ContentValues values = new ContentValues();
values.put("uid", user.getId());
values.put("user_name", user.getName());
SQLiteDatabase db = null;
try {
db = MainService.getDatabase();
} catch (Exception e) {
System.out.println("db error");
finish();
}
Cursor result = db.query("users", new String[] { "uid",
"user_name" }, "uid=?",
new String[] { user.getId() }, null, null, null);
if (result.getCount() == 0)
db.insert("users", null, values);
} else {
flag = true;
s = new String("网络存在问题,检查一下吧");
}
} else {
flag = true;
s = new String("框里输入点东西才能添加啊");
}
return null;
}
#Override
protected void onPostExecute(Void v) {
if (flag == true) {
System.out.println("要打印的是" + s);
showToast(s);
}
}
}
public class infobtnListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("点击了图片");
ColorDrawable cd = new ColorDrawable(-0000);
popupWindow.setBackgroundDrawable(cd);
// popupWindow.showAsDropDown(v);
popupWindow.showAtLocation(findViewById(R.id.informbtn),
Gravity.LEFT | Gravity.BOTTOM, 0, 100);
}
}
public class ImageListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
// Intent t = new Intent(NameListActivity.this,
// GridLayoutActivity.class);
// startActivity(t);
finish();
}
}
public class ChfrListListener implements OnClickListener {
public void onClick(View v) {
if ((haveInternet() == true)
&& (GridLayoutActivity.hasAccessToken() == true)) {
// TODO Auto-generated method stub
pd = ProgressDialog.show(NameListActivity.this, "",
"正在从服务器上获取数据,可能需要较长时间,请耐心等待 ...");
/* 开启一个新线程,在新线程里执行耗时的方法 */
new Thread(new Runnable() {
public void run() {
Intent t = new Intent(NameListActivity.this,
ChooseFromListActivity.class);
startActivity(t);
finish();
handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler
}
}).start();
} else {
Intent t = new Intent(NameListActivity.this,
WebViewActivity.class);
startActivity(t);
finish();
}
}
}
private void initPopupWindow() {
view = getLayoutInflater().inflate(R.layout.namewindow, null);
popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
// 这里设置显示PopuWindow之后在外面点击是否有效。如果为false的话,那么点击PopuWindow外面并不会关闭PopuWindow。
popupWindow.setOutsideTouchable(true);// 不能在没有焦点的时候使用
}
private boolean haveInternet() {
NetworkInfo info = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
// here is the roaming option you can change it if you want to
// disable internet while roaming, just return false
return true;
}
return true;
}
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {// handler接收到消息后就会执行此方法
pd.dismiss();// 关闭ProgressDialog
}
};
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_name_list, menu);
return true;
}
}
My question is : when I input words in the EditText, nothing happened. But when I press backspace did the AutoCompleteTextView show the suggestion list ... the problem is in the editAuto.setAdapter(adapter);
What is wrong?
make the following changes in your code
1) Instead of
private AutoCompleteTextView editAuto = null; JUST WRITE private AutoCompleteTextView editAuto;
2) Add this line to onCrate()
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, <your array name here>);
and remove this line from onTextChangedTask()
ArrayList<String> userNameArrayList = new ArrayList<String>();
3) Add this line to onCrate()
editAuto.setAdapter(adapter);
I know this is way late but for those who face similar problems here is the solution to show the autoCompleteTextView's drop down whenever you want i.e on button click or onTextChanged. After you set the ArrayAdapter for the autoCompleteTextView just put the following line.
autoCompleteTextView.showDropDown();