Unable to hide button from Listview in Custom Dialog Android - android

In first activity i have button(Named btIndividual) inside listview from that one custom dialog layout opens. In that custom dialog i have one text and edittext field inside listview and one save Button for posting data to server. Now i want that after posting data to server the button named btIndividual in first activity will go invisible.
Custom Adapter for first activity:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ProductChoosed productChoosed = productChoosedAr.get(position);
convertView = View.inflate(SolutionActivity.this, R.layout.custom_solution_row, null);
ImageView categoryImageView = (ImageView) convertView.findViewById(R.id.categoryImageView);
TextView categoryNameTextView = (TextView) convertView.findViewById(R.id.categoryNameTextView);
productsListTextView = (TextView) convertView.findViewById(R.id.productsListTextView);
btIndividual = (Button) convertView.findViewById(R.id.btIndividual);
String catgoryImage = "";
String isTradeProduct = productChoosed.isTradeProduct;
if(isTradeProduct.equals("0")){
btIndividual.setVisibility(View.VISIBLE);
productsListTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showTradDialog(position, productChoosedAr.get(position));
}
});
}else{
btIndividual.setVisibility(View.GONE);
}
btIndividual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showIndividualTradDialog(position,productChoosedAr.get(position));
individual_productChoosedAr.clear();
myList.clear();
idIndividual = "";
mIndCount =1;
checkHideButton = position ;
checkButtonPosition = position;
idIndividual = productChoosedAr.get(position).categoryId;
GetIndividualProducts getIndividualProducts = new GetIndividualProducts();
getIndividualProducts.execute();
showDialog();
Toast toast = Toast.makeText(getApplicationContext(),"Loading...",Toast.LENGTH_LONG);
toast.show();
}
});
Custom Dialog layout :
private void showDialog(){
dialog1 = new Dialog(this);
final Dialog tradDialog = new Dialog(this, android.R.style.Theme_Light_NoTitleBar);
View view = getLayoutInflater().inflate(R.layout.trad_dialog_layout_individual, null);
tradDialog.setCanceledOnTouchOutside(false);
lv = (ListView) view.findViewById(R.id.productsListView);
RelativeLayout saveBtnLayout = (RelativeLayout) view.findViewById(R.id.saveBtnLayout);
// Change MyActivity.this and myListOfItems to your own values
clad = new CustomListAdapterDialog(SolutionActivity.this, individual_productChoosedAr);
lv.setAdapter(clad);
clad.notifyDataSetChanged();
mCount = lv.getChildCount();
saveBtnLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int getChildCount1 = lv.getChildCount();
System.out.print(getChildCount1);
for (int i = 0; i < myList.size(); i++) {
// v = lv.getChildAt(i);
// etPrice = (EditText) v.findViewById(R.id.etPrice);
if(myList.get(i).toString().equals("")){
ProductPrice = "NULL";
}else {
ProductPrice = myList.get(i).toString();
}
// if(ProductPrice.equals("")){
// ProductPrice = "NULL";
// }
productPriceAr.add(ProductPrice);
}
Toast toast = Toast.makeText(getApplicationContext(),"Please wait...",Toast.LENGTH_LONG);
toast.show();
SendIndividualDatatoServer sendIndividualData = new SendIndividualDatatoServer();
sendIndividualData.execute();
}
});
//lv.setOnItemClickListener(........);
dialog1.setContentView(view);
dialog1.show();
}
AsyncTask class for posting data from where i want to disable btIndividual button:
protected void onPostExecute(Void paramVoid) {
super.onPostExecute(paramVoid);
try {
String typeId = "", messageReceived = "";
JSONObject localJSONObject = new JSONObject(this.sendDataResponse);
typeId = localJSONObject.getString("type_id");
messageReceived = localJSONObject.getString("msg");
if (typeId.equals("1")) {
//if i reached here i want to disable that button
// if(checkHideButton == checkButtonPosition){
// btIndividual.setVisibility(View.GONE);
// customSelectedProductsAdapter.notifyDataSetChanged();
// customSelectedProductsAdapter.notifyDataSetInvalidated();
// }
Toast toast = Toast.makeText(SolutionActivity.this,"Individual Data Posted",Toast.LENGTH_LONG);
toast.show();
dialog1.dismiss();
customSelectedProductsAdapter.notifyDataSetChanged();
productPriceAr.clear();
individual_productChoosedAr.clear();
} else
Toast.makeText(SolutionActivity.this, messageReceived, Toast.LENGTH_SHORT).show();
btIndividual.setVisibility(View.VISIBLE);
} catch (Exception localException) {
localException.printStackTrace();
Toast.makeText(SolutionActivity.this, "Network Error Occured", Toast.LENGTH_SHORT).show();
}

I guess the problem is here:
} else
Toast.makeText(SolutionActivity.this, messageReceived, Toast.LENGTH_SHORT).show();
btIndividual.setVisibility(View.VISIBLE);
You set the button visible even if your condition below is true.
I suggest to modify the code something like this:
protected void onPostExecute(Void paramVoid) {
super.onPostExecute(paramVoid);
try {
//1. By default button is visible
btIndividual.setVisibility(View.VISIBLE);
String typeId = "", messageReceived = "";
JSONObject localJSONObject = new JSONObject(this.sendDataResponse);
typeId = localJSONObject.getString("type_id");
messageReceived = localJSONObject.getString("msg");
if (typeId.equals("1")) {
if(checkHideButton == checkButtonPosition){
//2. if condition is true - hide the button
btIndividual.setVisibility(View.GONE);
customSelectedProductsAdapter.notifyDataSetChanged();
customSelectedProductsAdapter.notifyDataSetInvalidated();
}
Toast toast = Toast.makeText(SolutionActivity.this,"Individual Data Posted",Toast.LENGTH_LONG);
toast.show();
dialog1.dismiss();
customSelectedProductsAdapter.notifyDataSetChanged();
productPriceAr.clear();
individual_productChoosedAr.clear();
} else
Toast.makeText(SolutionActivity.this, messageReceived, Toast.LENGTH_SHORT).show();
//3. it is not needed
//btIndividual.setVisibility(View.VISIBLE);
} catch (Exception localException) {
localException.printStackTrace();
Toast.makeText(SolutionActivity.this, "Network Error Occured", Toast.LENGTH_SHORT).show();
}

Related

How to get the view of recyclerview Item Which will be visible on Scrolling

Actually i have 25 data in recylerview on screen opening 13 data are visible on screen and i wanted to get view for every item for 14 item i am able to get view but when my position become 14
View view = recyclerView.getChildAt(i);
i am getting view null
Here is my code in which i wanted to get view of every item when i click on ave button
private class SaveDataTask extends AsyncTask<Void, Void, Boolean> {
final UpdateActivity instance;
String errorMessage;
SaveDataTask(UpdateActivity instance) {
this.instance = instance;
}
#Override
protected void onPreExecute() {
instance.showProgressDialog();
}
#Override
protected Boolean doInBackground(Void... params) {
String getXmlName = "";
String getXmlString = "";
statusSuccessHashMap.clear();
updateActivityStatus.clear();
try {
Logger.d(instance, LOGGER_TAG, "Adding asset to structure");
String tenant = InstallParam.getInstance().getInstallParam(AppConstant.PARAM_APPSERVER_TENANT);
for (int i = 0; i < listViewData.size(); i++) {
View view = recyclerView.getChildAt(i);
isEditted = (CheckBox) view.findViewById(R.id.layout_editablerow);
if(!isEditted.isChecked()){
continue;
}
TextView posEditText = (TextView) view.findViewById(R.id.layout_overview_pos);
EditText descriptionEditText = (EditText) view.findViewById(R.id.layout_overview_desc);
EditText priceEditText = (EditText) view.findViewById(R.id.layout_overview_price);
EditText quantityEditText = (EditText) view.findViewById(R.id.layout_overview_qtyh);
EditText tradeEditText = (EditText) view.findViewById(R.id.layout_overview_trade);
CheckBox completeCheckBox = (CheckBox) view.findViewById(R.id.layout_overview_completed);
rowLayout = (LinearLayout)view.findViewById(R.id.layout_woupdate_row);
errorSign = (TextView)findViewById(R.id.layout_overview_error);
if(completeCheckBox.isChecked()){
completedVal = "true";
}else {
completedVal = "false";
}
if(priceEditText.getText() != null){
priceVal = priceEditText.getText().toString().replaceAll("[\\-\\+\\.\\^:,]","");
int priceDecimal = getNumberOfDecimalPlace(priceEditText.getText().toString());
pricePosVal = String.valueOf(priceDecimal);
}
if(posEditText.getText() != null){
posVal = posEditText.getText().toString();
}
if(quantityEditText.getText() != null){
quantityVal = quantityEditText.getText().toString().replaceAll("[\\-\\+\\.\\^:,]","");;
int quantityDecimal = getNumberOfDecimalPlace(quantityEditText.getText().toString());
quantityPosVal = String.valueOf(quantityDecimal);
}
descriptionVal = descriptionEditText.getText().toString();
tradeVal = tradeEditText.getText().toString();
getXmlName = "xmltemplate/wawebservices/MPCUST87_SyncWOActivities_001.xml";
getXmlString = GenericUtility.readAssetAsString(instance, getXmlName);
getXmlString = getXmlString.replace("$WORKORDER$", AppSession.getSessionUser().getWorkOrderno());
getXmlString = getXmlString.replace("$ACTIVITY$", posVal);
getXmlString = getXmlString.replace("$NOTE$", descriptionVal);
getXmlString = getXmlString.replace("$PRICE$", priceVal);
getXmlString = getXmlString.replace("$PRICEPOS$", pricePosVal);
getXmlString = getXmlString.replace("$QUANTITYHOUR$", quantityVal);
getXmlString = getXmlString.replace("$QUANTITYHOURPOS$", quantityPosVal);
getXmlString = getXmlString.replace("$TRADE$", tradeVal);
getXmlString = getXmlString.replace("$COMPLETE$", completedVal);
getXmlString = GenericUtility.enrichCommonXMLParameters(getXmlString, AppSession.getSessionUser().getUserCode(), tenant);
try{
WebServiceUtil.callSOAPWebService(instance, getXmlString);
runOnUiThread(new Runnable() {
#Override
public void run() {
isEditted.setChecked(false);
}
});
setErrorForNotSavedAct(updateActivityStatus);
}catch (Exception ex){
statusSuccessHashMap.put("Failed",ex.getMessage());
updateActivityStatus.put(posVal,statusSuccessHashMap);
setErrorForNotSavedAct(updateActivityStatus);
}
}
} catch (Exception xe) {
statusSuccessHashMap.put("Failed",xe.getMessage());
updateActivityStatus.put(posVal,statusSuccessHashMap);
Logger.e(instance, LOGGER_TAG, xe.getMessage(), xe);
errorMessage = xe.getMessage();
int strlength=errorMessage.length();
if (strlength == 17)
{
return true;
}else{
return false;
}
} finally {
}
return true;
}
#Override
protected void onPostExecute(final Boolean success) {
instance.hideProgressDialog();
if (success) {
String msg= LabelCache.getInstance().getLabel("msupdateact.save.success", "Activity Updated Succesfully*");
showToast(msg);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(instance);
builder.setTitle(LabelCache.getInstance().getLabel("global.alert.title.error", "Error*"));
builder.setMessage(errorMessage);
builder.setPositiveButton(LabelCache.getInstance().getLabel("global.alert.title.ok", "Ok*"), new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.setCanceledOnTouchOutside(false);
alert.show();
}
}
#Override
protected void onCancelled() {
}
}
here is the Code

My dialog is working online but its not working in offline

I have a list of company and I am opening a dialog for login the particular company. This is working fine online. Now my requirement is to move this app offline as well. And When i am clicking on a particular row of list i am getting crash and throw InflateExeption when app is offline.
This is my dialog method.
public void showDialog(){
dialog = new Dialog(context);
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_login);
dialog.setCancelable(true);
// set the custom dialog components - text, image and button
EditText username = (EditText) dialog.findViewById(R.id.cusername);
EditText password = (EditText) dialog.findViewById(R.id.cpassword);
CheckBox checkBox = (CheckBox) dialog.findViewById(R.id.remember_password);
LinearLayout submit = (LinearLayout) dialog.findViewById(R.id.submit);
LinearLayout close = (LinearLayout) dialog.findViewById(R.id.close);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
dialog.dismiss();
}
});
for (int i = 0; i < appUser.companyLoginArray.size(); i++) {
Map map = appUser.companyLoginArray.get(i);
String position = (String) map.get("position");
if (pos == Integer.parseInt(position)) {
Boolean status = (Boolean) map.get("status");
String uName = (String) map.get("username");
String pass = (String) map.get("password");
if (status) {
checkBox.setChecked(true);
username.setText(uName);
password.setText(pass);
}
}
}
// if button is clicked, close the custom dialog
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(v.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
appUser.boolSetOrAddtoMap=false;
appUser.company_logo=data.get(pos).getAttributes().getLogo();
appUser.company_state=data.get(pos).getAttributes().getState();
LocalRepositories.saveAppUser(context,appUser);
Map mapAdd= new HashMap();
if (!username.getText().toString().equals("")) {
if (!password.getText().toString().equals("")) {
appUser.cusername = username.getText().toString();
appUser.cpassword = password.getText().toString();
LocalRepositories.saveAppUser(context, appUser);
dialog.dismiss();
if (checkBox.isChecked()) {
mapAdd.put("position", String.valueOf(pos));
mapAdd.put("username", username.getText().toString());
mapAdd.put("password", password.getText().toString());
mapAdd.put("status", true);
for (int i=0;i<appUser.companyLoginArray.size();i++){
Map mapGet=appUser.companyLoginArray.get(i);
String str= (String) mapGet.get("position");
Integer integer= Integer.valueOf(str);
if (integer==Integer.valueOf(pos)){
LocalRepositories.saveAppUser(context,appUser);
appUser.companyLoginArray.set(i,mapGet);
LocalRepositories.saveAppUser(context, appUser);
}
}
if (!appUser.boolSetOrAddtoMap){
appUser.companyLoginArray.add(mapAdd);
LocalRepositories.saveAppUser(context, appUser);
}
} else {
for (int i = 0; i < appUser.companyLoginArray.size(); i++) {
Map mapRemove = appUser.companyLoginArray.get(i);
String position = (String) mapRemove.get("position");
if (pos ==Integer.valueOf(position)) {
appUser.companyLoginArray.remove(i);
LocalRepositories.saveAppUser(context, appUser);
}
}
}
EventBus.getDefault().post(new EventOpenCompany(pos));
} else {
Toast.makeText(context, "Enter password", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "Enter username", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}

Android Listview Scroll position

I have a ListView and a list view adapter. The adapter populates the ListView from a List. The list view has a onScrollListener. The problem I have is when on scroll new data are loaded to the view but the scroll bar jumps to the top of the view.
What I want is to keep the scroll position where it was!
Any help?
Thanks
List View class:
private class GetItems extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(AppList.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading more");
mProgressDialog.setMessage("loading);
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
applicationList = new ArrayList();
try
{
GetDataAppList getDataAppList = new GetDataAppList();
JSONArray jsonData = getDataAppList.getJSONData(webfileName, limit, offset);
for (int i = 0; i <= jsonData.length() - 2; i++)
{
JSONObject c = jsonData.getJSONObject(i);
id = c.getString("id");
name = c.getString("name");
logo = c.getString("logo");
developer = c.getString("developer");
rate = c.getInt("rates");
category = c.getInt("category");
fileName = c.getString("filename");
path = c.getString("path");
appSize = c.getDouble("size");
if(category == 1001)
{
String gCat = c.getString("game_category");
applicationList.add(new ApplicationPojo(id,name,logo,developer,appSize,category,fileName,path,gCat));
}
else
{
applicationList.add(new ApplicationPojo(id,name,logo,developer,appSize,category,fileName,path));
}
}
JSONObject sizeObj = jsonData.getJSONObject(jsonData.length() - 1);
size = sizeObj.getInt("size");
}
catch (Exception ex)
{
Log.d("Thread:", ex.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// Locate the ListView in listview.xml
listview = (ListView) findViewById(R.id.listView);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(AppList.this, applicationList,listview);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
// Create an OnScrollListener
listview.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int threshold = 1;
int count = listview.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (listview.getLastVisiblePosition() >= count - threshold) {
if (size >= offset)
{
new LoadMoreDataTask().execute();
offset = offset + 15;
}
else
{
Toast.makeText(getApplicationContext(), "ختم لست!", Toast.LENGTH_LONG).show();
}
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
});
RatingBar bar = (RatingBar) findViewById(R.id.ratingBarShow);
}
}
private class LoadMoreDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(AppList.this);
mProgressDialog.setTitle("Loading more");
mProgressDialog.setMessage("loading);
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
try
{
GetDataAppList getDataAppList = new GetDataAppList();
JSONArray jsonData = getDataAppList.getJSONData(webfileName, limit, offset);
for (int i = 0; i <= jsonData.length(); i++) {
JSONObject c = jsonData.getJSONObject(i);
id = c.getString("id");
name = c.getString("name");
logo = c.getString("logo");
developer = c.getString("developer");
rate = c.getInt("rates");
category = c.getInt("category");
fileName = c.getString("filename");
path = c.getString("path");
appSize = c.getDouble("size");
if(category == 1001)
{
String gCat = c.getString("game_category");
applicationList.add(new ApplicationPojo(id,name,logo,developer,appSize,category,fileName,path,gCat));
}
else
{
applicationList.add(new ApplicationPojo(id,name,logo,developer,appSize,category,fileName,path));
}
}
}
catch (Exception ex)
{
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
int position = listview.getLastVisiblePosition();
adapter = new ListViewAdapter(AppList.this, applicationList,listview);
listview.setAdapter(adapter);
listview.setSelectionFromTop(position, 0);
mProgressDialog.dismiss();
}
}
The Adpater class:
public ListViewAdapter(Activity activity, ArrayList<ApplicationPojo> applicationList, ListView listView)
{
this.activity = activity;
this.applicationList = applicationList;
this.inflater = LayoutInflater.from(activity);
downloader = new ApkFileDownloader(activity);
this.listView = listView;
}
#Override
public int getCount() {
return applicationList.size();
}
#Override
public ApplicationPojo getItem(int position) {
return applicationList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent)
{
if (view == null)
{
holder = new ViewHolder();
view = inflater.inflate(R.layout.singleapp, null);
holder.openInstalledAppBtn = (ImageView) view.findViewById(R.id.openInstalledApp);
holder.downloadBtn = (ImageView) view.findViewById(R.id.updateApp);
holder.progressBar = (ProgressBar)view.findViewById(R.id.updateProgress);
holder.cancelBtn = (ImageView) view.findViewById(R.id.cancel);
holder.appName = (TextView) view.findViewById(R.id.appName);
holder.developer = (TextView) view.findViewById(R.id.developer);
holder.size = (TextView) view.findViewById(R.id.size);
holder.appCat = (TextView) view.findViewById((R.id.appCat));
holder.installBtn = (ImageView) view.findViewById(R.id.install);
holder.catlogo = (ImageView) view.findViewById(R.id.catlogo);
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
}
try
{
final View finalView = view;
holder.logo = (ImageView) finalView.findViewById(R.id.appLogo);
logoName = applicationList.get(position).getLogo();
Picasso.with(activity)
.load(IPClass.SERVERIP + logoName)
.into(holder.logo);
// holder.logo.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View arg0) {
//
// }
// });
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String appid = applicationList.get(position).getId();
int category = applicationList.get(position).getCategory();
Intent rec1Intent = new Intent(activity, AppView.class);
activity.startActivity(rec1Intent);
AppView appView = new AppView();
appView.setParameters(appid, category);
AppList.adapter.notifyDataSetChanged();
}
});
final String id = applicationList.get(position).getId();
final String path = applicationList.get(position).getPath();
final String fileName = applicationList.get(position).getFileName();
final String name = applicationList.get(position).getName();
final String developer = applicationList.get(position).getDeveloper();
final double size = applicationList.get(position).getSize();
final String logo = applicationList.get(position).getLogo();
final int category = applicationList.get(position).getCategory();
final String appName = applicationList.get(position).getFileName();
String checkAppInstalled = appName.substring(0,appName.length() - 4);
//------------CHECK IF APPLICATION IS INSTALLED ----------------------------------------
if(appInstalled(checkAppInstalled))
{
holder.downloadBtn.setVisibility(View.GONE);
holder.cancelBtn.setVisibility(View.GONE);
holder.progressBar.setVisibility(View.GONE);
holder.installBtn.setVisibility(View.GONE);
holder.openInstalledAppBtn.setVisibility(View.VISIBLE);
holder.openInstalledAppBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String fileName = (applicationList.get(position).getFileName());
String appToOpen = fileName.substring(0,fileName.length() - 4);
Context ctx = activity.getApplicationContext();
Intent mIntent = ctx.getPackageManager().getLaunchIntentForPackage(appToOpen);
String mainActivity = mIntent.getComponent().getClassName();
Intent intent = new Intent("android.intent.category.LAUNCHER");
intent.setClassName(appToOpen, mainActivity);
activity.startActivity(intent);
}
});
}
//------------- IF APPLICATION IS NOT ALREADY INSTALLED --------------------------------
else
{
//------------------------ CHECK IF APK EXISTS -------------------------------------
String filePath = Environment.getExternalStorageDirectory().toString();
File file = new File(filePath + "/appsaraai/" + fileName);
if(file.exists())
{
holder.downloadBtn.setVisibility(View.GONE);
holder.cancelBtn.setVisibility(View.GONE);
holder.openInstalledAppBtn.setVisibility(View.GONE);
holder.progressBar.setVisibility(View.GONE);
holder.installBtn.setVisibility(View.VISIBLE);
holder.installBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/appsaraai/" + fileName)), "application/vnd.android.package-archive");
activity.startActivity(intent);
for (int i = 0; i < DownloadLists.list.size(); i++) {
if (DownloadLists.list.get(i).getName().equals(name)) {
DownloadLists.list.remove(i);
}
}
}
});
AppList.adapter.notifyDataSetChanged();
}
//------------------ IF APK DOES NOT EXIST -----------------------------------------
else
{
//-----CHECK IF DOWNLOAD IS IN PROGRESS ----------------------------------------
if (ApkFileDownloader.applicationList.containsKey(name))
{
holder.downloadBtn.setVisibility(View.GONE);
holder.installBtn.setVisibility(View.GONE);
holder.openInstalledAppBtn.setVisibility(View.GONE);
new ApkFileDownloader(activity).getDownloadStatus(holder.progressBar, name, holder.installBtn, holder.cancelBtn);
holder.progressBar.setVisibility(View.VISIBLE);
holder.cancelBtn.setVisibility(View.VISIBLE);
holder.cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downloader.cancelDownload(name);
holder.cancelBtn.setVisibility(View.GONE);
holder.downloadBtn.setVisibility(View.VISIBLE);
DownloadLists dlist = new DownloadLists(activity);
dlist.deleteData(name);
try {
AppList.adapter.notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex);
}
try
{
SearchResult.adapter.notifyDataSetChanged();
}
catch (Exception ex)
{
System.out.println(ex);
}
}
});
}
//-------------- IF DOWNLOAD IS NOT IN PROGRESS START NEW DOWNLOAD -------------
else
{
holder.progressBar.setVisibility(View.GONE);
holder.cancelBtn.setVisibility(View.GONE);
holder.installBtn.setVisibility(View.GONE);
holder.openInstalledAppBtn.setVisibility(View.GONE);
holder.downloadBtn.setVisibility(view.VISIBLE);
holder.downloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
holder.downloadBtn.setVisibility(View.GONE);
holder.cancelBtn.setVisibility(View.VISIBLE);
holder.cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downloader.cancelDownload(name);
holder.cancelBtn.setVisibility(View.GONE);
holder.downloadBtn.setVisibility(View.VISIBLE);
try {
AppList.adapter.notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex);
}
try {
SearchResult.adapter.notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex);
}
}
});
new Thread(new Runnable() {
#Override
public void run() {
try {
Bitmap logoImg = Picasso.with(activity).load(IPClass.SERVERIP + logo).get();
DownloadLists.list.add(new ApplicationPojo(id, name, developer, size, logoImg, holder.progressBar));
DownloadLists dlist = new DownloadLists(activity);
dlist.insertData(id, name, developer, size, fileName, logoImg);
UpdateServerDownload d = new UpdateServerDownload();
d.updateDownloadNo(id, category);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
new ApkFileDownloader(activity).setParameters(path, fileName, name);
try {
AppList.adapter.notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex);
}
try {
SearchResult.adapter.notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex);
}
}
});
}
}
}
holder.appName.setText(applicationList.get(position).getName());
holder.developer.setText(applicationList.get(position).getDeveloper());
String sizeText = " میگابایت ";
String appSize =String.valueOf(applicationList.get(position).getSize()) + sizeText;
holder.size.setText(appSize);
if(category == 1001)
{
String cat = applicationList.get(position).getgCat();
holder.appCat.setText(" " + returnGameCat(cat));
holder.catlogo.setImageResource(R.drawable.gamecatlogo);
}
}
catch (Exception ex)
{
Log.d("Adapter Exception", ex.toString());
}
return view;
}
//--------------- A METHOD TO CHECK IF APPLICATION IS ALREADY INSTALLED ------------------------
public boolean appInstalled(String checkApp)
{
pm = activity.getPackageManager();
try
{
pm.getPackageInfo(checkApp, PackageManager.GET_ACTIVITIES);
isAppInstalled = true;
}
catch (PackageManager.NameNotFoundException e)
{
isAppInstalled = false;
}
return isAppInstalled;
}
You are doing wrong in your GetItems and LoadMoreDataTask AsyncTask. you are setting new adapter each time when you scroll down so when new data are loaded to the view the scroll bar jumps to the top of the view.
You need to call
adapter = new ListViewAdapter(AppList.this, applicationList,listview);
listview.setAdapter(adapter);
only first time then you have to only call
adapter.notifyDataSetChanged()
to update your ListView no need to set adapter each time when making new request and also you have to set OnScrollListener to ListView only one time currently new OnScrollListener is set each time when making new request.
You need to setAdapter first time when adapter is null or you are fetching data first time after it just call notifyDataSetChanged()
Save state of listview before updating and then restore:
// save index and top position
int index = mListView.getFirstVisiblePosition();
View v = mListView.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
// notify dataset changed or re-assign adapter here
// restore the position of listview
mListView.setSelectionFromTop(index, top);
The most Optimal Solution will be
// Save the ListView state (= includes scroll position) as a Parceble
Parcelable state = listView.onSaveInstanceState();
// e.g. set new items
listView.setAdapter(adapter);
// Restore previous state (including selected item index and scroll position)
listView.onRestoreInstanceState(state);
Reference : Retain Scroll Position Android ListView

