How to delete Row entry from Custom ListView? - android

I had created a custom list view. Please tell me how to delete a entry from listview. I don't know where to write a code for delete button in my code. Please help me. Thanks..
Here is ListAdapater.java class:
package com.example.login;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ListAdapater extends ArrayAdapter<String> {
customButtonListener customListner;
public interface customButtonListener {
public void onButtonClickListner(int position, String value);
}
public void setCustomButtonListner(customButtonListener listener) {
this.customListner = listener;
}
private Context context;
private ArrayList<String> data = new ArrayList<String>();
public ListAdapater(Context context, ArrayList<String> dataItem) {
super(context, R.layout.my_custom_list_layout, dataItem);
this.data = dataItem;
this.context = context;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.my_custom_list_layout, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.TextView);
viewHolder.button = (Button) convertView.findViewById(R.id.delete);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final String temp = getItem(position);
viewHolder.text.setText(temp);
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onButtonClickListner(position, temp);
}
}
});
return convertView;
}
public class ViewHolder {
TextView text;
Button button;
}
}
Hompage.java class:
package com.example.login;
import com.example.login.ListAdapater.customButtonListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class Hompage extends Activity implements customButtonListener {
ListView listView;
ListAdapater adapter;
ArrayList<String> dataItems = new ArrayList<String>();
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
db = openOrCreateDatabase("login", MODE_PRIVATE, null);
// My code
String query1 = "SELECT * FROM USERS;";
int c = 0;
try {
Cursor c1 = db.rawQuery(query1, null);
if (c1.moveToFirst()) {
String[] temp2 = new String[c1.getCount()];
do {
String tempo = "Name" + ": " + c1.getString(1) + " " + c1.getString(2) + " \n" + "Gender" + ": "
+ c1.getString(4) + "\n " + "Hobbies" + ": " + c1.getString(8) + " \n" + "User Type" + ": "
+ c1.getString(9);
temp2[c] = tempo;
c++;
// String[] dataArray = temp2;
// List<String> datatemp = Arrays.asList(dataArray);
// dataItems.addAll(datatemp);
} while (c1.moveToNext());
String[] dataArray = temp2;
List<String> datatemp = Arrays.asList(dataArray);
dataItems.addAll(datatemp);
listView = (ListView) findViewById(R.id.listView);
adapter = new ListAdapater(Hompage.this, dataItems);
adapter.setCustomButtonListner(Hompage.this);
listView.setAdapter(adapter);
}
} catch (Exception e) {
}
}
#Override
public void onButtonClickListner(int position, String value) {
//EDITED CODE...
// TODO Auto-generated method stub
String query = "SELECT USER_TYPE FROM USERS WHERE userName = '" + temp + "'";
Cursor c2 = db.rawQuery(query, null);
if (c2.moveToFirst()) {
if (c2.getString(0).equals("Admin")) {
dataItems.remove(position);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_LONG).show();
return;
}
else{
Toast.makeText(getApplicationContext(), "Only Admin can delete", Toast.LENGTH_LONG).show();
}
}
}
}

Try like this
#Override
public void onButtonClickListner(int position, String value) {
// TODO Auto-generated method stub
dataItems.remove(position);
adapter.notifyDataSetChanged();
// call this method
deleteRowFromTable(your_table_name, your_column_name, value)
}
public void deleteRowFromTable(String tableName, String columnName, String keyValue) {
String whereClause = columnName + "=?";
String[] whereArgs = new String[]{String.valueOf(keyValue)};
yourDatabase.delete(tableName, whereClause, whereArgs);
}

Related

recyclerview items get changed when i scroll recyclerview

