Hy all,
In my APP in need show list of contact (it's ok for the moment) in the listview.
And I want when in swipe in the right of the number the APP call the number.
I have this for the moment :
MainActivity :
getSupportFragmentManager().beginTransaction().replace(R.id.fragmentLayout, new FragContact()).commit();
In my frag :
public class FragContact extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
if (shouldShowRequestPermissionRationale(Manifest.permission.READ_CONTACTS) == true) {
explain();
} else {
//demander l'autorisation
}
} else {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
final ListView list = (ListView) rootView.findViewById(android.R.id.list);
final List<Map<String, Object>> contacts = retrieveContacts(getActivity().getContentResolver());
if (contacts != null) {
final SimpleAdapter adapter = new SimpleAdapter(getActivity(), contacts, R.layout.contact, new String[]{"contactNumber", "photo"}, new int[]{R.id.name,
R.id.photo});
adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object data, String textRepresentation) {
if ((view instanceof ImageView) & (data instanceof Bitmap)) {
final ImageView image = (ImageView) view;
final Bitmap photo = (Bitmap) data;
image.setImageBitmap(photo);
return true;
}
return false;
}
});
list.setAdapter(adapter);
}
return rootView;
}
return null;
} else {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
final ListView list = (ListView) rootView.findViewById(android.R.id.list);
final List<Map<String, Object>> contacts = retrieveContacts(getActivity().getContentResolver());
if (contacts != null) {
final SimpleAdapter adapter = new SimpleAdapter(getActivity(), contacts, R.layout.contact, new String[]{"contactNumber", "photo"}, new int[]{R.id.name,
R.id.photo});
adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object data, String textRepresentation) {
if ((view instanceof ImageView) & (data instanceof Bitmap)) {
final ImageView image = (ImageView) view;
final Bitmap photo = (Bitmap) data;
image.setImageBitmap(photo);
return true;
}
return false;
}
});
list.setAdapter(adapter);
}
return rootView;
}
}
public List<Map<String, Object>> retrieveContacts(ContentResolver contentResolver)
{
final List<Map<String, Object>> contacts = new ArrayList<Map<String, Object>>();
final Cursor cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID}, null, null, null);
if (cursor == null)
{
Log.e("retrieveContacts", "Cannot retrieve the contacts");
return null;
}
if (cursor.moveToFirst() == true)
{
do {
final long id = Long.parseLong(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID)));
final String contactNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (contactNumber != null) {
final Bitmap photo = getPhoto(contentResolver, id);
final Map<String, Object> contact = new HashMap<String, Object>();
contact.put("contactNumber", contactNumber);
contact.put("photo", photo);
contacts.add(contact);
}
}
while (cursor.moveToNext() == true);
}
if (cursor.isClosed() == false)
{
cursor.close();
}
return contacts;
}
private Bitmap getPhoto(ContentResolver contentResolver, long contactId)
{
Bitmap photo = null;
final Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
final Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
final Cursor cursor = contentResolver.query(photoUri, new String[] { ContactsContract.Contacts.Photo.DATA15 }, null, null, null);
if (cursor == null)
{
Log.e("getPhoto", "Cannot retrieve the photo of the contact with id '" + contactId + "'");
return null;
}
if (cursor.moveToFirst() == true)
{
final byte[] data = cursor.getBlob(0);
if (data != null)
{
photo = BitmapFactory.decodeStream(new ByteArrayInputStream(data));
}
}
if (cursor.isClosed() == false)
{
cursor.close();
}
return photo;
}
private void askForPermission()
{
requestPermissions(new String[] { Manifest.permission.READ_CONTACTS }, 2);
}
private void explain()
{
askForPermission();
}
}
Actualy I have there :
Thank for you're help.
Related
I am calling the Camera Intent from one of the fragments to save the image into gallery. The photo is taken and the image also gets saved in the gallery. I also have an adapter which gets all the images stored in the gallery into my application using GridView. So after taking the photo from the Camera Intent, I have to go back to another fragment and come back to see my photo refreshed in the GridView. So basically, I want to refresh the fragment once I am back from the Camera Intent.
Here is the structure. I have a fragment called GalleryHomeFragment, from which I click a button and go to GalleryFragment. From there, I call the Camera Intent. My requirement is to refresh the GalleryFragment, once I come back from taking the picture, to see the pictures in my folders.
Here is what I have tried so far. Posting the necessary code.
GalleryFragment.java
cameraButton = (FloatingActionButton) view.findViewById(R.id.cameraBtn);
cameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
//gridView = (GridView) view.findViewById(R.id.gridView);
gv_folder = (GridView)view.findViewById(R.id.gv_folder);
gv_folder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getContext(), PhotosActivity.class);
intent.putExtra("value",i);
startActivity(intent);
}
});
if ((ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)) && (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
}else {
Log.e("Else","Else");
fn_imagespath();
}
setHasOptionsMenu(true);
return view;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {photoFile = createImageFile();
} catch (IOException ex) {
Context context = getContext();
CharSequence text = "Photo cannot be stored.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Context context = getContext();
Uri photoURI = FileProvider.getUriForFile(context,
"com.example.projectga.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}else{
Context context = getContext();
CharSequence text = "Attention! Required to take picture!!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
}
public void createFolder(){
if (!directory.exists()){
directory.mkdirs();
}
}
private File createImageFile() throws IOException {
createFolder();
// Create an image file name
Context context = getContext();
String timeStamp = new SimpleDateFormat("dd-MMM-yyyy").format(new Date());
String imageFileName = projectName + "_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
addImageToGallery(image, context);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getPath();
return image;
}
public static void addImageToGallery(File image, final Context context) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, image.toString());
context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
search = menu.add("search").setIcon(R.drawable.ic_search_green_24dp).setShowAsActionFlags(1);
super.onCreateOptionsMenu(menu, inflater);
}
public ArrayList<Model_images> fn_imagespath() {
al_images.clear();
int int_position = 0;
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
String absolutePathOfImage = null;
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
cursor = getContext().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
Log.e("Column", absolutePathOfImage);
Log.e("Folder", cursor.getString(column_index_folder_name));
for (int i = 0; i < al_images.size(); i++) {
if (al_images.get(i).getStr_folder().equals(cursor.getString(column_index_folder_name))) {
boolean_folder = true;
int_position = i;
break;
} else {
boolean_folder = false;
}
}
if (boolean_folder) {
ArrayList<String> al_path = new ArrayList<>();
al_path.addAll(al_images.get(int_position).getAl_imagepath());
al_path.add(absolutePathOfImage);
al_images.get(int_position).setAl_imagepath(al_path);
} else {
ArrayList<String> al_path = new ArrayList<>();
al_path.add(absolutePathOfImage);
Model_images obj_model = new Model_images();
obj_model.setStr_folder(cursor.getString(column_index_folder_name));
obj_model.setAl_imagepath(al_path);
al_images.add(obj_model);
}
}
for (int i = 0; i < al_images.size(); i++) {
Log.e("FOLDER", al_images.get(i).getStr_folder());
for (int j = 0; j < al_images.get(i).getAl_imagepath().size(); j++) {
Log.e("FILE", al_images.get(i).getAl_imagepath().get(j));
}
}
obj_adapter = new Adapter_PhotosFolder(getContext(),al_images);
gv_folder.setAdapter(obj_adapter);
return al_images;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
fn_imagespath();
} else {
Toast.makeText(getContext(), "The app was not allowed to read or write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
}
GridViewAdapter.java
Context context;
ViewHolder viewHolder;
ArrayList<Model_images> al_menu = new ArrayList<>();
int int_position;
public GridViewAdapter(Context context, ArrayList<Model_images> al_menu,int int_position) {
super(context, R.layout.adapter_photosfolder, al_menu);
this.al_menu = al_menu;
this.context = context;
this.int_position = int_position;
}
#Override
public int getCount() {
Log.e("ADAPTER LIST SIZE", al_menu.get(int_position).getAl_imagepath().size() + "");
return al_menu.get(int_position).getAl_imagepath().size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_menu.get(int_position).getAl_imagepath().size() > 0) {
return al_menu.get(int_position).getAl_imagepath().size();
} else {
return 1;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.adapter_photosfolder, parent, false);
viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder);
viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2);
viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_foldern.setVisibility(View.GONE);
viewHolder.tv_foldersize.setVisibility(View.GONE);
Glide.with(context).load("file://" + al_menu.get(int_position).getAl_imagepath().get(position))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(viewHolder.iv_image);
return convertView;
}
private static class ViewHolder {
TextView tv_foldern, tv_foldersize;
ImageView iv_image;
}
}
Adapter_PhotosFolder.java
Context context;
ViewHolder viewHolder;
ArrayList<Model_images> al_menu = new ArrayList<>();
int int_position;
public GridViewAdapter(Context context, ArrayList<Model_images> al_menu,int int_position) {
super(context, R.layout.adapter_photosfolder, al_menu);
this.al_menu = al_menu;
this.context = context;
this.int_position = int_position;
}
#Override
public int getCount() {
Log.e("ADAPTER LIST SIZE", al_menu.get(int_position).getAl_imagepath().size() + "");
return al_menu.get(int_position).getAl_imagepath().size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_menu.get(int_position).getAl_imagepath().size() > 0) {
return al_menu.get(int_position).getAl_imagepath().size();
} else {
return 1;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.adapter_photosfolder, parent, false);
viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder);
viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2);
viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_foldern.setVisibility(View.GONE);
viewHolder.tv_foldersize.setVisibility(View.GONE);
Glide.with(context).load("file://" + al_menu.get(int_position).getAl_imagepath().get(position))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(viewHolder.iv_image);
return convertView;
}
private static class ViewHolder {
TextView tv_foldern, tv_foldersize;
ImageView iv_image;
}
Any help is appreciated. Thanks a lot in advance.
I was so stupid and why I don't know it took me so long to figure out the answer.
I did this by restarting the fragment in the onActivityResult() like this.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Fragment galleryFragment = new GalleryFragment();
FragmentManager fm = getFragmentManager();
fm.popBackStack();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container_gaFragments, galleryFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
}
So each time when the result of activity is a success, I refresh the fragment to the galleryFragment and it works perfect.
I am trying to build a demo chatting App.I want to show the messages with section headers as Dates like "Today","Yesterday","May 21 2015" etc.I have managed to achieve this but since the new View method gets called whenever I scroll the list.The headers and messages get mixed up.
For simplicity, I have kept the header in the layouts itself and changing its visibility(gone and visible) if the date changes.
Can you help me out with this? Let me know if anyone needs any more info to be posted in the question.
public class ChatssAdapter extends CursorAdapter {
private Context mContext;
private LayoutInflater mInflater;
private Cursor mCursor;
private String mMyName, mMyColor, mMyImage, mMyPhone;
// private List<Contact> mContactsList;
private FragmentActivity mActivity;
private boolean mIsGroupChat;
public ChatssAdapter(Context context, Cursor c, boolean groupChat) {
super(context, c, false);
mContext = context;
mMyColor = Constants.getMyColor(context);
mMyName = Constants.getMyName(context);
mMyImage = Constants.getMyImageUrl(context);
mMyPhone = Constants.getMyPhone(context);
mIsGroupChat = groupChat;
mCursor = c;
// mActivity = fragmentActivity;
/*try {
mContactsList = PinchDb.getHelper(mContext).getContactDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}*/
}
#Override
public int getItemViewType(int position) {
Cursor cursor = (Cursor) getItem(position);
return getItemViewType(cursor);
}
private int getItemViewType(Cursor cursor) {
boolean type;
if (mIsGroupChat)
type = cursor.getString(cursor.getColumnIndex(Chat.COLMN_CHAT_USER)).compareTo(mMyPhone) == 0;
else type = cursor.getInt(cursor.getColumnIndex(Chat.COLMN_FROM_ME)) > 0;
if (type) {
return 0;
} else {
return 1;
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = null;
int itemViewType = getItemViewType(cursor);
if (v == null) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (itemViewType == 0) {
v = mInflater.inflate(R.layout.row_chat_outgoing, parent, false);
} else {
v = mInflater.inflate(R.layout.row_chat_incoming, parent, false);
}
}
return v;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = new ViewHolder();
View v = view;
final Chat chat = new Chat(cursor);
boolean fromMe = mIsGroupChat ? chat.getUser().compareTo(mMyPhone) == 0 : chat.isFrom_me();
if (fromMe) {
// LOGGED IN USER'S DATA SETTING....
holder.chat_name = (StyleableTextView) v
.findViewById(R.id.chat_user_name);
holder.chat_time = (StyleableTextView) v
.findViewById(R.id.chat_time);
holder.chat_tag = (StyleableTextView) v
.findViewById(R.id.chat_tag);
int color = Color.parseColor("#FFFFFF");
v.setBackgroundColor(color);
holder.chat_name.setText("#You");
holder.chat_time.setText(AppUtil.getEventTime(chat.getTimestampLong()));
// header text setting and process..
holder.chat_header_text = (TextView) v.findViewById(R.id.header_text);
String str_date = AppUtil.covertToDate(chat.getTimestampLong());
String pref_date = SharePreferencesUtil.getSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, "");
if (!str_date.equalsIgnoreCase(pref_date)) {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, str_date);
holder.chat_header_text.setText(str_date);
} else {
holder.chat_header_text.setVisibility(View.GONE);
}
String firstWord, theRest;
String mystring = chat.getText();
String arr[] = mystring.split(" ", 2);
if (arr.length > 1) {
firstWord = arr[0]; // the word with hash..
theRest = arr[1]; // rest of the body..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + firstWord + "</b></font>" + " " + "<font color=\"#000000\">" + theRest + "</font>"));
// holder.chat_text.setText(theRest);
// holder.chat_text.setClickable(false);
} else {
String msg = arr[0]; // the word with hash..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + msg + "</b></font>"));
//holder.chat_text.setText("");
}
updateTimeTextColorAsPerStatus(holder.chat_time, chat.getStatus());
v.setTag(holder);
} else {
// OTHER USER'S DATA SETTING....
holder.chat_name = (StyleableTextView) v
.findViewById(R.id.chat_user_name);
holder.chat_time = (StyleableTextView) v
.findViewById(R.id.chat_time);
holder.chat_tag = (StyleableTextView) v
.findViewById(R.id.chat_tag);
holder.chat_image = (ImageView) v
.findViewById(R.id.chat_profile_image);
String image = cursor.getString(cursor.getColumnIndex("image"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String color = cursor.getString(cursor.getColumnIndex("color"));
// set the values...
if (holder.chat_image != null) {
MImageLoader.displayImage(context, image, holder.chat_image, R.drawable.round_user_place_holder);
}
int back_color = Color.parseColor("#FFFFFF");
v.setBackgroundColor(back_color);
holder.chat_name.setText(name);
holder.chat_time.setText(AppUtil.getEventTime(chat.getTimestampLong()));
// header text setting and process..
holder.chat_header_text = (TextView) v.findViewById(R.id.header_text);
String str_date = AppUtil.covertToDate(chat.getTimestampLong());
String pref_date = SharePreferencesUtil.getSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, "");
Log.d("eywa", "str date is ::::: " + str_date + " pref date is :::::: " + pref_date);
/*if (!TextUtils.isEmpty(pref_date)) {
if (!pref_date.contains(str_date)) {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, pref_date + str_date);
holder.chat_header_text.setText(str_date);
} else {
holder.chat_header_text.setVisibility(View.GONE);
}
} else {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, pref_date + str_date);
holder.chat_header_text.setText(str_date);
}*/
if (!str_date.equalsIgnoreCase(pref_date)) {
holder.chat_header_text.setVisibility(View.VISIBLE);
SharePreferencesUtil.putSharedPreferencesString(mContext, Constants.CHAT_TIMESTAMP, str_date);
holder.chat_header_text.setText(str_date);
} else {
holder.chat_header_text.setVisibility(View.GONE);
}
String firstWord, theRest;
String mystring = chat.getText();
String arr[] = mystring.split(" ", 2);
if (arr.length > 1) {
firstWord = arr[0]; // the word with hash..
theRest = arr[1]; // rest of the body..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + firstWord + "</b></font>" + " " + "<font color=\"#000000\">" + theRest + "</font>"));
// holder.chat_text.setClickable(false);
} else {
String msg = arr[0]; // the word with hash..
holder.chat_tag.setText(Html.fromHtml("<font color=\"#999999\"><b>" + msg + "</b></font>"));
// holder.chat_text.setText("");
}
String phone = cursor.getString(cursor.getColumnIndex("user"));
final Contact contact = new Contact(name, phone, "", color, image);
if (holder.chat_image != null) {
holder.chat_image.setTag(contact);
// holder.chat_name.setTag(contact);
holder.chat_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Contact con = (Contact) v.getTag();
Intent intent = new Intent(mContext, OtherProfileActivity.class);
intent.putExtra(Constants.EXTRA_CONTACT, con);
mContext.startActivity(intent);
}
});
}
v.setTag(holder);
}
/*else
{
view=
}*/
}
private void updateTimeTextColorAsPerStatus(TextView chat_time, int status) {
if (status == 0) chat_time.setVisibility(View.INVISIBLE);
else {
chat_time.setVisibility(View.VISIBLE);
/* if (status == 1)
chat_time.setTextColor(mContext.getResources().getColor(android.R.color.white));*/
if (status == 2)
chat_time.setTextColor(mContext.getResources().getColor(android.R.color.darker_gray));
else if (status == 3)
chat_time.setTextColor(mContext.getResources().getColor(android.R.color.black));
}
}
#Override
public int getViewTypeCount() {
return 2;
}
public class ViewHolder {
public StyleableTextView chat_name;
public StyleableTextView chat_time;
public StyleableTextView chat_tag;
public ImageView chat_image;
public TextView chat_header_text;
}
#Override
public int getCount() {
if (getCursor() == null) {
return 0;
} else {
return getCursor().getCount();
}
}
}
I'm now currently working on a project that lets the user view the list of a certain table and has the privilege of either editing or deleting it. There's no error, I just don't have any idea on what to do. Maybe anyone could help me on even just the delete feature? Giving a sample code would be so much helpful. Here's my code:
SQLiteDatabase myDataBase;
String DB_PATH = null;
private ProgressDialog m_ProgressDialog = null;
private ArrayList<Order> m_orders = null;
private OrderAdapter m_adapter;
private Runnable viewOrders;
int totalId, totalProdId, totalQty, totalBigQty, totalUnitQty;
Cursor cursorProduct;
String id = "";
String productid = "";
String qty = "";
String bigqty = "";
String unitqty = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dc_invviewlist);
copyDB();
myDataBase = SQLiteDatabase.openOrCreateDatabase(DB_PATH,null);
m_orders = new ArrayList<Order>();
this.m_adapter = new OrderAdapter(this, R.layout.dc_inventory_viewlist, m_orders);
setListAdapter(this.m_adapter);
viewOrders = new Runnable(){
#Override
public void run() {
getOrders();
}
};
Thread thread = new Thread(null, viewOrders, "MagentoBackground");
thread.start();
m_ProgressDialog = ProgressDialog.show(DC_invviewlist.this,
"Please wait...", "Retrieving data ...", true);
registerForContextMenu(getListView());
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(m_orders != null && m_orders.size() > 0){
m_adapter.notifyDataSetChanged();
for(int i=0;i<m_orders.size();i++)
m_adapter.add(m_orders.get(i));
}
m_ProgressDialog.dismiss();
m_adapter.notifyDataSetChanged();
}
};
private void getOrders(){
try{
String i = getPIViewListId();
String pi = getPIViewListProdId();
String q = getPIViewListQty();
String bq = getPIViewListBigQty();
String uq = getPIViewListUnitQty();
String[] iValue = i.split("~");
String[] piValue = pi.split("~");
String[] qValue = q.split("~");
String[] bqValue = bq.split("~");
String[] uqValue = uq.split("~");
totalId = iValue.length;
totalProdId = piValue.length;
totalQty = qValue.length;
totalBigQty = bqValue.length;
totalUnitQty = uqValue.length;
m_orders = new ArrayList<Order>();
for (int j = 0; j < totalId; j++) {
Order o = new Order();
o.setOrderId(iValue[j]);
o.setOrderProdId(piValue[j]);
o.setOrderQty(qValue[j]);
o.setOrderBigQty(bqValue[j]);
o.setOrderUnitQty(uqValue[j]);
m_orders.add(o);
}
Thread.sleep(2000);
Log.i("ARRAY", ""+ m_orders.size());
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
private class OrderAdapter extends ArrayAdapter<Order> {
private ArrayList<Order> items;
public OrderAdapter(Context context, int textViewResourceId, ArrayList<Order> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.dc_inventory_viewlist, null);
}
Order o = items.get(position);
if (o != null) {
TextView id = (TextView) v.findViewById(R.id.txtInvViewListId);
TextView prodid = (TextView) v.findViewById(R.id.txtInvViewListProductId);
TextView qty = (TextView) v.findViewById(R.id.txtInvViewListQty);
TextView bigqty = (TextView) v.findViewById(R.id.txtInvViewListBigQty);
TextView unitqty = (TextView) v.findViewById(R.id.txtInvViewListUnitQty);
if (id != null) {
id.setText(o.getOrderId()); }
if(prodid != null){
prodid.setText(o.getOrderProdId());
}
if(qty != null){
qty.setText(o.getOrderQty());
}
if(bigqty != null){
bigqty.setText(o.getOrderBigQty());
}
if(unitqty != null){
unitqty.setText(o.getOrderUnitQty());
}
}
return v;
}
}
public void copyDB(){
if(android.os.Build.VERSION.SDK_INT >= 17){
DB_PATH = getApplicationContext().getApplicationInfo().dataDir + "/databases/";
}
else{
DB_PATH = "/data/data/" + getApplicationContext().getPackageName() + "/databases/";
}
File dbdir = new File(DB_PATH);
if(!dbdir.exists()){
dbdir.mkdirs();
}
File file = new File(DB_PATH+"DC");
if(!file.exists()){
try{
InputStream is = getApplicationContext().getAssets().open("DC");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(file);
fos.write(buffer);
fos.flush();
fos.close();
}catch(Exception e){ throw new RuntimeException(e);};
}
if(android.os.Build.VERSION.SDK_INT >= 17){
DB_PATH = getApplicationInfo().dataDir + "/databases/DC";
}else{
DB_PATH = "/data/data/" + getPackageName() + "/databases/DC";
}
}
#Override
protected void onResume() {
super.onResume();
myDataBase = SQLiteDatabase.openOrCreateDatabase(DB_PATH, null);
}
#Override
protected void onPause() {
super.onPause();
myDataBase.close();
}
public String getPIViewListId(){
cursorProduct = myDataBase.rawQuery("Select * from tblProductInvAdjust", null);
if (cursorProduct.moveToFirst()) {
do {
id += ""+cursorProduct.getString(0)+"~";
} while (cursorProduct.moveToNext());
}
if (cursorProduct != null && !cursorProduct.isClosed()) {
cursorProduct.close();
}
return id;
}
public String getPIViewListProdId(){
cursorProduct = myDataBase.rawQuery("Select * from tblProductInvAdjust", null);
if (cursorProduct.moveToFirst()) {
do {
productid += ""+cursorProduct.getString(1)+"~";
} while (cursorProduct.moveToNext());
}
if (cursorProduct != null && !cursorProduct.isClosed()) {
cursorProduct.close();
}
return productid;
}
public String getPIViewListQty(){
cursorProduct = myDataBase.rawQuery("Select * from tblProductInvAdjust", null);
if (cursorProduct.moveToFirst()) {
do {
qty += ""+cursorProduct.getString(2)+"~";
} while (cursorProduct.moveToNext());
}
if (cursorProduct != null && !cursorProduct.isClosed()) {
cursorProduct.close();
}
return qty;
}
public String getPIViewListBigQty(){
cursorProduct = myDataBase.rawQuery("Select * from tblProductInvAdjust", null);
if (cursorProduct.moveToFirst()) {
do {
bigqty += ""+cursorProduct.getString(3)+"~";
} while (cursorProduct.moveToNext());
}
if (cursorProduct != null && !cursorProduct.isClosed()) {
cursorProduct.close();
}
return bigqty;
}
public String getPIViewListUnitQty(){
cursorProduct = myDataBase.rawQuery("Select * from tblProductInvAdjust", null);
if (cursorProduct.moveToFirst()) {
do {
unitqty += ""+cursorProduct.getString(4)+"~";
} while (cursorProduct.moveToNext());
}
if (cursorProduct != null && !cursorProduct.isClosed()) {
cursorProduct.close();
}
return unitqty;
}
final int CONTEXT_MENU_EDIT_ITEM =1;
final int CONTEXT_MENU_DELETE =2;
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
menu.add(Menu.NONE, CONTEXT_MENU_EDIT_ITEM, Menu.NONE, "Edit");
menu.add(Menu.NONE, CONTEXT_MENU_DELETE, Menu.NONE, "Delete");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
Long id = getListAdapter().getItemId(info.position);
switch (item.getItemId()) {
case CONTEXT_MENU_EDIT_ITEM:
//do smth
return(true);
case CONTEXT_MENU_DELETE:
myDataBase.execSQL("DELETE FROM tblProductInvAdjust");
return(true);
}
return(super.onOptionsItemSelected(item));
}
I hope anyone could help me on this. I really need a help right now. Thanks! :)
You can use this
sql_lite_db_obj.delete(tablename, whereClause, whereArgs)
For your convenience i edited my answer
public void clickHandler(View v) {
if (v.getId() == R.id.deleteOrder) {
int _id = 0;
try {
_id = (Integer) v.getTag(R.id.orderTitle);
} catch (Exception e) {
e.printStackTrace();
}
dh.delete(DatabaseHelpere.TableNAME, "_id=?",new String[] { String.valueOf(_id) });
}
}
EDITED
I am working on a contact list and trying to implement sectioned listview. When the app gets started, only one of the Header (Section) starts displaying itself after some chunks of items repeatedly and changing its position on scrolling up/down.
Here is my code :
private class MySimpleCursorAdapter extends SimpleCursorAdapter {
Holder holder = null;
LayoutInflater layoutInflater;
// String keyWord = "empty";
public MySimpleCursorAdapter(Context context, int layout, Cursor cur,
String[] from, int[] to, int flag) {
super(context, layout, cur, from, to, flag);
}
public String getTitle(String contName) {
return contName.substring(0, 1);
}
#Override
public View newView(Context context, Cursor mCursor, ViewGroup parent) {
holder = new Holder();
layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
String cont_Name = mCursor.getString(mCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
View view = null;
if ( ! keyWord.equalsIgnoreCase(getTitle(cont_Name)) || keyWord.equals(null))
{
view = layoutInflater.inflate(R.layout.section_header, null);
TextView sectionTitle = (TextView) view.findViewById(R.id.title2);
sectionTitle.setText(getTitle(cont_Name));
keyWord = getTitle(cont_Name);
Log.d("KeyWord", keyWord);
Log.d("Contact Name", cont_Name);
}
else if(keyWord.equalsIgnoreCase(getTitle(cont_Name))) {
view = layoutInflater.inflate(R.layout.pm_fragment, null);
holder.contactTitle= (TextView)view.findViewById(R.id.textView1);
holder.contactDetail = (TextView)view.findViewById(R.id.textView2);
holder.contactTitle.setText(mCursor.getString(mCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
holder.contactDetail.setText(mCursor.getString(mCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
Log.d("KeyWord", keyWord);
Log.d("Contact Name", cont_Name);
String contactId_String = ""+mCursor.getString(mCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
long contactId = Long.parseLong(mCursor.getString(mCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID)));
DatabaseHandler handler = new DatabaseHandler(getActivity());
Contact matchedContact = handler.getContact(contactId) ;
String dbContactId= "";
if(matchedContact != null){
if(matchedContact.getID() != 0 && ""+matchedContact.getID() != null){
dbContactId= ""+matchedContact.getID();
}
if(dbContactId.equals(contactId_String)){
holder.myImage = (ImageView) view.findViewById(R.id.imageView1);
holder.myImage.getLayoutParams().height = 100;
holder.myImage.getLayoutParams().width = 100;
holder.myImage.setBackgroundResource(R.drawable.person_empty_online);
}
}else{
holder.myImage = (ImageView) view.findViewById(R.id.imageView1);
holder.myImage.getLayoutParams().height = 100;
holder.myImage.getLayoutParams().width = 100;
holder.myImage.setBackgroundResource(R.drawable.person_empty_offline);
}
handler.close();
keyWord = getTitle(cont_Name);
}
return view;
}
}
During Debugging, After the ending line return view ; , it enters in CursorAdapter.class and passes by through the lines:
if (!mCursor.moveToPosition(position)) {
throw new IllegalStateException("couldn't move cursor to position " + position);
}
and enters in if condtion, but app doesn't crash.
Finally Got my answer my own after two weeks...my if-else conditions were too complex , so i make comparison on some different criteria.
if (mCursor.getPosition() > 0 && mCursor.moveToPrevious())
{
preName = mCursor.getString(mCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
mCursor.moveToNext();
}
else if(mCursor.getPosition() == 0)
{
preName = null;
}
else{
preName = null;
}
if(preName != null){
preTitle = getTitle(preName);
}
//===============================================================================
/*
* Setting Header And Contact Details
*/
//===============================================================================
if(mCursor.isFirst()){
holder.titleText.setVisibility(View.VISIBLE);
holder.titleText.setText(itemTitle);
}
else if(preName != null){
if(! itemTitle.equalsIgnoreCase(preTitle))
{
holder.titleText.setVisibility(View.VISIBLE);
holder.titleText.setText(itemTitle);
}else{
holder.titleText.setVisibility(View.GONE);
}
}
holder.contactTitle.setText(mCursor.getString(mCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
holder.contactDetail.setText(mCursor.getString(mCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
I am trying to get a simple view to work in android by using a cursor and a provider.
The provider works perfectly but I don't know how to get an int array out of a row in my cursor.
Here's my provider:
public class RecipeProvider extends ContentProvider {
public static final String COL_RECID = "_ID";
public static final String COL_RECCATID = "recipeCategory";
public static final String COL_RECIMGID = "recipeImageID";
public static final String COL_RECDESC = "recipeDescription";
public static final String COL_RECLOC = "recipeLocations";
public static final String[] columnNames = {COL_RECID, COL_RECCATID, COL_RECIMGID, COL_RECDESC, COL_RECLOC };
public static final String AUTHORITY = "be.pxl.minecraftguide.providers.recipeprovider";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/*");
private List<Recipe> recipesList;
#Override
public boolean onCreate() {
recipesList = new ArrayList<Recipe>();
recipesList.add(new Recipe(1, 2, R.drawable.diamond_boots, "Boots (Diamond)",
new int[] { 0,0,0, 1,0,1, 1,0,1 }, new int[] { R.drawable.diamond_ingot }));
recipesList.add(new Recipe(2, 2, R.drawable.gold_boots, "Boots (Gold)",
new int[] { 0,0,0, 1,0,1, 1,0,1 }, new int[] { R.drawable.gold_ingot }));
recipesList.add(new Recipe(3, 2, R.drawable.iron_boots, "Boots (Iron)",
new int[] { 0,0,0, 1,0,1, 1,0,1 }, new int[] { R.drawable.iron_ingot }));
return true;
}
#Override
public Cursor query(Uri arg0, String[] categories, String recipeID, String[] arg3,
String arg4) {
MatrixCursor mxCur = new MatrixCursor(columnNames);
RowBuilder rb;
if (categories != null && Integer.parseInt(categories[0]) != 1) {
for (Recipe rcp : recipesList) {
if (rcp.getRecipeCategory() == Integer.parseInt(categories[0])) {
rb = mxCur.newRow();
rb.add(rcp.getRecipeID());
rb.add(rcp.getRecipeCategory());
rb.add(rcp.getRecipeImageID());
rb.add(rcp.getRecipeDescription());
rb.add(rcp.getRecipeLocations());
}
}
} else if (recipeID != null) {
for (Recipe rcp : recipesList) {
if (rcp.getRecipeID() == Integer.parseInt(recipeID)) {
rb = mxCur.newRow();
rb.add(rcp.getRecipeID());
rb.add(rcp.getRecipeCategory());
rb.add(rcp.getRecipeImageID());
rb.add(rcp.getRecipeDescription());
rb.add(rcp.getRecipeLocations());
}
}
} else {
for (Recipe rcp : recipesList) {
rb = mxCur.newRow();
rb.add(rcp.getRecipeID());
rb.add(rcp.getRecipeCategory());
rb.add(rcp.getRecipeImageID());
rb.add(rcp.getRecipeDescription());
rb.add(rcp.getRecipeLocations());
}
}
if (mxCur.getCount() == 0) {
rb = mxCur.newRow();
rb.add(0);
rb.add(0);
rb.add(R.drawable.air);
rb.add("No recipes found for this category");
rb.add(new int[] { 0,0,0,0,0,0,0,0,0 });
}
return mxCur;
}
But my view intent class is where I'm stuck
public class RecipeDetails extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.recipedetails);
Bundle extras = getIntent().getExtras();
String id = Integer.toString(extras.getInt("recipeID"));
ImageView imgResult = (ImageView) findViewById(R.id.imgResult);
int[] imgLocations = new int[9];
ImageView imgIngr1 = (ImageView) findViewById(R.id.imgIngr1);
ImageView imgIngr2 = (ImageView) findViewById(R.id.imgIngr2);
ImageView imgIngr3 = (ImageView) findViewById(R.id.imgIngr3);
ImageView imgIngr4 = (ImageView) findViewById(R.id.imgIngr4);
ImageView imgIngr5 = (ImageView) findViewById(R.id.imgIngr5);
ImageView imgIngr6 = (ImageView) findViewById(R.id.imgIngr6);
ImageView imgIngr7 = (ImageView) findViewById(R.id.imgIngr7);
ImageView imgIngr8 = (ImageView) findViewById(R.id.imgIngr8);
ImageView imgIngr9 = (ImageView) findViewById(R.id.imgIngr9);
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(RecipeProvider.CONTENT_URI, null, id, null, null);
if (cursor.moveToFirst()) {
imgResult.setImageResource(cursor.getInt(2));
setTitle(cursor.getString(3));
//________________HOW CAN I GET AN INT ARRAY OUT?_________________
int[] intLocations = cursor.getType(4); //Cannot convert int to int[]
int[] intUsedImages = cursor.getType(5); //Same here
imgIngr1.setImageResource(imgLocations[0]);
imgIngr2.setImageResource(imgLocations[1]);
imgIngr3.setImageResource(imgLocations[2]);
imgIngr4.setImageResource(imgLocations[3]);
imgIngr5.setImageResource(imgLocations[4]);
imgIngr6.setImageResource(imgLocations[5]);
imgIngr7.setImageResource(imgLocations[6]);
imgIngr8.setImageResource(imgLocations[7]);
imgIngr9.setImageResource(imgLocations[8]);
}
}
}
So basically eclipse tells me that it's getting an int but I know it's an int array.
What should I do?