When I run this code I get all the list of image give below audio files but, the date of all the audio files are same like 20 Jan 1970 . below the code of AudioActivity.java. I don't know how I can do it if is possible .
public class AudioActivity extends AppCompatActivity {
Adapter adapter;
RecyclerView recyclerView;
private SlideAdapter slideAdapter;
public static final int PERMIT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio);
Toolbar toolbar = findViewById(R.id.aa_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(true);
getSupportActionBar().setTitle("Call Tank");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
recyclerView = findViewById(R.id.recyclerview);
fetchSongs();
}
private void fetchSongs() {
//define list to carry songs
List<ModelClass> songs = new ArrayList<>();
Uri songLibraryUri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
songLibraryUri = MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
} else {
songLibraryUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
//projection
String[] projection = new String[]{
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DATE_MODIFIED,
MediaStore.Audio.Media.DATA
};
//sort order
String sortOrder = MediaStore.Audio.Media.DATE_ADDED + " DESC";
//Querying
try (Cursor cursor = getContentResolver().query(songLibraryUri, projection, null, null, sortOrder)) {
// cache the cursor indices
int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
int nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
int dateColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATE_MODIFIED);
int pathColimn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
//getting the values
while (cursor.moveToNext()) {
// get values of colums for a give audio files
long id = cursor.getLong(idColumn);
String name = cursor.getString(nameColumn);
long date = cursor.getLong(dateColumn);
String path = cursor.getString(pathColimn);
//song uri
Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
//remove .mp3 extension on song's name
name = name.substring(0, name.lastIndexOf("."));
// song item
ModelClass song = new ModelClass(path, name, uri, date);
// add song to songs list
songs.add(song);
}
Intent i = new Intent(AudioActivity.this,Onboarding.class);
Bundle bundle = new Bundle();
bundle.putSerializable("songs", (Serializable) songs);
i.putExtras(bundle);
startActivity(i);
//Intent intent = new Intent(AudioActivity.this,Onboarding.class);
// intent.putExtra("songs", (Serializable) songs);
//show songs on rv
showSongs(songs);
Toast.makeText(this, "Number of Songs:" + songs.size(), Toast.LENGTH_SHORT).show();
}
}
private void showSongs(List<ModelClass> songs) {
// songs.clear();
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(RecyclerView.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
adapter = new Adapter(songs);
recyclerView.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
item.getItemId();
return super.onOptionsItemSelected(item);
}
}
Below the code of Adapter.java
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
List<ModelClass> songs;
public Adapter(List<ModelClass> songs) {
this.songs = songs;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// View view = LayoutInflater.from(parent).inflate(R.layout.item_layout,parent,false);
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.item_layout,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
ModelClass modelClass = songs.get(position);
String file = modelClass.getFilename();
holder.fileName.setText(file);
Long dateTime = modelClass.getDate();
String currentDate = DateFormat.getDateInstance().format(dateTime);
holder.date.setText(currentDate);
MediaPlayer mediaPlayer = new MediaPlayer();
String audioPath = modelClass.getPath();
try {
mediaPlayer.setDataSource(audioPath);
} catch (IOException e) {
e.printStackTrace();
}
holder.play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mP) {
mP.start();
holder.play.setVisibility(View.INVISIBLE);
holder.pause.setVisibility(View.VISIBLE);
}
});
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
});
holder.pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
holder.play.setVisibility(View.VISIBLE);
holder.pause.setVisibility(View.INVISIBLE);
}
});
}
#Override
public int getItemCount() {
return songs.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView play , pause;
TextView fileName, date;
public ViewHolder(#NonNull View itemView) {
super(itemView);
play = itemView.findViewById(R.id.play);
pause= itemView.findViewById(R.id.pause);
fileName = itemView.findViewById(R.id.fileName);
pause.setVisibility(View.INVISIBLE);
date = itemView.findViewById(R.id.date);
}
}
} // the code end
Date of all the audio files are same in the list
This is ModalClass.java
public class ModelClass {
String path,filename;
Uri uri;
Long date;
public ModelClass(String path, String filename, Uri uri, Long date) {
this.path = path;
this.filename = filename;
this.date = date;
this.uri = uri;
}
public ModelClass() {
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public Uri getUri() {
return uri;
}
public void setUri(Uri uri) {
this.uri = uri;
}
public Long getDate() {
return date;
}
public void setDate(Long date) {
this.date = date;
}
}
Long dateTime = modelClass.getDate()
You did not post the code for getDate() while there starts your problem.
It problably returns 0 for all files.
And 0 equals 20 Jan 1970.
Related
I am working on a chat application and I am having some problems displaying the chat messages. For storage I'm using a Room database and in order to display the messages I'm using a RecyclerView. The problem is that the activity gets very slow and not so responsive on scrolling through messages.
Here is my code:
ChatActivity.java
public class ChatActivity extends AppCompatActivity {
public static final String TAG = ChatActivity.class.getSimpleName();
public static Contact contact;
public static boolean isContactConnected;
private CircleImageView mContactPicture;
private ImageView mContactConnected;
private TextView mContactName;
private TextView mContactStatus;
private ChatAdapter mChatAdapter;
private RecyclerView mRecyclerView;
private EmojiconEditText mUserMessageInput;
private View rootView;
private ImageView emojiImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
initializeToolbar();
String contactPhone = Objects.requireNonNull(getIntent().getStringExtra("phone"));
contact = MainActivity.db.getContactDao().findByPhone(contactPhone);
if (MainActivity.notificationMessages.get(contact.getId()) != null) {
MainActivity.notificationMessages.put(contact.getId(), new ArrayList<Message>());
}
updateUI(contact);
initializeViews();
initializeRecyclerView();
EmojIconActions emojIconActions = new EmojIconActions(this, rootView, mUserMessageInput, emojiImageView);
emojIconActions.ShowEmojIcon();
emojIconActions.setIconsIds(R.drawable.ic_baseline_keyboard_24, R.drawable.ic_baseline_emoji_emotions_24);
mChatAdapter = new ChatAdapter(this, new ArrayList<Message>());
mRecyclerView.setAdapter(mChatAdapter);
MainActivity.db.getMessageDao().getLiveMessages(contactPhone).observe(this, new Observer<List<Message>>() {
#Override
public void onChanged(List<Message> newMessages) {
mChatAdapter.setMessages(newMessages);
mRecyclerView.scrollToPosition(newMessages.size() - 1);
}
});
}
[...]
private void updateUI(Contact contact) {
mContactName.setText(contact.getName());
if (!contact.isConnected()) {
Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.US);
isContactConnected = false;
mContactStatus.setText(
String.format(
"Last seen %s",
DateManager.getLastActiveText(
df.format(currentTime),
contact.getLastActive()
)
)
);
mContactConnected.setVisibility(View.GONE);
Log.d(TAG, "updateUI: initialized contact UI as disconnected");
} else {
mContactStatus.setText(R.string.active_now);
mContactConnected.setVisibility(View.VISIBLE);
isContactConnected = true;
Log.d(TAG, "updateUI: initialized contact UI as connected");
}
if (contact.getPhotoUri() != null) {
Uri imageUri = Uri.parse(contact.getPhotoUri());
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
mContactPicture.setImageBitmap(bitmap);
Log.d(TAG, "updateUI: loaded contact photo from device");
} catch (IOException e) {
Toast.makeText(
ChatActivity.this,
"Failed to load image from device.",
Toast.LENGTH_SHORT
).show();
e.printStackTrace();
}
}
}
[...]
private void initializeRecyclerView() {
mRecyclerView = findViewById(R.id.chat_recycler_view);
RecyclerView.LayoutManager layoutManager =
new LinearLayoutManager(ChatActivity.this, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(layoutManager);
Log.d(TAG, "initializeRecyclerView: initialized RecyclerView");
}
[...]
}
AppDatabase.java
#Database(entities = {Contact.class, Message.class}, version = 1)
#TypeConverters({Converters.class})
public abstract class AppDatabase extends RoomDatabase {
public abstract ContactDao getContactDao();
public abstract MessageDao getMessageDao();
}
MessageDao.java
#Dao
public interface MessageDao {
#Query("SELECT * FROM messages WHERE to_from = :contact ORDER BY timestamp")
List<Message> getMessages(String contact);
#Query("SELECT * FROM messages WHERE to_from = :contact ORDER BY timestamp")
LiveData<List<Message>> getLiveMessages(String contact);
#Query("SELECT * FROM messages WHERE to_from =:contact AND status = 0")
List<Message> getUndeliveredMessages(String contact);
#Query("SELECT * FROM messages WHERE payloadId = :payloadId LIMIT 1")
Message getMessageByPayloadId(long payloadId);
#Query("SELECT * FROM messages WHERE to_from = :contact ORDER BY timestamp DESC LIMIT 1")
Message getLastMessage(String contact);
#Query("SELECT * FROM messages WHERE to_from = :contact ORDER BY timestamp DESC LIMIT 1")
LiveData<Message> getLastLiveMessage(String contact);
#Query("DELETE FROM messages")
void deleteAllMessages();
#Insert
void addMessage(Message message);
#Update
void updateMessage(Message message);
#Delete
void deleteMessage(Message message);
}
ChatAdapter.java
public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private List<Message> messages;
public ChatAdapter(Context context, List<Message> messages) {
this.mContext = context;
this.messages = messages;
}
#Override
public int getItemViewType(int position) {
Message message = messages.get(position);
int status = message.getStatus();
if (status == Message.RECEIVED) {
return 0;
} else {
return 1;
}
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == 0) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_message_item, parent, false);
return new ChatUserViewHolder(itemView);
}
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.chat_message_item2, parent, false);
return new ChatOtherViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
Message currentMessage = messages.get(position);
String messageContent = currentMessage.getContent();
Date date = currentMessage.getTimestamp();
SimpleDateFormat ft = new SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.US);
Date currentDate = Calendar.getInstance().getTime();
switch (getItemViewType(position)) {
case 0:
ChatUserViewHolder mHolder = (ChatUserViewHolder) holder;
Contact sender = MainActivity.db.getContactDao().findByPhone(currentMessage.getToFrom());
if (sender.getPhotoUri() != null) {
Uri imageUri = Uri.parse(sender.getPhotoUri());
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), imageUri);
mHolder.getSenderProfilePicture().setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
mHolder.getSenderName().setText(sender.getName());
mHolder.getMessageContent().setText(messageContent);
mHolder.getTimestamp().setText(DateManager.getLastActiveText(ft.format(currentDate), ft.format(date)));
break;
case 1:
ChatOtherViewHolder nHolder = (ChatOtherViewHolder) holder;
SharedPreferences sharedPreferences = mContext.getSharedPreferences("LOGIN_DETAILS", MODE_PRIVATE);
String name = sharedPreferences.getString("name", "");
String photoUri = sharedPreferences.getString("photoUri", null);
if (photoUri != null) {
Uri imageUri = Uri.parse(photoUri);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), imageUri);
nHolder.getSenderProfilePicture().setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
nHolder.getSenderName().setText(name);
nHolder.getMessageContent().setText(messageContent);
nHolder.getTimestamp().setText(DateManager.getLastActiveText(ft.format(currentDate), ft.format(date)));
if (currentMessage.getStatus() == Message.SENT) {
nHolder.getMessageStatus().setImageResource(R.drawable.ic_baseline_done_24);
} else {
nHolder.getMessageStatus().setImageResource(R.drawable.ic_baseline_done_all_24);
}
break;
default:
break;
}
}
#Override
public int getItemCount() {
return messages.size();
}
public void setMessages(List<Message> messages) {
if (this.messages.size() > 0) {
this.messages.clear();
}
this.messages = messages;
notifyDataSetChanged();
}
ChatItemViewHolder.java
class ChatItemViewHolder extends RecyclerView.ViewHolder {
private CircleImageView mUserProfilePic;
private ImageView mUserStatus;
private TextView mUserProfileName;
private EmojiconTextView mLastMessage;
private TextView mTimestamp;
public ChatItemViewHolder(#NonNull View itemView) {
super(itemView);
mUserProfilePic = itemView.findViewById(R.id.contact_image_item);
mUserProfileName = itemView.findViewById(R.id.contact_name_item);
mUserStatus = itemView.findViewById(R.id.status);
mLastMessage = itemView.findViewById(R.id.contact_status_item);
mTimestamp = itemView.findViewById(R.id.timestamp);
}
public CircleImageView getUserProfilePic() {
return mUserProfilePic;
}
public ImageView getUserStatus() {
return mUserStatus;
}
public TextView getUserProfileName() {
return mUserProfileName;
}
public EmojiconTextView getLastMessage() {
return mLastMessage;
}
public TextView getTimestamp() {
return mTimestamp;
}
}
ChatOtherViewHolder.java
class ChatOtherViewHolder extends RecyclerView.ViewHolder {
private CircleImageView mSenderProfilePicture;
private TextView mSenderName;
private EmojiconTextView mMessageContent;
private TextView mTimestamp;
private ImageView mMessageStatus;
public ChatOtherViewHolder(#NonNull View itemView) {
super(itemView);
mSenderProfilePicture = itemView.findViewById(R.id.sender_profile_pic);
mSenderName = itemView.findViewById(R.id.sender_name);
mMessageContent = itemView.findViewById(R.id.message_content);
mTimestamp = itemView.findViewById(R.id.message_timestamp);
mMessageStatus = itemView.findViewById(R.id.message_status);
}
public CircleImageView getSenderProfilePicture() {
return mSenderProfilePicture;
}
public TextView getSenderName() {
return mSenderName;
}
public EmojiconTextView getMessageContent() {
return mMessageContent;
}
public TextView getTimestamp() {
return mTimestamp;
}
public ImageView getMessageStatus() {
return mMessageStatus;
}
}
Clearly the problem comes from the RV. Initially I thought that the observe method running on the UI thread could be causing problems, but I replaced the action in the onChanged method and the UI is very smooth, so the problem occurs only when I try updating the RV items.
What can I do to solve this issue?
There are two big issues I see
Never do database calls in your adapter, database calls are too expensive to use in there.
You are also loading entire bitmaps into memory, use an image loading library like Glide to load images, they handle recycled view and resizing the image to what they need to be along with asynchronous loading
I want to know that, How can I use the Url to set the background of a particular view.
Something like this:
TextView someview;
someview.setbackground(url).
Suppose I am getting that URL from Firebase Database through a getter method in my model class.
Can someone help me clearly understand this...
Actually I am trying to load user status from Firebase node that I have created.
Below is the whole code and explanation:
The problem is in adapter class, and I commented there please check...
The Node I want to achieve from firebase:
Model class for that node:
package com.example.sociapp;
public class Status {
String backgrounduri, date, fullname, profileimage, e, time, uid, userstatus;
long textcolor, textsize;
public Status ( )
{
}
public Status(String backgrounduri, String date, String fullname, String profileimage, long textcolor, long textsize, String time, String uid, String userstatus)
{
this.backgrounduri = backgrounduri;
this.date = date;
this.fullname = fullname;
this.profileimage = profileimage;
this.textcolor = textcolor;
this.textsize = textsize;
this.time = time;
this.uid = uid;
this.userstatus = userstatus;
}
public String getBackgrounduri() {
return backgrounduri;
}
public void setBackgrounduri(String backgrounduri) {
this.backgrounduri = backgrounduri;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getProfileimage() {
return profileimage;
}
public void setProfileimage(String profileimage) {
this.profileimage = profileimage;
}
public long getTextcolor() {
return textcolor;
}
public void setTextcolor(long textcolor) {
this.textcolor = textcolor;
}
public long getTextsize() {
return textsize;
}
public void setTextsize(long textsize) {
this.textsize = textsize;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getUserstatus() {
return userstatus;
}
public void setUserstatus(String userstatus) {
this.userstatus = userstatus;
}
}
Below is the adapter class:
public class StatusAdapter extends RecyclerView.Adapter<StatusAdapter.viewHolder> {
java.util.List<String> statuskeyList;
List<Status> SList;
Context context;
DatabaseReference ClickstatusRef;
FirebaseAuth mAuth;
public StatusAdapter(List<String> statuskeyList, List<Status> SList, Context context)
{
this.statuskeyList = statuskeyList;
this.SList = SList;
this.context = context;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.all_user_status_layout, parent, false);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull viewHolder holder, int position) {
Status status = SList.get(position);
String statusKey = statuskeyList.get(position);
mAuth = FirebaseAuth.getInstance();
final String CurrentUserId = mAuth.getCurrentUser().getUid();
Picasso.get().load(status.getProfileimage()).placeholder(R.drawable.profile).into(holder.Profileimage);
holder.FullName.setText(status.getFullname());
holder.Date.setText(status.getDate());
holder.Time.setText(status.getTime());
holder.UserStatus.setText(status.getUserstatus());
ClickstatusRef = FirebaseDatabase.getInstance().getReference().child("Status").child(statusKey);
/* String name = status.getBackgrounduri();
int id = context.getResources().getIdentifier(name, "drawable", context.getPackageName());
Drawable drawable = context.getResources().getDrawable(id);*/
try {
int status_background = Integer.parseInt(status.getBackgrounduri());
holder.UserStatus.setBackgroundResource(status_background);
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
//I tried all the code for setting background commented and not commented but no use
//The problem is here, and here I am setting background Url that I am getting from firebase. I tried all the code you can see in here commented and none commented
// holder.UserStatus.setBackground(context.getResources().getDrawable(context.getResources().getIdentifier("SociApp", "getBackground",context.getPackageName())));
int status_color = (int) status.getTextcolor();
holder.UserStatus.setTextColor(status_color);
int Text_Size = (int) status.getTextsize()/ 3 ;
holder.UserStatus.setTextSize(Text_Size);
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
ClickstatusRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
String statusUserId = dataSnapshot.child("uid").getValue().toString();
if (statusUserId.equals(CurrentUserId))
{
View mview = LayoutInflater.from(context).inflate(R.layout.dialog_layout, null);
TextView Message = mview.findViewById(R.id.dialog_text);
Button OkBtn = mview.findViewById(R.id.dialog_btn);
AlertDialog.Builder mbuilder = new AlertDialog.Builder(context, R.style.mydialog);
mbuilder.setView(mview);
String message = "Do you want to delete your status!";
Message.setText(message);
OkBtn.setText("Do it");
OkBtn.setWidth(100);
final Dialog dialog = mbuilder.create();
dialog.show();
OkBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ClickstatusRef.removeValue();
dialog.dismiss();
SendUserToLoadstatusActivity();
}
});
}
else
{
Toast.makeText(context, "You just long clicked the status", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return true;
}
});
}
private void SendUserToLoadstatusActivity()
{
Intent MainIntent = new Intent(context, LoadStatusActivity.class);
MainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(MainIntent);
}
#Override
public int getItemCount()
{
return SList.size();
}
public class viewHolder extends RecyclerView.ViewHolder{
private CircleImageView Profileimage;
private TextView FullName;
private TextView Date,Time;
private TextView UserStatus;
public viewHolder(#NonNull View itemView)
{
super(itemView);
Profileimage = itemView.findViewById(R.id.status_profile_image);
FullName = itemView.findViewById(R.id.status_user_name);
Date = itemView.findViewById(R.id.status_date);
Time = itemView.findViewById(R.id.status_time);
UserStatus = itemView.findViewById(R.id.all_user_status);
}
}
}
Below I am passing data to arraylists from LoadStatusActivity:
public class LoadStatusActivity extends AppCompatActivity {
private Toolbar mtoolbar;
private TextView UserStatusButton;
private RecyclerView StatusList;
private ProgressBar ProgressCircular;
private DatabaseReference StatusRef;
private FirebaseAuth mAuth;
private List<Status> mUserStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_load_status);
mtoolbar = findViewById(R.id.status_page_toolbar);
setSupportActionBar(mtoolbar);
mAuth = FirebaseAuth.getInstance();
StatusList = (RecyclerView) findViewById(R.id.all_users_status_list);
ProgressCircular = (ProgressBar) findViewById(R.id.status_progress_circular);
StatusRef = FirebaseDatabase.getInstance().getReference().child("Status");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Status");
UserStatusButton = findViewById(R.id.status_post_btn);
mUserStatus = new ArrayList();
final List<String> Keys = new ArrayList<>();
StatusList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
StatusList.setLayoutManager(linearLayoutManager);
UserStatusButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SendUserToStatusPostActivity( );
}
});
Query sortStatusInDescendantOrder = StatusRef.orderByChild("counter");
sortStatusInDescendantOrder.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
mUserStatus.clear();
if (dataSnapshot.exists()) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Keys.add(dataSnapshot1.getKey());
Status status = dataSnapshot1.getValue(Status.class);
mUserStatus.add(status);
}
StatusAdapter statusAdapter = new StatusAdapter( Keys, mUserStatus, LoadStatusActivity.this);
StatusList.setAdapter(statusAdapter);
ProgressCircular.setVisibility(View.INVISIBLE);
} else {
Toast.makeText(LoadStatusActivity.this, "There is no post Exists! " + DatabaseError.PERMISSION_DENIED, Toast.LENGTH_SHORT).show();
ProgressCircular.setVisibility(View.INVISIBLE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void SendUserToStatusPostActivity() {
Intent StatusPostIntent = new Intent(LoadStatusActivity.this, StatusPostActivity.class);
startActivity(StatusPostIntent);
}
}
The Output I am getting:
but I want text with background not only text.and that background url is saved in backgrounduri as shown in first picture at the top. how to load it.
You have to download the Bitmap from the given URL and set this Bitmap as the background Drawable of your TextView.
To download the Bitmap you have to add internet permission to your AndroidManifest.xml.
You can download your Bitmap from the given url like this:
try {
// create url from string
URL url = new URL(imageUrl);
// connect to url
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
// download image
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
# return myBitmap or do something else
} catch (IOException e) {
e.printStackTrace();
return null;
}
To set this Bitmap as background of your TextView you have to convert it to a Drawable first by using:
// create drawable from bitmap
Drawable dr = new BitmapDrawable(myBitmap);
myTextView.setBackground(dr);
I found the answer from above link in comment.
For my problem I solved it by adding the below code in my adapter class at the place I commented above:
Code peace I needed:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url = new URL(status.backgrounduri);
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
Drawable dr = new BitmapDrawable(image);
holder.UserStatus.setBackgroundDrawable(dr);
} catch(IOException e) {
System.out.println(e);
}
int status_color = (int) status.getTextcolor();
holder.UserStatus.setTextColor(status_color);
int Text_Size = (int) status.getTextsize()/ 3 ;
holder.UserStatus.setTextSize(Text_Size);
We can do this by downloading the URL in String formate then convert it into Bitmap and then Convert that bitmap into drawable formate and set as background through the use of setbackground(the drawable);
I'm developing an Android app using Google Sheets as a database.
I have information about books in a Google Sheet (title, author, cover, date, etc). I want to retrieve this information and show it in a "Listview" in the "Spreadsheets" Activity. I created a "BookItem" object and an "BookAdapter" adapter. In the "Spreadsheets.java" I have the read method, called "getDataFromApi()". I know that this method works, but I don't know how to adapt it to my "BookAdapter" and show the information on the ListView.
This is mi code:
public class BookItem {
static String title_item;
static Drawable cover_item; //probar con String
public BookItem(String title, Drawable cover){
super();
this.title_item = title;
this.cover_item = cover;
}
public String getTitle() {
return title_item;
}
public void setTitle(String title){
this.title_item = title;
}
public static Drawable getCover() {
return cover_item;
}
public void setCover(Drawable cover) {
this.cover_item = cover;}
This is my BookAdapter:
public class BookAdapter extends BaseAdapter {
private ArrayList<BookItem> items;
List<BookItem> items;
private Context context;
public BookAdapter (Context context, List<BookItem> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public BookItem getItem(int position) {
return this.items.get(position);
}
#Override
public long getItemId(int i) {
return 0;
}
private static class ViewHolder {
public final ImageView cover_item;
public final TextView title_item;
public ViewHolder (ImageView cover_item, TextView title_item){
this.cover_item = cover_item;
this.title_item = title_item;
}
}
#Override
public View getView (int position, View view, ViewGroup viewGroup) {
ImageView cover_item;
TextView title_item;
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.fila_lista_miestanteria, viewGroup, false); //se mete aqui en getView por ser baseAdapter
title_item = (TextView) view.findViewById(R.id.book_title_item);
cover_item = (ImageView) view.findViewById(R.id.book_cover_item);
view.setTag(R.id.book_title_item, title_item);
view.setTag(R.id.book_cover_item, cover_item);
}
else {
cover_item = (ImageView) view.getTag(R.id.book_cover_item);
title_item = (TextView)view.getTag(R.id.book_title_item);
}
BookItem bookItem = getItem(position);
cover_item.setImageDrawable(bookItem.getCover());
title_item.setText(bookItem.getTitle());
return view;
}
}
public class Spreadsheets extends Activity {
static String book_title, book_author, book_date, book_category, book_description, book_rating, book_cover;
static String read_only = "no";
static String book_favorite = "no";
static GoogleAccountCredential mCredential;
private ListView bookList;
private TextView mOutputText;
ProgressDialog mProgress;
Context context;
List<String> rst;
List<BookItem> resultados;
BookAdapter adapter;
private static final String[] SCOPES = {SheetsScopes.SPREADSHEETS};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spread);
// mOutputText = (TextView) findViewById(R.id.outputText);
bookList = (ListView) findViewById(R.id.bookList);
// mOutputText.setText("");
mProgress = new ProgressDialog(this);
mProgress.setMessage("Calling Google Sheets...");
// Initialize credentials and service object.
mCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
System.out.print("read only es igual a "+ read_only);
new MakeRequestTask(mCredential).execute();
}
public void rellenar(){
System.out.println("VOY A HACER NEW BOOK ADAPTER ");
adapter = new BookAdapter(context, resultados);
bookList.setAdapter(adapter);
System.out.println("SETADAPTER");
}
private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
private Exception mLastError = null;
MakeRequestTask(GoogleAccountCredential credential) {
}
#Override
protected List<String> doInBackground(Void... params) {
try {
if(read_only.equals("no")) {
setDataToApi();
return null;
}
else {
return getDataFromApi();
}
} catch (Exception e) {
mLastError = e;
cancel(true);
return null;
}
}
private List<String> getDataFromApi() throws IOException {
String range = "Sheet1!A1:H";
List<String> results = new ArrayList<String>();
ValueRange response = CreateSpreadsheets.mService.spreadsheets().values()
.get(CreateSpreadsheets.spreadsheet_id, range)
.execute();
List<List<Object>> values = response.getValues();
if (values != null) {
for (List row : values) {
results.add(row.get(0) + ", " + row.get(7));
}
}
//funcion();
return results;
}
private void setDataToApi() throws IOException {
String range = "Sheet1!A2:H";
List<List<Object>> values = new ArrayList<>();
List<Object> data1 = new ArrayList<>();
data1.add(book_title);
data1.add(book_author);
data1.add(book_date);
data1.add(book_category);
data1.add(book_description);
data1.add(book_rating);
data1.add(book_cover);
data1.add("a");
values.add(data1);
ValueRange valueRange = new ValueRange();
valueRange.setMajorDimension("ROWS");
valueRange.setRange(range);
valueRange.setValues(values);
ValueRange body = new ValueRange().setValues(values);
AppendValuesResponse response =
CreateSpreadsheets.mService.spreadsheets().values().append(CreateSpreadsheets.spreadsheet_id, range, body)
.setValueInputOption("RAW")
.execute();
}
#Override
protected void onPreExecute() {
//mOutputText.setText("");
mProgress.show();
}
#Override
protected void onPostExecute(List<String> output) {
mProgress.hide();
if (output == null || output.size() == 0) {
// mOutputText.setText("No results returned.");
} else {
if(read_only.equals("no")) {
Intent intent = new Intent(Spreadsheets.this, MainActivity.class);
startActivity(intent);
// mOutputText.setText("Se ha añadido un libro a su lista");
}
else {
System.out.println("VOY A RELLENAR LA LISTA");
rellenar();
}
}
}
#Override
protected void onCancelled() {
}
}
}
The "spread.xml" is a list, and the "fila_list_miestanteria.xml" is a TextView&ImageView to show the book info.
Thank you so much!
I have create the recycerview and this recycerview display the Person image ,person name and + button when i have press + button change the button image like true.and after recycerview bottom one button this button click all data show the next activity..
My Adapter
public class BuildCustomAdapter extends RecyclerView.Adapter<BuildCustomAdapter.MyViewHolder> implements Filterable {
private List<People> peopleList;
private List<People> peopleListCopy;
private ItemFilter mFilter = new ItemFilter();
public BuildCustomAdapter(List<People> buildList) {
this.peopleList = buildList;
this.peopleListCopy = new ArrayList<>();
peopleListCopy.addAll(buildList);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.build_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
People people = peopleList.get(position);
byte[] decodedString = Base64.decode(people.getPeopleImage(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
holder.ivPeopleImage.setImageBitmap(decodedByte);
holder.tvPersonName.setText(people.getPeopleName());
holder.button.setSelected(people.isSelected());
holder.button.setOnClickListener(new onSelectListener(position));
}
#Override
public int getItemCount() {
return peopleList.size();
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ItemFilter();
}
return mFilter;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
// public ImageView ivPeopleImage;
public TextView tvPersonName;
public Button button;
public CircularImageView ivPeopleImage;
public MyViewHolder(View itemView) {
super(itemView);
ivPeopleImage = (CircularImageView) itemView.findViewById(R.id.ivPerson);
tvPersonName = (TextView) itemView.findViewById(R.id.tvPersonName);
button = (Button) itemView.findViewById(R.id.addbn);
}
}
private class ItemFilter extends Filter {
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
List<People> filterList = new ArrayList<>();
for (int i = 0; i < peopleListCopy.size(); i++) {
if ((peopleListCopy.get(i).getPeopleName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
People peopleName = peopleListCopy.get(i);
filterList.add(peopleName);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = peopleListCopy.size();
results.values = peopleListCopy;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
peopleList = (List<People>) results.values;
notifyDataSetChanged();
}
}
private class onSelectListener implements View.OnClickListener {
int mPosition;
public onSelectListener(int position) {
mPosition = position;
}
#Override
public void onClick(View view) {
view.setSelected(!view.isSelected());
People people = peopleList.get(mPosition);
people.setSelected(!people.isSelected());
notifyDataSetChanged();
}
}
Activity
public class BulidActivity extends AppCompatActivity {
private List<People> peopleList = new ArrayList<>();
private List<People> peopleListCopy = new ArrayList<>();
private RecyclerView recyclerView;
private BuildCustomAdapter buildCustomAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bulid);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
BuildData();
peopleListCopy.addAll(peopleList);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
buildCustomAdapter = new BuildCustomAdapter(peopleList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(buildCustomAdapter);
AddTxt();
BtnBuildNow();
}
private void BtnBuildNow() {
Button btnnuildnow = (Button) findViewById(R.id.btn_build_now);
btnnuildnow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BulidActivity.this, AlertList.class);
startActivity(intent);
}
});
}
private void AddTxt() {
EditText editTxt = (EditText) findViewById(R.id.etSearch);
editTxt.setTextColor(Color.WHITE);
editTxt.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.setFocusable(true);
v.setFocusableInTouchMode(true);
return false;
}
});
editTxt.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() <= 0) {
peopleList.clear();
peopleList.addAll(peopleListCopy);
recyclerView.setAdapter(null);
buildCustomAdapter = new BuildCustomAdapter(peopleList);
recyclerView.setAdapter(buildCustomAdapter);
} else {
buildCustomAdapter.getFilter().filter(s.toString());
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private List<People> BuildData() {
DataBaseHelper db = new DataBaseHelper(getApplicationContext());
try {
db.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
if (db.open()) {
peopleList = db.getPeople();
}
return peopleList;
}
Model class
public class People implements Serializable {
private String peopleImage;
private String peopleName;
private boolean selected;
public void setPeopleName(String peopleName) {
this.peopleName = peopleName;
}
public String getPeopleName() {
return peopleName;
}
public void setPeopleImage(String peopleImage) {
this.peopleImage = peopleImage;
}
public String getPeopleImage() {
return peopleImage;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
DatabaseHelper.class
public class DataBaseHelper extends SQLiteOpenHelper {
private static final String DB_PATH = "/data/data/databasename/databases/";
private static final String DB_NAME = "alertme.db";
private final String TABLE_PEOPLE = "people";
private final String TABLE_CATEGORY = "category";
private final String CATEGORY_NAME = "name";
private final String ID = "id";
private final String CATEGORY_ID = "category_id";
private final String PEOPLE_IMAGE = "image";
private final String PEOPLE_NAME = "name";
private SQLiteDatabase myDataBase;
private final Context myContext;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public boolean open() {
try {
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
return true;
} catch (SQLException sqle) {
myDataBase = null;
return false;
}
}
public List<People> getPeople(String category_id) {
List<People> peoples = new ArrayList<>();
try {
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery("select * from people where category_id = " + category_id, null);
while (cursor.moveToNext()) {
String peopleName = cursor.getString(cursor.getColumnIndex(PEOPLE_NAME));
String peopleImage = cursor.getString(cursor.getColumnIndex(PEOPLE_IMAGE));
People people = new People();
people.setPeopleName(peopleName);
people.setPeopleImage(peopleImage);
peoples.add(people);
}
} catch (Exception e) {
Log.d("DB", e.getMessage());
}
return peoples;
}
public List<Category> getCategory() {
List<Category> categoryList = new ArrayList<>();
try {
String query = " SELECT * FROM " + TABLE_CATEGORY;
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery(query, null);
while (cursor.moveToNext()) {
int categoryID = cursor.getInt(cursor.getColumnIndex(ID));
String categoryName = cursor.getString(cursor.getColumnIndex(CATEGORY_NAME));
Category category = new Category();
category.setId(categoryID);
category.setCategoryName(categoryName);
categoryList.add(category);
}
} catch (Exception e) {
Log.d("DB", e.getMessage());
}
return categoryList;
}
#Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
First you should implement Serializable interface in your Build model class like this :-
public class Build implements Serializable{
//Content will be as it is
}
Change your clickListener like this :-
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build.setSelected(!build.isSelected());
if (build.isSelected()) {
holder.button.setBackgroundResource(R.drawable.selected_true_icon_new);
Intent intent = new Intent(context, youractivity.class)
intenet.putExtra("build",build);
context.startActivity(intent);
} else
holder.button.setBackgroundResource(R.drawable.add_button_icon);
}
});
In the onCreate method of receiving activity write this :-
Build build = (Build) getIntent().getSerializableExtra("build");
Add Intent in below Method,
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
build.setSelected(!build.isSelected());
if (build.isSelected()) {
holder.button.setBackgroundResource(R.drawable.selected_true_icon_new);
Intent intent = new Intent(context, youractivity.class)
intenet.putExtra("key","value");
context.startActivity(intent);
} else
holder.button.setBackgroundResource(R.drawable.add_button_icon);
}
});
Huge mistak that you register to the click event on your ViewHolder! you will get diffrent position from the actual because when android use notifyItemMoved the viewBindHolder will not be called and than you got the wrong position.
and in the click listener implementation you should pass Intent with your data
I tried to add textwatcher with filter class but it do not work plz help. I get the json array through the server using the url. the search(filter) doesnt work well.
public class CallDetails extends Activity {
SessionManager session;
ArrayList<Drivers> driverList = new ArrayList<Drivers>();
private List<Drivers> driverlist = null;
ListView listview;
ImageButton btback;
DriverAdapter dadapter;
String uid;
String name;
String email;
String odtyp;
static String oid;
Drivers driver;
private EditText editTextFilter;
private static String OUTBOX_URL ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calldetails);
Intent i = getIntent();
oid =i.getStringExtra("orderId");
odtyp =i.getStringExtra("ordertype");
OUTBOX_URL ="http://www.gdrive.com/api/calldetails.php?id="+oid;
//managing session...
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
name = user.get(SessionManager.KEY_NAME);
email = user.get(SessionManager.KEY_EMAIL);
uid = user.get(SessionManager.KEY_UID);
btback =(ImageButton)findViewById(R.id.btnBack);
btback.setVisibility(View.INVISIBLE);
// Locate the EditText in listview_main.xml
editTextFilter = (EditText)findViewById(R.id.editTextFilter);
editTextFilter.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
String text = editTextFilter.getText().toString().toLowerCase(Locale.getDefault());
dadapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3){ /* to do*/ }
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) { /*to do*/ }
});
//populating view with data...
//driverList = new ArrayList<Drivers>();
new JSONAsyncTask().execute(OUTBOX_URL);
listview = (ListView)findViewById(R.id.drlist);
dadapter = new DriverAdapter(CallDetails.this, R.layout.list_item, driverList);
listview.setItemsCanFocus(false);
listview.setAdapter(dadapter);
//populating list ends
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), driverList.get(position).getName(), Toast.LENGTH_LONG).show();
}
});
}
public void back(View v){
Intent back = new Intent(getApplicationContext(), SafetyDrive.class);
startActivity(back);
finish();
}
private class DriverAdapter extends ArrayAdapter<Drivers> {
Context context;
int Resource;
LayoutInflater inflater;
ArrayList<Drivers> driverList = new ArrayList<Drivers>();
public DriverAdapter(Context context, int layoutResourceId,ArrayList<Drivers> drs) {
super(context, layoutResourceId, drs);
//inflater = ((Activity) context).getLayoutInflater();
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = layoutResourceId;
driverList = drs;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//Log.d("in ", "view start");
View item = convertView;
DriverWrapper DriverWrapper = null;
if (item == null) {
DriverWrapper = new DriverWrapper();
item = inflater.inflate(Resource, null);
DriverWrapper.ename = (TextView) item.findViewById(R.id.textName);
DriverWrapper.ephone = (TextView) item.findViewById(R.id.textPhone);
DriverWrapper.mkcall = (ImageButton) item.findViewById(R.id.btnphone);
item.setTag(DriverWrapper);
} else {
DriverWrapper = (DriverWrapper) item.getTag();
}
Drivers driver = driverList.get(position);
DriverWrapper.ename.setText("Name: " + driver.getName());
DriverWrapper.ephone.setText("Phone: " + driver.getPhone());
final String dp = driver.getPhone().trim();
DriverWrapper.mkcall.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//making call..
//Log.e("no is", dp);
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" +dp));
//callIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(callIntent);
//finish();
}
});
return item;
}
class DriverWrapper {
TextView ename;
TextView ephone;
ImageButton mkcall;
//ImageButton msg;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
driverList.clear();
if (charText.length() == 0) {
driverList.addAll(driverList);
} else {
for (Drivers driver : driverList) {
if (driver.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
driverList.add(driver);
}
}
}
notifyDataSetChanged();
}
}
class JSONAsyncTask extends AsyncTask {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(CallDetails.this);
dialog.setMessage("Loading, please wait");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//Log.d("in at-", "asynctask");
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("drivers");
if(jarray.length()!=0){
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
Drivers driver = new Drivers();
driver.setPhone(object.getString("phone"));
driver.setName(object.getString("emp_name"));
driverList.add(driver);
}
}else{
driver = new Drivers();
driver.setPhone(" ");
driver.setName(" No Driver Place yet");
driverList.add(driver);
}
return true;
}
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
btback.setVisibility(View.VISIBLE);
dadapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
}
}
public class Drivers {
private String name;
private String phone;
public Drivers() {
}
public Drivers(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
actually it wont filter because youve cleared the driverList and then in the else statement you loop to driverList which is already empty. the only thing you can do is create a backup list for the driversList and then use the backup list to get all data for filtering to the driverList.
Example Here:
// here is the backuplist
ArrayList<Drivers> backupList = new ArrayList<Drivers>();
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
// actually its easy to just clear the backup list
// but due to reasons where users press backspace you have to load backup list only once
if(backupList.isEmpty()) {
backupList.addAll(driverList);
}
driverList.clear();
if (charText.length() == 0) {
driverList.addAll(backupList);
} else {
for (Drivers driver : backupList) {
if (driver.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
driverList.add(driver);
}
}
}
notifyDataSetChanged();
}
Hope it helps :)