multiple items get selected automatically when i select one item in recyclerview
What i m doing is
i just want to fetch contacts with no duplication and list all contacts in recyclerview And make visible two textviews (one is for number and second is for name)Its Done But The problem is
when i click on an item it gets clicked 4 times (for example if i click on an item it make visible two textviews but the same item with same name and number get visible like with i have clicked 4 items and see pics )
adpter class
package "";
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.altu.calllocker.R;
import com.example.altu.calllocker.model.ContactsModel;
import java.util.HashMap;
import java.util.List;
public class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.ContactsViewHolder> {
List<ContactsModel> list;
Context context;
public static HashMap<String, String> hashMapBlock;
public ContactsAdapter(List<ContactsModel> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public ContactsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.contacts_item, parent, false);
context = parent.getContext();
hashMapBlock = new HashMap<>();
ContactsViewHolder viewHolder = new ContactsViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ContactsViewHolder holder, final int position) {
holder.txtno.setText(list.get(position).get_id());
holder.txt_contactname.setText(list.get(position).getDisplay_name());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("position", list.get(position).get_id() + " " + list.get(position).getData1() + " " + list.get(position).getDisplay_name());
if (holder.linearLayout.getVisibility() == View.VISIBLE) {
holder.linearLayout.setVisibility(View.GONE);
} else {
holder.linearLayout.setVisibility(View.VISIBLE);
holder.txt_contactName.setText(list.get(position).getDisplay_name());
holder.txt_contact_no.setText(list.get(position).getData1());
}
}
});
holder.switchBlock.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
hashMapBlock.put(list.get(position).getData1(), "block");
Log.e("block", list.get(position).getData1());
Toast.makeText(context, "block" + " " + list.get(position).getData1(), Toast.LENGTH_SHORT).show();
} else {
hashMapBlock.remove(list.get(position).getData1());
Log.e("unblock", list.get(position).getData1());
Toast.makeText(context, "unblock" + " " + list.get(position).getData1(), Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class ContactsViewHolder extends RecyclerView.ViewHolder {
TextView txt_contactname;
TextView txt_contactName;
TextView txt_contact_no;
LinearLayout linearLayout;
SwitchCompat switchBlock;
TextView txtno;
public ContactsViewHolder(View itemView) {
super(itemView);
this.txtno = (TextView) itemView.findViewById(R.id.txtno);
this.txt_contactname = (TextView) itemView.findViewById(R.id.txt_contactName);
this.txt_contactName = (TextView) itemView.findViewById(R.id.txt_contact_name);
this.txt_contact_no = (TextView) itemView.findViewById(R.id.txt_contact_no);
this.linearLayout = (LinearLayout) itemView.findViewById(R.id.linearlayout);
this.switchBlock = (SwitchCompat) itemView.findViewById(R.id.switchButton_block);
}
}
}
MainActivity where i get all contacts to recyclerview
package "";
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;
import com.example.altu.calllocker.R;
import com.example.altu.calllocker.adapter.ContactsAdapter;
import com.example.altu.calllocker.customclass.SimpleDividerItemDecoration;
import com.example.altu.calllocker.model.ContactsModel;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerview_contacts;
List<ContactsModel> contactVOList;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindview();
new Thread(new Task()).start();
progressDialog.dismiss();
//adapter = new ContactsAdapter(contactlist, getApplicationContext());
//recyclerview_contacts.setAdapter(adapter);
}
public void bindview() {
recyclerview_contacts = (RecyclerView) findViewById(R.id.recyclerview_contacts);
contactVOList = new ArrayList<>();
recyclerview_contacts.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(MainActivity.this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerview_contacts.setLayoutManager(llm);
SimpleDividerItemDecoration itemDecoration = new SimpleDividerItemDecoration(this);
recyclerview_contacts.addItemDecoration(itemDecoration);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading.....");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.show();
}
class Task implements Runnable {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
getAllContact();
}
});
}
}
private void getAllContact() {
if (contactVOList.size() > 0) {
contactVOList.clear();
}
// List<ContactsModel> contactVOList = new ArrayList();
ContactsModel contactVO;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contactVO = new ContactsModel();
contactVO.setDisplay_name(name);
contactVO.set_id(id);
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id},
null);
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactVO.setData1(phoneNumber);
}
phoneCursor.close();
Cursor emailCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCursor.moveToNext()) {
String emailId = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
}
emailCursor.close();
contactVOList.add(contactVO);
}
}
ContactsAdapter contactAdapter = new ContactsAdapter(contactVOList, getApplicationContext());
//recyclerview_contacts.setLayoutManager(new LinearLayoutManager(this));
recyclerview_contacts.setAdapter(contactAdapter);
contactAdapter.notifyDataSetChanged();
Log.e("size", String.valueOf(contactVOList.size()));
}
}
}
image 1 image2 with auto selection
You should set OnclickListener inside ViewHolder and get clicked Item's posision with getLayoutPosition() method.
public class ContactsViewHolder extends RecyclerView.ViewHolder {
TextView txt_contactname;
TextView txt_contactName;
TextView txt_contact_no;
LinearLayout linearLayout;
SwitchCompat switchBlock;
TextView txtno;
public ContactsViewHolder(View itemView) {
super(itemView);
this.txtno = (TextView) itemView.findViewById(R.id.txtno);
this.txt_contactname = (TextView) itemView.findViewById(R.id.txt_contactName);
this.txt_contactName = (TextView) itemView.findViewById(R.id.txt_contact_name);
this.txt_contact_no = (TextView) itemView.findViewById(R.id.txt_contact_no);
this.linearLayout = (LinearLayout) itemView.findViewById(R.id.linearlayout);
this.switchBlock = (SwitchCompat) itemView.findViewById(R.id.switchButton_block);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position =getLayoutPosition();
//Your logic
}
});
}
}

NotifyDataSetChanged on gridview not working - Android