How to check empty edittext in android [duplicate]

This question already has answers here:
How do I check if my EditText fields are empty? [closed]
(30 answers)
Closed 9 years ago.
My code does not print empty edit text itry trim stirng .length==00 but is not work hat wrong in my code?? how do my code check if edittext is empty before sumbit query
I want to check before submit method if edittext is empty? If is empty then print toast message
public class AgAppTransPayExternalAccount extends Activity {
TextView lblTPEAWelcomeToPayExternalAccountPage;
TextView lblTPEAOtherAccount;
TextView lblTPEAPinno;
TextView lblTPEAAmount;
EditText txtTPEAotheraccount;
EditText txtTPEApinno;
EditText txtTPEAamount;
Button btnTPEAsubmit;
Button clearTPEAButton;
Button btnTPEAgoback;
String sms;
public static ProgressDialog PayExternalAccountProgressDialog = null;
public static boolean value=true;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agapptranspayexternalaccount);
sms=LoginScreen.item.toString();
/*
lblTPEAWelcomeToPayExternalAccountPage = (TextView)
findViewById(R.id.lblTPEAWelcomeToPayExternalAccountPage);
lblTPEAWelcomeToPayExternalAccountPage.setText("Welcome To Pay External
Account Page");
lblTPEAWelcomeToPayExternalAccountPage.setTextColor(getResources().getColor
(R.color.text_color_black));
*/
lblTPEAOtherAccount = (TextView) findViewById(R.id.lblTPEAOtherAccount);
lblTPEAOtherAccount.setText("Other Account :");
txtTPEAotheraccount=(EditText) findViewById(R.id.txtTPEAotheraccount);
lblTPEAPinno = (TextView) findViewById(R.id.lblTPEAPinno);
lblTPEAPinno.setText("PIN Number :");
txtTPEApinno=(EditText) findViewById(R.id.txtTPEApinno);
lblTPEAAmount = (TextView) findViewById(R.id.lblTPEAAmount);
lblTPEAAmount.setText("Amount :");
txtTPEAamount=(EditText) findViewById(R.id.txtTPEAamount);
btnTPEAsubmit=(Button) findViewById(R.id.btnTPEAsubmit);
btnTPEAsubmit.setTextColor(getResources().getColor(R.color.text_color_blue));
clearTPEAButton=(Button) findViewById(R.id.clearTPEAButton);
clearTPEAButton.setTextColor(getResources().getColor(R.color.text_color_blue));
btnTPEAgoback=(Button) findViewById(R.id.btnTPEAgoback);
btnTPEAgoback.setTextColor(getResources().getColor(R.color.text_color_blue));
clearTPEAButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
txtTPEAotheraccount.setText("");
txtTPEApinno.setText("");
txtTPEAamount.setText("");
}
});
btnTPEAgoback.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
finish();
}
});
btnTPEAsubmit.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
String tpeapinemptycheck = txtTPEApinno.getText().toString();
String otheraccountemptycheck =
lblTPEAOtherAccount.getText().toString();
String amountemptycheck = txtTPEAamount.getText().toString();
if (tpeapinemptycheck.trim().equals("")||
(otheraccountemptycheck.trim().equals("")) ||(amountemptycheck.trim().equals("")))
{
Toast.makeText(getApplicationContext(), "Please Enter
Correct Information", Toast.LENGTH_LONG).show();
}
else
showProgress();
submitPEA();
}
});
}
private void submitPEA() {
String message;
String mobilenumber= LoginScreen.smsmobileno;
if (( sms.compareTo("SMS")==0))
{
SmsManager smsmanager = SmsManager.getDefault();
message="AGPEA"+AgAppHelperMethods.varMobileNo+AgAppHelperMethods.
arMobileNo+txtTPEAotheraccount.getText().toString()+AgAppHelperMethods.
varMobileNo+txtTPEApinno.getText().toString()+txtTPEAamount.getText().toString();
smsmanager.sendTextMessage(mobilenumber, null, message, null, null);
}
else
{
Intent j = new Intent(AgAppTransPayExternalAccount.this, AgAppTransPEAResponse.class);
Bundle bundle = new Bundle();
bundle.putString("txtTPEApinno", txtTPEApinno.getText().toString());
bundle.putString("txtTPEAotheraccount",txtTPEAotheraccount.getText().toString());
bundle.putString("txtTPEAamount",txtTPEAamount.getText().toString());
j.putExtras(bundle);
startActivity(j);
value=false;
PayExternalAccountProgressDialog.dismiss();
}
}
private void showProgress()
{
PayExternalAccountProgressDialog =
ProgressDialog.show(AgAppTransPayExternalAccount.this,null, "Processing please
wait...", true);
if (PayExternalAccountProgressDialog != null) {
try
{
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
PayExternalAccountProgressDialog.dismiss();
if(value)
{
Toast.makeText(AgAppTransPayExternalAccount.this, "Request
TimeOut " , Toast.LENGTH_SHORT).show();
}
}
}, 15000); // <--- here is the time adjustment.
}
catch (Exception e)
{
}
}
}
}
Your code is right, only missing this is { } braces in the else condition, try out as following,
if (tpeapinemptycheck.trim().equals("")||
(otheraccountemptycheck.trim().equals("")) ||(amountemptycheck.trim().equals("")))
{
Toast.makeText(getApplicationContext(), "Please Enter
Correct Information", Toast.LENGTH_LONG).show();
}
else
{ // add this
showProgress();
submitPEA();
} // add this
Just because you haven't added those { } braces, your control was going into submitPEA() method.
Try like this
edit_text.getText().toString().trim().equals("");
Create a String variable say x;
Now if et is your EditText field use this:
x = et.getText().toString();
if the EditText field has any text in it it would be passed to the string x.
Now to check if the string x is not null or contains nothing use
if(x.matches(""))
{
//your code here
}
else
{
//the counter action you'll take
}
this way you can check that the entry you are about to enter in the database won't be empty.
Happy coding.

Android Dialog box with remote server login

Here is a little initialization of the AlertDialog in Android and a method to verify a user using HttpClient
private void loginBox() {
USERS = db.getUserData();
login_layout = (LinearLayout) findViewById(R.id.loginlayout);
loginLayout = (LinearLayout) View.inflate(this, R.layout.login, null);
usernameEditText = (EditText) loginLayout.findViewById(R.id.username);
passwordEditText = (EditText) loginLayout.findViewById(R.id.password);
rememmber = (CheckBox) loginLayout.findViewById(R.id.checkBox1);
gallery = (Gallery) loginLayout.findViewById(R.id.users_gallery);
notificationText = (TextView) loginLayout
.findViewById(R.id.notificationtext);
userChooseText = (TextView) loginLayout
.findViewById(R.id.user_choose_text);
breakLine = (View) loginLayout.findViewById(R.id.login_break_line);
registerForContextMenu(loginLayout);
galleryVisibility();
gallery.setAdapter(new AddImgAdp(this));
if (userPrefs.getUserName() == null
&& userPrefs.getUserPassword() == null) {
if (!USERS.isEmpty()) {
System.out.println("not empty");
usernameEditText.setText(
USERS.get(gallery.getSelectedItemPosition())
.getUsername(), TextView.BufferType.EDITABLE);
passwordEditText.setText(
USERS.get(gallery.getSelectedItemPosition())
.getPassword(), TextView.BufferType.EDITABLE);
}
}
gallery.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
selectedUser = USERS.get(arg2).getUsername();
if (!USERS.isEmpty()) {
System.out.println("not empty");
usernameEditText.setText(USERS.get(arg2).getUsername(),
TextView.BufferType.EDITABLE);
passwordEditText.setText(USERS.get(arg2).getPassword(),
TextView.BufferType.EDITABLE);
}
return false;
}
});
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
usernameEditText.setText(USERS.get(position).getUsername(),
TextView.BufferType.EDITABLE);
passwordEditText.setText(USERS.get(position).getPassword(),
TextView.BufferType.EDITABLE);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// rememmber.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v) {
// if (rememmber.isChecked()) {
// Toast toast = Toast.makeText(getApplicationContext(),
// "Try to avoid this option, it is unsecure!",
// Toast.LENGTH_LONG);
// toast.show();
//
// // TODO: store in DB
// }
// }
// });
Button loginButton = (Button) loginLayout
.findViewById(R.id.action_login);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
username = usernameEditText.getText().toString();
password = passwordEditText.getText().toString();
if (rememmber.isChecked()) {
db.createNewUser(username, password);
}
if (testUser()) {
// gallery.removeAllViewsInLayout();
username = usernameEditText.getText().toString();
password = passwordEditText.getText().toString();
userPrefs.savePrefs(username, password);
alert.dismiss();
// alert.cancel();
// login = null;
// alert = null;
} else {
userPrefs.clearPrefs();
System.out.println("Gallery children: "
+ gallery.getChildCount());
notificationText.setText("Username or password incorrect!");
notificationText.setTextColor(Color.RED);
USERS = db.getUserData();
galleryVisibility();
((BaseAdapter) gallery.getAdapter()).notifyDataSetChanged();
gallery.setSelection(gallery.getCount());
}
}
});
if (!initialized) {
System.out.println("Run login box initialization");
initialized = true;
login = new AlertDialog.Builder(this);
login.setView(loginLayout).setTitle("Logon Credentials")
.setCancelable(false);
alert = login.create();
alert.show();
}
}
private void galleryVisibility() {
if (USERS.size() < 1) {
gallery.setEnabled(false);
gallery.setVisibility(LinearLayout.INVISIBLE);
breakLine.setEnabled(false);
breakLine.setVisibility(LinearLayout.INVISIBLE);
userChooseText.setEnabled(false);
userChooseText.setVisibility(LinearLayout.INVISIBLE);
} else {
gallery.setEnabled(true);
gallery.setVisibility(LinearLayout.VISIBLE);
breakLine.setEnabled(true);
breakLine.setVisibility(LinearLayout.VISIBLE);
userChooseText.setEnabled(true);
userChooseText.setVisibility(LinearLayout.VISIBLE);
}
}
private boolean testUser() {
System.out.println("Testing user");
if (usernameEditText.getText().toString()!= null
&& , passwordEditText.getText().toString() != null) {
try {
System.out.println("getting viewwstate");
String viewState = client
.httpGetViewstate("http://website/Login.aspx");
HttpResponse response = client.httpPost1(viewState,
"http://website/Login.aspx",
usernameEditText.getText().toString(), passwordEditText
.getText().toString());
System.out.println("posted!");
HttpEntity entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
System.out.println(responseText);
// String commentsHtml = client
// .httpGet("http://website/PriceTables.aspx");
// System.out.println(commentsHtml);
if (responseText.contains("Log Out")) {
success = true;
System.out.println("username is ok");
this.finish();
return true;
} else {
System.out.println("back again..");
fail = true;
// loginBox();
return false;
}
} catch (SocketTimeoutException socket) {
System.out.println("login socket timeout");
} catch (IOException e) {
System.out.println("Login io exception");
}
return false;
} else {
// Intent login = new Intent(getApplicationContext(),
// Login.class);
// startActivity(login);
fail = true;
// loginBox();
return false;
}
}
The problem is that when I click login button for the first time, everything works fine, but when I click it the second time, the testUserMethod, try{ statement is ignored.. Found the problem - again, my own mistake, everything is ok now. Thank you everybody who helped
Can you check with setCancelable().. you are setting it to true once and again to false...
It looks like problem isn't here. Maybe, you did some field static?

Categories

Resources