I am working with GridView. I want to update GridView on some basis. But notifyDataSetChanged() method is not working.
I am selecting tables on basis of section name. When I select section name very first time than I got tables of that section. But when I go to sections fragment again and select diff. section than I get previously selected tables only. That means notifyDataSetChanged() is not working.
What I have tried is like below.
TableScreenActivity.java
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import com.malaka.R;
import com.malaka.db.DBAdapter;
import com.malaka.helper.ActionItem;
import com.malaka.helper.AssignGetterSetter;
import com.malaka.helper.Attributes;
import com.malaka.helper.CategoryAdapter;
import com.malaka.helper.DialogAdapter;
import com.malaka.helper.JoinTableAdapter;
import com.malaka.helper.ListSwipeDetector;
import com.malaka.helper.Logout;
import com.malaka.helper.PopupWindows;
import com.malaka.helper.QuickAction;
import com.malaka.helper.QuickActionLocation;
import com.malaka.helper.ReplaceFragment;
import com.malaka.helper.async.AddNewCustomerAsync;
import com.malaka.helper.async.CustomerPhotoAsync;
import com.malaka.helper.async.GetValetNoAsync;
import com.malaka.helper.async.ReAssignTableAsync;
import com.malaka.helper.async.SetTableStatusAsync;
import com.malaka.helper.async.TableStatusAsync;
import com.malaka.helper.async.UnAttendedAsync;
import com.malaka.helper.async.ValetAsync;
import com.malaka.utils.CommanUtils;
import com.malaka.utils.PreferenceUtils;
public class TableScreenActivity extends Fragment {
final static String TAG = "TableScreenActivity";
Button btnBarCode, btnFeedBack, btnLogOut;
GridView gridView;
private TextView mDropdownTitle;
static DBAdapter dbAdapter;
TextView malaka, version;
ImageView refresh;
Animation rotation;
boolean isOpen = false;
RelativeLayout rl;
public static FragmentActivity activity;
LinearLayout mDropdownFoldOutNewCust;
TextView dropDownTextViewNewCust, alt0NewCust, alt1NewCust,
mDropdownTitleNewCust;
LinearLayout ll;
static Dialog dialogAddCust, joinDialog;
ListSwipeDetector detector;
static PreferenceUtils pref;
ArrayList<String> tableName, tableId, sectionId, tableDescriptionId,
tableDescription, custName, custId, custNo, parentId, isManager,
parentName;
ArrayList<String> isVale, isInquired;
ArrayList<Integer> tableColors;
Bundle bundle;
String name = "", no = "", custType = "", tableIds, tableDesc;
static String tableDescId;
static EditText edtName, edtNo;
int pos;
QuickAction quickAction;
QuickActionLocation quickActionLocation;
private static final int ID_TABLE = 1;
private static final int ID_TASK = 2;
private static final int ID_MANAGER = 3;
private static final int ID_RECIPE = 4;
private static final int ID_INSTRUCTION = 5;
private static final int ID_SEARCH = 6;
private static final int ID_HELP = 7;
private static final int ID_SETTING = 8;
private static final int ID_LOGOUT = 9;
private static final int ID_SECTIONS = 11;
private static final int ID_KP = 10;
private static final int ID_BANER = 20;
private static final int ID_CITY = 30;
static ArrayList<String> o_name, o_id, e_id, mTableIdList;
private CategoryAdapter categoryAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
System.out.println("TestTag: savedInstanceState " + savedInstanceState
+ " container: " + container);
System.out.println("TestTag: o_name " + o_name + " mTableIdList: "
+ mTableIdList);
View view = inflater.inflate(R.layout.table_screen, container, false);
init(view);
return view;
}
private void init(View view) {
System.out.println("TestTag: Time1: " + System.currentTimeMillis());
// getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
activity = getActivity();
o_id = new ArrayList<String>();
o_name = new ArrayList<String>();
e_id = new ArrayList<String>();
mTableIdList = new ArrayList<String>();
TextView textView = (TextView) view.findViewById(R.id.txt_table_status);
textView.setVisibility(View.GONE);
refresh = (ImageView) view.findViewById(R.id.img_refresh_table);
rotation = AnimationUtils.loadAnimation(getActivity(),
R.anim.refresh_dialog);
pref = new PreferenceUtils(getActivity());
version = (TextView) view.findViewById(R.id.table_version);
version.setText(pref.getVersion());
if (!pref.getTableStatus()) {
TableStatusAsync Async = new TableStatusAsync(getActivity());
HashMap<String, String> map = new HashMap<String, String>();
Log.e(TAG,
"user id : " + pref.getUserId() + "location : "
+ pref.getLocation() + "SectionId: "
+ pref.getSectionId());
map.put("UserId", pref.getUserId());
map.put("SectionId", pref.getSectionId());
map.put("Location", pref.getLocation());
Async.execute(map);
}
dbAdapter = new DBAdapter(getActivity());
dbAdapter.open();
tableId = dbAdapter.getTableId();
tableName = dbAdapter.getTableName();
sectionId = dbAdapter.getTableSectionId();
tableDescriptionId = dbAdapter.getTableDescriptionId();
tableDescription = dbAdapter.getTableDescription();
custName = dbAdapter.getTableCustName();
custId = dbAdapter.getTableCustID();
custNo = dbAdapter.getTableCustNo();
parentId = dbAdapter.getTableParentId();
parentName = dbAdapter.getTableParentName();
isVale = dbAdapter.getTableIsValeStatus();
isManager = dbAdapter.getTableIsManagerStatus();
isInquired = dbAdapter.getTableIsInquiredStatus();
dbAdapter.close();
Log.d(TAG, "Table length ==" + tableId.size());
tableColors = new ArrayList<Integer>();
for (int i = 0; i < tableDescriptionId.size(); i++) {
tableColors.add(Attributes.getColors(tableDescriptionId.get(i),
getActivity()));
}
ll = (LinearLayout) view.findViewById(R.id.table_ll);
rl = (RelativeLayout) view.findViewById(R.id.ll);
if (pref.getUserRole()) {
rl.setVisibility(View.VISIBLE);
} else {
rl.setVisibility(View.GONE);
}
rl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
quickActionLocation.show(arg0);
}
});
detector = new ListSwipeDetector();
malaka = (TextView) view.findViewById(R.id.txt_malaka_title_table);
malaka.setText(pref.getLocation());
gridView = (GridView) view.findViewById(R.id.gridView_table);
if (tableId.size() <= 0) {
gridView.setVisibility(View.GONE);
textView.setVisibility(View.VISIBLE);
} else {
gridView.setVisibility(View.VISIBLE);
textView.setVisibility(View.GONE);
}
dbAdapter = new DBAdapter(getActivity());
// CategoryAdapter categoryAdapter = new CategoryAdapter(getActivity(),
// 0,
// tableName, tableColors, isInquired, custName,
// tableDescriptionId, parentId, parentName, isManager);
// gridView.setAdapter(categoryAdapter);
// categoryAdapter.notifyDataSetChanged();
//tableName.clear();
//tableName = dbAdapter.getTableName();
categoryAdapter = new CategoryAdapter(getActivity(), 0, tableName,
tableColors, isInquired, custName, tableDescriptionId,
parentId, parentName, isManager);
gridView.setAdapter(categoryAdapter);
categoryAdapter.notifyDataSetChanged();
mDropdownTitle = ((TextView) view
.findViewById(R.id.dropdown_textview_table));
mDropdownTitle.setText(pref.getUserNameToGetManagerPage()
.substring(0, 1).toUpperCase()
+ pref.getUserNameToGetManagerPage().substring(1).toLowerCase()
+ " ");
final TextView dropDownTextView = (TextView) view
.findViewById(R.id.dropdown_textview_table);
dropDownTextView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (PopupWindows.mWindow.isShowing()) {
closeDropdown();
} else {
openDropdown();
}
quickAction.show(v);
}
});
gridView.setOnTouchListener(detector);
gridView.setOnItemLongClickListener(new OnItemLongClickListener() {
....
....
}
gridView.setOnItemClickListener(new OnItemClickListener() {
....
....
}
}// init() method closes
#Override
public void onAttach(Activity activity) {
Log.d(TAG, "TestTag::: onAttach()");
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "TestTag::: onCreate() savedInstanceState: "
+ savedInstanceState);
super.onCreate(savedInstanceState);
}
#Override
public void onStart() {
Log.d(TAG, "TestTag::: onStart()");
super.onStart();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.d(TAG, "TestTag::: onActivityCreated(): savedInstanceState "
+ savedInstanceState);
super.onActivityCreated(savedInstanceState);
}
#Override
public void onResume() {
Log.d(TAG, "TestTag::: onResume()");
super.onResume();
}
#Override
public void onPause() {
Log.d(TAG, "TestTag::: onPause()");
super.onPause();
}
#Override
public void onDestroyView() {
Log.d(TAG, "TestTag::: onDestroyView()");
super.onDestroyView();
}
#Override
public void onDestroy() {
Log.d(TAG, "TestTag::: onDestroy()");
super.onDestroy();
}
#Override
public void onStop() {
Log.d(TAG, "TestTag::: onStop()");
super.onStop();
}
#Override
public void onDetach() {
Log.d(TAG, "TestTag::: onDetach()");
super.onDetach();
}
}
Please, Help. I got stuck in. Thanks advance.
EDIT
TableStatusAsync.java
package com.malaka.helper.async;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.malaka.helper.AsyncAttributes;
import com.malaka.helper.ReplaceFragment;
import com.malaka.helper.TableStatusXmlParser;
import com.malaka.ui.TableScreenActivity;
import com.malaka.utils.CommanUtils;
import com.malaka.utils.NetworkUtils;
import com.malaka.utils.PreferenceUtils;
public class TableStatusAsync extends
AsyncTask<Map<String, String>, Void, Void> {
final static String TAG = "TableStatusAsync";
FragmentActivity context;
String xml;
PreferenceUtils pref;
int response;
boolean isConnected;
public TableStatusAsync(FragmentActivity context) {
this.context = context;
pref = new PreferenceUtils(context);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
CommanUtils.getDialogShow(context, "Please Wait...");
}
#Override
protected Void doInBackground(Map<String, String>... params) {
if (NetworkUtils.isConnectedToInternet(context)) {
isConnected = true;
HashMap<String, String> map = (HashMap<String, String>) params[0];
SoapObject request = new SoapObject(
AsyncAttributes.TableStatusNAMESPACE,
AsyncAttributes.TableStatusMETHOD_NAME);
Iterator<String> iterator = map.keySet().iterator();
// PropertyInfo pi1 = new PropertyInfo();
// pi1.setName("UserId");
// pi1.setValue(map.get("UserId"));
// pi1.setType(String.class);
//
// PropertyInfo pi2 = new PropertyInfo();
// pi2.setName("SectionId");
// pi2.setValue(map.get("SectionId"));
// pi2.setType(String.class);
//
// PropertyInfo pi3 = new PropertyInfo();
// pi3.setName("Location");
// pi3.setValue(map.get("Location"));
// pi3.setType(String.class);
//
// request.addProperty(pi1);
// request.addProperty(pi2);
// request.addProperty(pi3);
Log.e(TAG,
"user id : " + map.get("UserId") + "\nsection id : "
+ map.get("SectionId") + "\nlocation : "
+ map.get("Location"));
while (iterator.hasNext()) {
String key = iterator.next();
request.addProperty(key, map.get(key));
Log.d(TAG, "user id key: " + key + " value: " + map.get(key));
}
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
AsyncAttributes.TableStatusURL);
try {
androidHttpTransport.call(
AsyncAttributes.TableStatusSOAP_ACTION, envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
if (result
.toString()
.equals("GetTableStatusResponse{GetTableStatusResult=No Table available; }")) {
String xmltemp = String.valueOf(result).split("=")[1];
xml = xmltemp.split(";")[0];
} else {
String xmltemp = "<NewDataSet>\n"
+ String.valueOf(result).split("<NewDataSet>")[1];
xml = xmltemp.split("</NewDataSet>")[0] + "</NewDataSet>";
}
} catch (Exception e) {
e.printStackTrace();
}
if (xml == null) {
response = 1;
Log.d(TAG, "xml null");
} else if (xml.equals("No Table available")) {
response = 2;
} else {
response = 2;
Log.d(TAG, "Task 1 result " + xml);
TableStatusXmlParser.getTableStatusXmlParseData(xml, context);
}
} else {
isConnected = false;
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
CommanUtils.getDialogDismiss();
if (!isConnected) {
CommanUtils.showAlertDialog("Internet Is Required", context);
} else if (response == 1) {
CommanUtils.getToast("Server Error", context);
}
if (response == 2) {
pref.setTableStatus(true);
ReplaceFragment.getReplaceFragment(context,
new TableScreenActivity(), "");
}
}
}
EDIT - 2
CategoryAdapter.java
package com.malaka.helper;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.malaka.R;
import com.malaka.utils.PreferenceUtils;
public class CategoryAdapter extends ArrayAdapter<String> {
ArrayList<String> table, custName, isInquired, isManager, sectionId,
parentId, parentname;
ArrayList<Integer> tableColors;
FragmentActivity context;
ArrayList<Boolean> status;
View view;
PreferenceUtils pref;
int posision;
final static String TAG = "CategoryAdapter";
public CategoryAdapter(FragmentActivity context, int textViewResourceId,
List<String> objects, List<Integer> colors,
List<String> isInquired, List<String> custName,
List<String> sectionId, List<String> parentId,
List<String> parentname, List<String> ismanager) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
table = (ArrayList<String>) objects;
this.parentId = (ArrayList<String>) parentId;
this.parentname = (ArrayList<String>) parentname;
pref = new PreferenceUtils(context);
this.custName = (ArrayList<String>) custName;
tableColors = (ArrayList<Integer>) colors;
this.isManager = (ArrayList<String>) ismanager;
this.isInquired = (ArrayList<String>) isInquired;
this.sectionId = (ArrayList<String>) sectionId;
status = new ArrayList<Boolean>();
Log.i(TAG, "\nisInquired == " + isInquired);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
view = convertView;
ViewHolder holder = new ViewHolder();
if (convertView == null) {
Display display = context.getWindowManager().getDefaultDisplay();
int height = display.getHeight() / 8;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.table_screen_row, null);
holder.textView = (TextView) convertView
.findViewById(R.id.txt_category_seat);
holder.txtName = (TextView) convertView
.findViewById(R.id.txt_customer_name);
holder.imageViewManager = (ImageView) convertView
.findViewById(R.id.imageView_table_manager);
holder.textViewValet = (TextView) convertView
.findViewById(R.id.text_table_valley);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, height);
holder.rl = (RelativeLayout) convertView
.findViewById(R.id.category_seat);
holder.rl.setLayoutParams(params);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// if(isVale.get(position).equals("0")){
// holder.textViewValet.setText("");
// }else{
// if(parentId.get(position).equals("0")){
// holder.textViewValet.setText(isVale.get(position));
// }
// }
Log.d(TAG, "custName == " + custName.get(position) + "\nlength == "
+ custName.get(position).length());
if (custName.get(position).length() > 9) {
if (parentId.get(position).equals("0")) {
holder.txtName.setText(custName.get(position).substring(0, 8)
+ "...");
holder.textView.setText(table.get(position));
} else {
// we have to use parent table Name when Parent id is not 0
holder.txtName.setText(parentname.get(position));
holder.textView.setText("");
}
} else {
if (parentId.get(position).equals("0")) {
holder.txtName.setText(custName.get(position));
holder.textView.setText(table.get(position));
} else {
holder.txtName.setText(parentname.get(position));
holder.textView.setText("");
}
}
if (isManager.get(position).equals("true")) {
holder.imageViewManager
.setBackgroundResource(R.drawable.manager_icon);
} else {
holder.imageViewManager.setBackgroundResource(0);
}
holder.rl.setBackgroundColor(tableColors.get(position));
return convertView;
}
private class ViewHolder {
TextView textView, txtName;
ImageView imageViewManager;
TextView textViewValet;
RelativeLayout rl;
}
}
At last I got the solution.
I have done like below...
I was maintaining a FLAG called getTableStatus to get the tables of particular section. If the value of getTableStatus is FALSE than only TableStatusAsync is called. At first selection of section, tables are coming from web service and those tables are being inserted in DB.
On second time, selecting of SECTION, tables are coming from DB not from web service. And tables are coming from DB are of previously selected SECTION. So, there is nothing to do with notifyDataSetChanged().
I have just change the FLAG value to FALSE by calling pref.setTableStatus(false); on selection of SECTION. Now, TableStatusAsync is called every time when you change your selection of SECTION.
Modified Code...
TableScreenSectionwiseActivity.java
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
pref.setSectionId(view.getTag().toString());
pref.setTableStatus(false);
pref.setTableServiceStatus(false);
Fragment fragment = new TableScreenActivity();
ReplaceFragment.getReplaceFragment(getActivity(), fragment, "");
}

Setting OnClickListener on items inside of ListView Item in Custom Adapter

I have created a custom Adapter for list which different items and each item has a button to invite. The item should flip horizontally when the respective invite button is clicked and that is working fine. The problem is that when I click invite button of first item then invite button of 4th item is also clicked. I am attaching the code hee
package rovoltlabs.coffeechat.adapters;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import rovoltlabs.coffeechat.R;
import rovoltlabs.coffeechat.animation.AnimationFactory;
import rovoltlabs.coffeechat.animation.AnimationFactory.FlipDirection;
import rovoltlabs.coffeechat.volley.utils.Const;
import rovoltslabs.coffeechat.app.AppController;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewAnimator;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.StringRequest;
public class MyCustomAdapter extends BaseAdapter implements OnClickListener {
Context contexts;
List<String> name = new ArrayList<String>();
List<String> ids = new ArrayList<String>();
List<String> slots = new ArrayList<String>();
List<String> heading = new ArrayList<String>();
List<String> showtime = new ArrayList<String>();
List<Bitmap> img = new ArrayList<Bitmap>();
List<ViewHolder> myview = new ArrayList<ViewHolder>();
private String tag_json_obj = "jobj_req";
private LayoutInflater mLayoutInflater;
View row;
ViewHolder holder;
public MyCustomAdapter(Context context, List<String> name,
List<Bitmap> img, List<String> heading, List<String> slots,
List<String> id) {
super();
this.contexts = context;
this.name = name;
this.img = img;
this.heading = heading;
this.slots = slots;
this.ids = id;
mLayoutInflater = ((Activity) contexts).getLayoutInflater();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
// check to see if the reused view is null or not, if is not null then
// reuse it
if (view == null) {
holder = new ViewHolder();
view = mLayoutInflater.inflate(R.layout.item, null);
holder.name = (TextView) view.findViewById(R.id.Name);
holder.fname = (TextView) view.findViewById(R.id.flipName);
holder.msg = (EditText) view.findViewById(R.id.fsend);
holder.heading = (TextView) view.findViewById(R.id.ddheading);
holder.distance = (TextView) view.findViewById(R.id.Distance);
holder.image = (ImageView) view.findViewById(R.id.imagecoffee);
holder.invite = (Button) view.findViewById(R.id.inviteButton);
holder.send = (Button) view.findViewById(R.id.fsendButton);
holder.time = (TextView) view.findViewById(R.id.timefree);
holder.viewAnimator = (ViewAnimator) view
.findViewById(R.id.viewFlipper);
myview.add(holder);
holder.v = view;
} else {
holder = (ViewHolder) view.getTag();
}
view.setTag(holder);
holder.invite.setOnClickListener(this);
holder.send.setOnClickListener(this);
holder.name.setText(name.get(position).split("\n")[0]);
holder.fname.setText(name.get(position).split("\n")[0]);
holder.heading.setText(heading.get(position));
String temp = "";
int sl = Integer.parseInt(slots.get(position));
if (sl % 2 == 0) {
temp = "" + ((sl / 2) - 1) + ":30 - " + ((sl / 2)) + ":00";
} else {
temp = "" + ((sl / 2)) + ":00-" + ((sl / 2)) + ":30";
}
holder.time.setText(temp);
holder.distance.setText(name.get(position).split("\n")[1] + " m");
holder.image.setImageBitmap(img.get(position));
holder.invite.setTag(position);
holder.send.setTag(position);
return view;
}
private static class ViewHolder {
protected TextView name;
protected TextView heading;
protected TextView distance, time;
protected ImageView image;
protected Button invite, send;
protected View v;
protected ViewAnimator viewAnimator;
protected TextView fname;
protected EditText msg;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.inviteButton) {
AnimationFactory.flipTransition(
myview.get((Integer) v.getTag()).viewAnimator,
FlipDirection.LEFT_RIGHT);
} else if (v.getId() == R.id.fsend) {
SharedPreferences pref = contexts.getApplicationContext()
.getSharedPreferences("MyPref", 0);
String slotsss = "{\"slots\":[" + slots.get((Integer) v.getTag())
+ "]}";
final Map<String, String> params = new HashMap<String, String>();
params.put("slot", slotsss);
Log.e("invite slots", slotsss);
params.put("to", ids.get((Integer) v.getTag()));
params.put("from", pref.getString("id", "N/A"));
params.put("message", myview.get((Integer) v.getTag()).msg
.getText().toString());
StringRequest jsonObjReq = new StringRequest(Method.POST,
Const.URL_INVITE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Slots Response: ", response.toString());
Toast.makeText(contexts, "invited" + response,
Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("invite Error:",
"Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#Override
protected Map<String, String> getParams() {
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq,
tag_json_obj);
}
}
}
The View objects are recycling and you're using the same ViewHolder object (and other UI components) for both positions. The view being clicked has had its tag updated to the position desired, but the animation object is the same as another position due to the recycling.

How to get rowID of custom ListView's selected row's child?

I've a custom list view with 4 textViews and 2 buttons,which i am filling up via database,
TV NAME | TV EMAIL | TV NO | TV ID(database primary key,set invisible) | ButtonEDIT | ButtonDelete.
I successfully got the id from the database,which is set as primary key.
Now what i want to do is,when i PRESS ButtonEDIT,it should toast a message something like
"Edit selected for ID :" + TVID.getText().toString(),so basically i want to display the value which is stored in the TVID(i.e. my database id).
But when i am trying to do it,it only displays the firstID (0) for buttons of different rows,please do help asap.
Am linking code below
Custom ListView Adapter :
package com.iwill.Database_add_display;
import java.io.ObjectOutputStream.PutField;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MyAdapter extends BaseAdapter
{
private ArrayList<userdetails> data;
private static LayoutInflater minflater=null;
private int[] userArray;
public MyAdapter(Context context,ArrayList<userdetails> results)
{
data = results;
minflater = LayoutInflater.from(context);
}
#Override
public int getCount()
{
return data.size();
}
#Override
public Object getItem(int position)
{
return data.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
public int getUserArray(int position){
return userArray[position];
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
if (convertView == null)
{
convertView = minflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.tvname = (TextView) convertView.findViewById(R.id.textname);
holder.tvemail = (TextView) convertView.findViewById(R.id.textemail);
holder.tvno = (TextView) convertView.findViewById(R.id.textno);
holder.tvID = (TextView)convertView.findViewById(R.id.textID);
holder.b1 = (Button) convertView.findViewById(R.id.btnEdit);
holder.b2 = (Button) convertView.findViewById(R.id.btnDelete);
//convertView.setTag(holder);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.tvname.setText(data.get(position).getName());
holder.tvemail.setText(data.get(position).getMail());
holder.tvno.setText(data.get(position).getNo());
holder.tvID.setText(String.valueOf(data.get(position).getID()));
return convertView;
}
static class ViewHolder
{
TextView tvname;
TextView tvemail;
TextView tvno;
Button b1;
Button b2;
TextView tvID;
}
}
ListActivity :
package com.iwill.Database_add_display;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class viewnameactivity extends Activity
{
ArrayList<userdetails> mylist = new ArrayList<userdetails>();
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
ListView listView;
MyAdapter adapter;
int pos;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.viewname);
mDbHelper = new DatabaseHelper(this);
final List<userdetails> List = mDbHelper.selectAll();
for (int i = 0; i < List.size(); i++)
{
//Log.i("List of Data....", List.get(i));
}
for (int j = 0; j < List.size(); j++)
{
mylist.add(List.get(j));
Log.i("List View :", mylist.get(j).toString());
}
listView = (ListView)findViewById(R.id.listView);
adapter = new MyAdapter(this,mylist);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,View v,int position,long id) {
Toast.makeText(viewnameactivity.this,"Edit button of ID : "+ adapter.getUserArray(position)+" selected.",
Toast.LENGTH_SHORT).show();
pos = adapter.getUserArray(position);
}
});
mDbHelper.close();
Button btnBack = (Button)findViewById(R.id.btnBack);
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(viewnameactivity.this,MainActivity.class);
startActivity(i);
}
});
/* Button btnEdit = (Button)findViewById(R.id.btnEdit);
btnEdit.setOnClickListener(new OnClickListener() {
//TextView strID = (TextView)findViewById(R.id.textID);
//long lngID = Long.parseLong(strID.getText().toString());
#Override
public void onClick(View v) {
Toast.makeText(viewnameactivity.this,"Edit button of ID : selected.",
Toast.LENGTH_SHORT).show();
}
});
Button btnDelete = (Button)findViewById(R.id.btndelete);
btnDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(viewnameactivity.this,"Delete button of ID : selected.",
Toast.LENGTH_SHORT).show();
}
});*/
}
public void OnClickEdit(View v){
//TextView strID = (TextView)this.findViewById(R.id.textID);
//long lngID = Long.parseLong(strID.getText().toString());
Toast.makeText(viewnameactivity.this,"Edit button of ID : "+ pos +" selected.",
Toast.LENGTH_SHORT).show();
}
public void OnClickDelete(View v){
TextView strID = (TextView)findViewById(R.id.textID);
long lngID = Long.parseLong(strID.getText().toString());
Toast.makeText(viewnameactivity.this,"Delete button of ID :"+ lngID + "selected.",
Toast.LENGTH_SHORT).show();
}
}
DatabaseOpenHelper Class :
package com.iwill.Database_add_display;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper
{
public static final String KEY_NAME = "NAME";
public static final String KEY_MAIL = "EMAIL";
public static final String KEY_NO ="NO";
public static final String KEY_ID = "ID";
private static final String DATABASE_NAME = "info.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "user";
private static String DB_PATH = "/data/data/com.iwill.Database_add_display";
private static String DB_NAME = "info.db";
private static Context context;
private static SQLiteDatabase db;
private static final String TAG = "MEDIA";
public DatabaseHelper(Context context)
{
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
//this.insertStmt = this.db.compileStatement(INSERT);
}
public long insert(String uname,String mail,String no)
{
ContentValues CV = new ContentValues();
CV.put(KEY_NAME, uname);
CV.put(KEY_MAIL , mail);
CV.put(KEY_NO, no);
long rawId = db.insert(TABLE_NAME, null, CV);
return rawId;
}
public void update(long _ID,String updateuname,String updatemail,String updateno)
{
Log.i("tag","_ID"+_ID);
ContentValues cvupdate=new ContentValues();
cvupdate.put(KEY_NAME,updateuname);
cvupdate.put(KEY_MAIL, updatemail);
cvupdate.put(KEY_NO, updateno);
db.update(TABLE_NAME, cvupdate, "_id"+" = ?",new String[]{String.valueOf(_ID)});
Log.i("tag", "Item Updated Database Helper");
}
public void delete(long _ID)
{
this.db.delete(TABLE_NAME, "_id"+" = ?", new String[]{String.valueOf(_ID)});
Log.i("tag", "Item deleted");
}
public List<userdetails> selectAll(){
List<userdetails> list = new ArrayList<userdetails>();
Cursor cursor = this.db.query(TABLE_NAME, new String[] {"_id", "NAME", "EMAIL", "NO"},
null, null, null, null, "_id asc");
if(cursor.moveToFirst()){
do {
userdetails usd= new userdetails();
usd.setName(cursor.getString(1));
usd.setMail(cursor.getString(2));
usd.setNo(cursor.getString(3));
usd.setID(cursor.getLong(0));
list.add(usd);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
public void close(){
db.close();
}
public List<String> selectAllid(){
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME, new String[] {"_id", "NAME"},
null, null, null, null, "_id asc");
if(cursor.moveToFirst()){
do {
//list.add(cursor.getInt(0) + " "+cursor.getString(1));
list.add(cursor.getString(0));
Log.i("List 0 (id)....", cursor.getString(0));
Log.i("List 1 (URL)....", cursor.getString(1));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
// TESTING
private static class OpenHelper extends SQLiteOpenHelper
{
public OpenHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
String str = "CREATE TABLE IF NOT EXISTS user(_id INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT,EMAIL TEXT,NO TEXT)";
db.execSQL(str);
}
private boolean checkDatabase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
public void createNewDatabase() {
InputStream assetsDB = null;
try {
assetsDB = context.getAssets().open(DB_NAME);
OutputStream dbOut = new FileOutputStream(DB_PATH + DB_NAME);
byte[] buffer = new byte[1024];
int length;
while ((length = assetsDB.read(buffer)) > 0) {
dbOut.write(buffer, 0, length);
}
dbOut.flush();
dbOut.close();
assetsDB.close();
Log.i("New Database created.......", "New database created...");
} catch (IOException e) {
Log.e("Could not create new database...", "Could not create new database...");
e.printStackTrace();
}
}
#Override
public synchronized void close() {
if(db != null){
db.close();
super.close();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
//Log.w("Example", "Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
Am kinda beginner and any help would be really appreciated. (:
Try adding this to your adapter:
public class MyAdapter extends BaseAdapter
{
public static HashMap<Integer,String> myList=new HashMap<Integer,String>();
...
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
...
myList.put(position,String.valueOf(data.get(position).getID()));
return convertView;
}
...
}
Now in your activity,
public class viewnameactivity extends Activity
{
...
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,View v,int position,long id) {
pos = adapter.getUserArray(position);
String TVID=MyAdapter.myList.get(position); // this will give you tvid for each listitem
}
});
...
}

How do i get image from imageUrl in imageView

How can i get image from image url in image view.
My imageUrl is coming from databaseadapter.
In Fields class LocationImage dataype is string but in setBackgroundResource method it is asking for int value as parameter. LocationImage url is getting from database, so that i've taken that as string variable.
code lines are here.
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class FindPlaces extends ListActivity{
private SQLiteDatabase DbLoc;
ListView lv;
int val;
private ArrayList<Fields> results = new ArrayList<Fields>();
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.places);
getallLocs();
setListAdapter(new StudentListAdapter(this, val, results));
}
class StudentListAdapter extends ArrayAdapter<Fields>{
private ArrayList<Fields> locationDetails;
private Context mContext;
public StudentListAdapter(Context context,int textViewResourceId, ArrayList<Fields> results) {
super(context, textViewResourceId, results);
// TODO Auto-generated constructor stub
System.out.println("Constructor StudentList Adapter...");
this.locationDetails = results;
mContext = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return results.size();
}
#Override
public Fields getItem(int position) {
// TODO Auto-generated method stub
return locationDetails.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return super.getItemId(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if(v == null){
LayoutInflater vl = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vl.inflate(R.layout.placeslist, null);
}
Fields o = results.get(position);
if (o != null) {
TextView iv = (TextView)v.findViewById(R.id.toptext);
TextView tv_sNo = (TextView)v.findViewById(R.id.toptext1);
ImageView tv_Image = (ImageView)v.findViewById(R.id.Locimage);
iv.setText(o.getLocationName());
//tv_sNo.setText("Status: "+ o.getOrderStatus());
tv_sNo.setText(o.getLocationImage());
tv_Image.setBackgroundResource(o.getLocationImage());
}
DbLoc.close();
return v;
}
}
static class ViewHolder
{
TextView Locationname;
ImageView Locationimage;
}
private void getallLocs() {
// TODO Auto-generated method stub
try {
DatabaseHelper dbHelper = new DatabaseHelper(
this.getApplicationContext());
DbLoc = dbHelper.getWritableDatabase();
Cursor c = DbLoc.rawQuery("SELECT " + DatabaseHelper.LocationName+ " , " + DatabaseHelper.LocationImage + " FROM "
+ DatabaseHelper.LOCATIONTABLE , null);
System.out.println("SELECT " + DatabaseHelper.LocationLang+" , "+DatabaseHelper.LocationLat+" , "+ DatabaseHelper.LocationName
+ " ," + DatabaseHelper.LocationImage + " FROM "
+ DatabaseHelper.LOCATIONTABLE );
if (c != null) {
if (c.moveToFirst()) {
do {
String LocationName= c.getString(c.getColumnIndex("LocationName"));
String Mobile = c.getString(c
.getColumnIndex("LocationImage"));
Fields p = new Fields(LocationName, Mobile);
results.add(p);
} while (c.moveToNext());
}
}
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(),
"Could not create or Open the database");
}
}
}
if u got image url use the below code to set the image from url to imageview
Bitmap mbmp = BitmapFactory.decodeStream(new java.net.URL("urlname").openStream());
Imageview_ref.setImageBitmap(mbmp);

Categories

Resources