How to use setbackground property with URL - java

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);

Related

The date of audio file is same for all audio file

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.

Android Recycler view cannot return more than 8 items

I am having this issue for some time now, when I retrieved data from a database using volley and then show it in a recycler view, if the items are 8 or less than 8 then it shows them without any problem, but if I retrieve more than 8 items from database then the activity closes/crashes and goes back to the main activity. I don't get any error in the run console in android studio. I am retrieving 3 things from database for a single item, 2 strings and an image. I don't think the error is in the php file which is used to get the data as that I have checked and it retrieves without any issue. I have searched android documentation of recycler view but couldn't find anything
NOTE: I am getting image as string and then converting to bitmap.
if there is anything else needed then I can provide them without any issue.
the code is below:
Method which is used to call the recycler view activity which has problems.
public void onViewAttendanceButtonClick(int position, String courseCode,
String courseName, String batchName) {
if (MainActivity.teacherData != null) {
seeAttendanceDetails(MainActivity.teacherData.getEmail(),courseCode,
batchName, courseName, getDateAndTime);
}
}
private void seeAttendanceDetails(final String email,final String
courseCode, final String batchName,final String courseName, final String
date) {
StringRequest stringRequest = new StringRequest(Request.Method.POST,
seeAttendanceDetails, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject data = jsonArray.getJSONObject(i);
String fullName = data.getString("full_name");
String Email = data.getString("email");
String photo = data.getString("photo");
Toast.makeText(CoursesActivity.this, courseCode,
Toast.LENGTH_LONG).show();
Attendance attendance1 = new Attendance(fullName, Email, photo);
attendanceArrayList.add(attendance1);
}
if (!attendanceArrayList.isEmpty()) {
Intent intent = new Intent(CoursesActivity.this,
ShowAttendanceActivity.class);
Bundle bundle = new Bundle();
bundle.putString("attendanceCourseCode",
courseCode);
bundle.putString("attendanceCourseName",
courseName);
bundle.putString("attendanceBatchName", batchName);
bundle.putSerializable("attendanceList",
attendanceArrayList);
intent.putExtras(bundle);
startActivity(intent);
}
else if (RegistrationActivity.teacherData != null) {
//
seeAttendanceDetails(RegistrationActivity.teacherData.getEmail(),
batchName,courseName, getDateAndTime);
// Toast.makeText(CoursesActivity.this,"No Record
Found",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(CoursesActivity.this,
error.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}) {
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("batch", batchName);
params.put("date", date);
params.put("courseCode",courseCode);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
<br/>
The recycler view activity code
public class ShowAttendanceActivity extends AppCompatActivity implements
ShowAttendanceActivityAdapter.RemoveAttendanceClickListener {
private RecyclerView recyclerView;
private String courseCode,courseName,batchName;
private ArrayList<Attendance> attendanceArrayList = new ArrayList<>();
private TextView
textViewCourseCode,textViewCourseName,textViewBatchName;
private String deleteStudentAttendance =
"https://asuiot.umargulzar.com/Teacher%20API%2
0Files/deleteStudentattendance.php";
int success;
private String TAG_SUCCESS = "success";
private String TAG_MESSAGE = "message";
private String getDateAndTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_attendance);
recyclerView = findViewById(R.id.attendance_details_recyclerView);
textViewCourseCode = findViewById(R.id.SA_textView_course_code);
textViewCourseName = findViewById(R.id.SA_textView_course_name);
textViewBatchName = findViewById(R.id.SA_textView_Batch);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL,false);
recyclerView.setLayoutManager(layoutManager);
Calendar calendar = Calendar.getInstance();
// SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyy hh:mm:ss a");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd");
String dateTime = simpleDateFormat.format(calendar.getTime());
this.getDateAndTime = dateTime;
courseCode = (String) getIntent().getStringExtra("attendanceCourseCode");
courseName = (String) getIntent().getStringExtra("attendanceCourseName");
batchName = (String) getIntent().getStringExtra("attendanceBatchName");
attendanceArrayList = (ArrayList<Attendance>) getIntent().getExtras().getSerializable("attendanceList");
textViewCourseCode.setText(courseCode);
textViewCourseName.setText(courseName);
textViewBatchName.setText(batchName);
recyclerView.setAdapter(new ShowAttendanceActivityAdapter(attendanceArrayList,this));
}
#Override
public void onRemoveAttendanceClick(int position,String email) {
// Toast.makeText(ShowAttendanceActivity.this,"The Email of Student:"+email,Toast.LENGTH_LONG).show();
if(MainActivity.teacherData !=null){
deleteStudentAttendance(email,getDateAndTime,courseCode);
}
}
private void deleteStudentAttendance(final String email, final String getDateAndTime,final String courseCode) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, deleteStudentAttendance, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
success = jsonObject.getInt(TAG_SUCCESS);
if (success == 1) {
Toast.makeText(ShowAttendanceActivity.this, jsonObject.getString(TAG_MESSAGE)+" Plz refresh the page.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ShowAttendanceActivity.this, jsonObject.getString(TAG_MESSAGE), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("Email", email);
params.put("Date",getDateAndTime);
params.put("CourseCode",courseCode);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
the recycler view activity adapter
public class ShowAttendanceActivityAdapter extends RecyclerView.Adapter<ShowAttendanceActivityAdapter.AttendanceView> {
private ArrayList<Attendance> attendanceData;
Bitmap bitmap;
private RemoveAttendanceClickListener removeAttendanceClickListener;
public ShowAttendanceActivityAdapter(ArrayList<Attendance> attendanceData,RemoveAttendanceClickListener removeAttendanceClickListener){
this.attendanceData = attendanceData;
this.removeAttendanceClickListener = removeAttendanceClickListener;
}
#NonNull
#Override
public AttendanceView onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_attendance_data,parent,false);
return new AttendanceView(view,removeAttendanceClickListener);
}
#Override
public void onBindViewHolder(#NonNull AttendanceView holder, int position) {
Attendance attendance = attendanceData.get(position);
holder.textViewName.setText(attendance.getStudentName());
// holder.textViewEmail.setText(attendance.getStudentEmail());
holder.textViewEmail.setText(attendance.getStudentEmail());
decodeStringToImage(attendance.getStudentPhoto());
holder.imageViewPhoto.setImageBitmap(bitmap);
}
#Override
public int getItemCount() {
return attendanceData.size();
}
public void decodeStringToImage(String photo) {
// Bitmap bitmap = photo.
byte[] bytes = Base64.decode(photo, Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
public class AttendanceView extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textViewName, textViewEmail;
ImageView imageViewPhoto;
Button buttonRemoveCourse;
RemoveAttendanceClickListener removeAttendanceClickListener;
public AttendanceView(#NonNull View itemView,RemoveAttendanceClickListener removeAttendanceClickListener) {
super(itemView);
textViewName = itemView.findViewById(R.id.textView_name);
textViewEmail = itemView.findViewById(R.id.textView_Email);
imageViewPhoto = itemView.findViewById(R.id.textView_SA_Photo);
this.removeAttendanceClickListener = removeAttendanceClickListener;
buttonRemoveCourse = itemView.findViewById(R.id.btn_remove_attendance);
buttonRemoveCourse.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_remove_attendance:
removeAttendanceClickListener.onRemoveAttendanceClick(getAdapterPosition(),textViewEmail.getText().toString());
break;
}
}
}
public interface RemoveAttendanceClickListener{
void onRemoveAttendanceClick(int position,String email);
}
}
You are probably getting OutOfMemory exception while converting bytes array in to bitmap if the image sizes are huge.
Add try catch in your decodeStringToImage method where you are converting bitmaps and check the log when you load more than 8 images.

Selecting one from radio group value and scrolling down and some item selected automatically in Recycler View( beginner)

I am making an attendance system where I take the attendance using RadioGroup with two options. When I select some radio button and scroll down some other radio button gets auto-selected. If I change them upper ones also get changed.
Main class
public class TeacherAttendanceActivity extends AppCompatActivity implements AttendanceAdapter.AttendanceAdapterListner {
public static TeacherAttendanceActivity teacherAttendanceActivity;
private static final String TAG = TeacherAttendanceActivity.class.getSimpleName();
List<AttendanceModel> listItems;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private AttendanceAdapter attendanceAdapter;
ProgressDialog progressDialog;
private SQLiteHandler db;
private SessionManager session;
private SearchView searchView;
Button btnSubmit;
JSONObject mainObj = new JSONObject();
// date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String currentDateandTime = sdf.format(new Date());
String class_id,title;
Boolean Error;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teacher_attendance);
//get data from intent
class_id = super.getIntent().getExtras().getString("id"); //class_id
title = super.getIntent().getExtras().getString("title");
getSupportActionBar().setTitle("Class: "+title+", Date: "+currentDateandTime );
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
btnSubmit=findViewById(R.id.buttonAttendanceSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Error=false;
Gson gson=new Gson();
final String newDataArray=gson.toJson(listItems); // dataarray is list aaray
for (int i = 0; i < AttendanceAdapter.listItems.size(); i++){
if(AttendanceAdapter.listItems.get(i).getAttendance()==null){
Toast.makeText(TeacherAttendanceActivity.this, "Check attendance at roll:"+AttendanceAdapter.listItems.get(i).getRoll(), Toast.LENGTH_SHORT).show();
Error =true;
break;
}
}
if (!Error){
request(class_id,currentDateandTime,newDataArray);
}
}
});
listItems = new ArrayList<>();
attendanceAdapter = new AttendanceAdapter(listItems, this, (AttendanceAdapter.AttendanceAdapterListner) this);
recyclerView = (RecyclerView) findViewById(R.id.list_attendance);
recyclerView.setLayoutManager(new LinearLayoutManager(TeacherAttendanceActivity.this));
progressDialog = new ProgressDialog(this);
teacherAttendanceActivity = this;
//refresh_list(class_id);
}
#Override
protected void onStart() {
refresh_list(class_id);
super.onStart();
}
#Override
public void onAttendanceAdapterSelected(AttendanceModel model) {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.refresh, menu);
getMenuInflater().inflate(R.menu.tool_bar, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.action_settings:
Toast.makeText(getApplicationContext(),"Sittings",Toast.LENGTH_LONG).show();
return true;
case R.id.action_logout:
logoutUser();
return true;
case R.id.action_about:
Toast.makeText(getApplicationContext(),"About",Toast.LENGTH_LONG).show();
return true;
case R.id.action_devinfo:
Toast.makeText(getApplicationContext(),"Dev info",Toast.LENGTH_LONG).show();
return true;
case R.id.refresh:
refresh_list(class_id);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
// refresh list
public void refresh_list(String id) {
// this method refresh list and get the json data
listItems.clear();
// adapter = new MyAdapter(listItems,getApplicationContext());
recyclerView.setAdapter(attendanceAdapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());
progressDialog.setMessage("Loading");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, ApiConfig.URL_TEACHER_ATTENDANCE+id, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
progressDialog.hide();
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("Data"); // finding data
Log.d(TAG, String.valueOf(jsonObject));
int len = jsonArray.length();
for (int i = 0; i < len; i++) {
JSONObject o = jsonArray.getJSONObject(i);
AttendanceModel item = new AttendanceModel(
o.getString("id"),
o.getString("name"),
o.getString("roll"),
o.getString("class_id"),
o.getString("status"),
null
);
listItems.add(item);
//adapter = new MyAdapter(listItems,getApplicationContext());
recyclerView.setAdapter(attendanceAdapter); // setting them in list view
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.hide();
Toast.makeText(TeacherAttendanceActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}) {
/** Passing some request headers* */
#Override
public Map getHeaders() throws AuthFailureError {
SQLiteHandler db = new SQLiteHandler(getApplicationContext());
HashMap<String,String> userDetail= db.getUserDetails();
String userToken = userDetail.get("token");
Log.d(TAG, String.valueOf(userToken));
HashMap headers = new HashMap();
headers.put("Accept", "application/json");
headers.put("Authorization", "Bearer "+userToken);
return headers;
}
};
stringRequest.setShouldCache(false);
VolleyRequest.getInstance(TeacherAttendanceActivity.this).addToRequestQueue(stringRequest);
}
// take attendance
private void request( final String classId,final String date,final String data ) {
progressDialog.setMessage("Taking attendance");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
ApiConfig.URL_TEACHER_ATTENDANCE_STORE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response);
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
String attendance = jObj.getString("Attendance");
Toast.makeText(TeacherAttendanceActivity.this, attendance, Toast.LENGTH_LONG).show();
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("message");
Toast.makeText(TeacherAttendanceActivity.this,
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(TeacherAttendanceActivity.this, "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(TeacherAttendanceActivity.this,
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
/** Passing some request headers* */
#Override
public Map getHeaders() throws AuthFailureError {
SQLiteHandler db = new SQLiteHandler(TeacherAttendanceActivity.this);
HashMap<String,String> userDetail= db.getUserDetails();
String userToken = userDetail.get("token");
Log.d(TAG, String.valueOf(userToken));
HashMap headers = new HashMap();
headers.put("Accept", "application/json");
headers.put("Authorization", "Bearer "+userToken);
return headers;
}
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("class_id", classId);
params.put("date", date);
params.put("data", data);
return params;
}
};
strReq.setShouldCache(false);
// Adding request to request queue
VolleyRequest.getInstance(TeacherAttendanceActivity.this).addToRequestQueue(strReq);
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
Model class
'model class for convenient '
public class AttendanceModel {
String id,name,roll,classId,previousAttendance,attendance;
public AttendanceModel(String id, String name,String roll, String classId,String previousAttendance,String attedance ){
this.id = id;
this.name = name;
this.classId =classId;
this.roll=roll;
this.attendance=attedance;
this.previousAttendance=previousAttendance;
}
public String getAttendance() {
return attendance;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getRoll() {
return roll;
}
public String getClassId() {
return classId;
}
public String getPreviousAttendance(){return previousAttendance;}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setRoll(String roll) {
this.roll = roll;
}
public void setClassId(String classId) {
this.classId = classId;
}
public void setPreviousAttendance(String previousAttendance) {
this.previousAttendance = previousAttendance;
}
public void setAttendance(String attendance) {
this.attendance = attendance;
}
}
Adapter class
' adapter class '
public class AttendanceAdapter extends RecyclerView.Adapter<AttendanceAdapter.ViewHolder> implements Filterable
{
// date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String currentDateandTime = sdf.format(new Date());
private static final String TAG = AttendanceAdapter.class.getSimpleName();
public static List<AttendanceModel> listItems;
private List<AttendanceModel> listItemsFiltered;
private Context context;
private ProgressDialog dialog;
private AttendanceAdapter.AttendanceAdapterListner listner;
private ProgressDialog pDialog;
private SQLiteHandler db;
public static JSONObject jo = new JSONObject();
public static JSONArray ja = new JSONArray();
public AttendanceAdapter(List<AttendanceModel> listItems, Context context, AttendanceAdapter.AttendanceAdapterListner listner) {
this.listItems = listItems;
this.listner=listner;
this.context = context;
this.listItemsFiltered =listItems;
// SqLite database handler
db = new SQLiteHandler(context);
// Progress dialog
pDialog = new ProgressDialog(context);
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
listItemsFiltered = listItems;
} else {
List<AttendanceModel> filteredList = new ArrayList<>();
for (AttendanceModel row : listItems) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getName().toUpperCase().contains(charSequence.toString().toUpperCase())||row.getName().toLowerCase().contains(charSequence.toString().toLowerCase())) {
filteredList.add(row);
}
}
listItemsFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = listItemsFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
listItemsFiltered = (ArrayList<AttendanceModel>) filterResults.values;
notifyDataSetChanged();
}
};
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView roll;
public TextView previous;
RadioGroup radioAttendance;
RadioButton radioAttendancePresent,radioAttendanceAbsent;
public CardView card_view;
public ViewHolder(View itemView) {
super(itemView);
name= (TextView) itemView.findViewById(R.id.textViewAttendanceStudentName);
roll = (TextView) itemView.findViewById(R.id.textViewAttendanceStudentRoll);
previous = (TextView) itemView.findViewById(R.id.textViewAttendanceStudentPreviousStatus);
radioAttendance = itemView.findViewById(R.id.radioAttendance);
radioAttendancePresent =itemView.findViewById(R.id.radioAttendancePresent);
radioAttendanceAbsent =itemView.findViewById(R.id.radioAttendanceAbsent);
//card_view = (CardView) itemView.findViewById(R.id.class_card_view); // card view for on click method
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View view) {
// send selected contact in callback
listner.onAttendanceAdapterSelected(listItemsFiltered.get(getAdapterPosition())); // selecting cardview and position (model)
}
});
radioAttendance.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
//Toast.makeText(TeacherAttendanceActivity.this, toString(i), Toast.LENGTH_SHORT).show();
// Toast.makeText(context,"clicked at position"+i+" "+id+""+name,Toast.LENGTH_SHORT).show();
if(radioAttendancePresent.isChecked())
{
listItems.get(getAdapterPosition()).setAttendance("present");
}
else {
listItems.get(getAdapterPosition()).setAttendance("absent");
}
}
});
}
}
#Override
public AttendanceAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.attendance_list, parent, false);
return new AttendanceAdapter.ViewHolder(v);
}
#Override
public void onBindViewHolder (final AttendanceAdapter.ViewHolder holder, final int position) {
final AttendanceModel listItem = listItemsFiltered.get(position);
holder.name.setText(listItem.getName());
holder.roll.setText(listItem.getRoll());
holder.previous.setText(listItem.getPreviousAttendance());
}
public interface AttendanceAdapterListner {
void onAttendanceAdapterSelected(AttendanceModel model); // sending cardview to say the dialoge and model for sending context
}
#Override
public int getItemCount() {
return listItemsFiltered.size();
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
Your problem would be solved by making small changes to your Recycler view adapter, please do not disable recyclable property, this makes your recycler view a glorified list view.
I can see you tried using a sparse boolean array to hold the state of the radio buttons, that is good but you do not need that too. The idea behind using a Sparse boolean array is to keep the state of each item in the recycler view so that when they are recycled you still have a reference to what the state of each item is.
In your adapter you already have something that we can use to know the state, that is the attendance property of your model, in that case, you can set the state of your checkboxes by checking if the attendance property is present or absent.
One more thing about your code is that you are using the onCheckChangedListener as a click event handler for your radio button, you should not use this because it responds to all check changed events, even if it is triggered from code and not from user action, so when you bind your view and you set any of your radio buttons as checked or unchecked, it calls this callback.
Here is a modified version of your ViewHolder class that solves this issue by applying the solution above.
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView roll;
public TextView previous;
RadioGroup radioAttendance;
RadioButton radioAttendancePresent, radioAttendanceAbsent;
public CardView card_view;
public ViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.textViewAttendanceStudentName);
roll = (TextView) itemView.findViewById(R.id.textViewAttendanceStudentRoll);
previous = (TextView) itemView.findViewById(R.id.textViewAttendanceStudentPreviousStatus);
radioAttendance = itemView.findViewById(R.id.radioAttendance);
radioAttendancePresent = itemView.findViewById(R.id.radioAttendancePresent);
radioAttendanceAbsent = itemView.findViewById(R.id.radioAttendanceAbsent);
radioAttendancePresent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
radioAttendancePresent.setChecked(true);
listItems.get(getAdapterPosition()).setAttendance("present");
}
});
radioAttendanceAbsent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
radioAttendanceAbsent.setChecked(true);
listItems.get(getAdapterPosition()).setAttendance("absent");
}
});
}
void bind(int position) {
// use the sparse boolean array to check
if (listItems.get(position).getAttendance() != null) {
if (listItems.get(position).getAttendance().equals("present")) {
radioAttendancePresent.setChecked(true);
} else if (listItems.get(position).getAttendance().equals("absent")) {
radioAttendanceAbsent.setChecked(true);
}
} else {
radioAttendance.clearCheck();
}
name.setText(listItems.get(position).getName());
roll.setText(listItems.get(position).getRoll());
previous.setText(listItems.get(position).getPreviousAttendance());
}
}
Notice that we have separate click listener for each radio button and set the state in the list of items and just check that state when we are binding, also we have removed the onCheckChangedListener and the sparse boolean array, one last thing is that we made sure that when there is not state set for the attendance property, we just clear the radio buttons so that no one is selected the code is much simpler and works correctly now.
You have to initialize your RadioButton based on model state like below:
#Override
public void onBindViewHolder (final AttendanceAdapter.ViewHolder holder, final int position) {
final AttendanceModel listItem = listItemsFiltered.get(position);
holder.name.setText(listItem.getName());
holder.roll.setText(listItem.getRoll());
holder.previous.setText(listItem.getPreviousAttendance());
final String id =listItem.getId();
final String class_id =listItem.getClassId();
holder.radioAttendance.setOnCheckedChangeListener(null);
if(listItem.getAttendance().equalsIgnoreCase("present")) {
radioAttendancePresent.setChecked(true);
} else {
radioAttendancePresent.setChecked(false);
}
//Add listener here and remove from holder
holder.radioAttendance.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
if(holder.radioAttendancePresent.isChecked()) {
listItemsFiltered.get(position).setAttendance("present");
} else {
listItemsFiltered.get(position).setAttendance("absent");
}
notifyDataSetChanged();
}
});
}

I have difficulty and run into errors while sending images messages in my app. Text messages work fine

In the chat functionality of the application, I am able to send and receive text messages. I am trying to implement where I am able to send and receive image messages and I am running into errors.
StudentChatActivity.java
public class StudentChatActivity extends AppCompatActivity {
private FirebaseListAdapter<ChatMessage> adapter;
private ListView listView;
public static String tutorID = "";
public String tutorName = "";
private String mChatUser;
private FirebaseAuth mAuth;
private DatabaseReference mRootRef;
FirebaseDatabase database;
private MessageAdapter mAdapter;
private static final int TOTAL_ITEMS_TO_LOAD = 10;
private int mCurrentPage = 1;
private static final int GALLERY_PICK = 1;
private FirebaseUser mCurrentUser;
private StorageReference mImageStorage;
private int itemPos = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Intent intt = getIntent();
Bundle b = intt.getExtras();
if (b != null) {
tutorID = (String) b.get("tutorID");
tutorName = (String) b.get("tutorName");
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
listView = (ListView) findViewById(R.id.list);
ImageButton imagebutton = (ImageButton) findViewById(R.id.image_button);
mImageStorage = FirebaseStorage.getInstance().getReference();
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String current_uid = mCurrentUser.getUid();
final EditText input = (EditText) findViewById(R.id.input1);
mRootRef.child("Chat").child(String.valueOf(mCurrentUser)).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(mChatUser)){
Map chatAddMap = new HashMap();
chatAddMap.put("seen",false);
chatAddMap.put("timestamp", ServerValue.TIMESTAMP);
Map chatUserMap = new HashMap();
chatUserMap.put("Chat/" + mCurrentUser + "/" + mChatUser, chatAddMap);
chatUserMap.put("Chat/" + mChatUser + "/" + mCurrentUser, chatAddMap);
mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null)
Log.d( "Chat_log: ", databaseError.getMessage().toString());
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
showAllOldMessages();
imagebutton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent,"SELECT IMAGE"),GALLERY_PICK);
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (input.getText().toString().trim().equals("")) {
Toast.makeText(StudentChatActivity.this, "Please enter some texts!", Toast.LENGTH_SHORT).show();
} else {
FirebaseDatabase.getInstance()
.getReference()
.push()
.setValue(
new ChatMessage(input.getText().toString(),
StudentHome.info.etFirstname,
FirebaseAuth.getInstance().getCurrentUser().getUid(),
StudentChatActivity.this.tutorName,
StudentChatActivity.this.tutorID,
FirebaseAuth.getInstance().getCurrentUser().getUid()
)
);
input.setText("");
//send notification
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
mRootRef = database.getReference();
// mAuth = FirebaseAuth.getInstance();
final EditText input = (EditText) findViewById(R.id.input1);
if(requestCode == GALLERY_PICK && resultCode == RESULT_OK){
Uri imageUri = data.getData();
final String current_user_ref = "messages/" + mCurrentUser + "/" + mChatUser;
final String chat_user_ref = "messages/" + mChatUser + "/" + mCurrentUser;
DatabaseReference user_message_push = mRootRef.child("messages").child(String.valueOf(mCurrentUser)).child(mChatUser).push();
final String push_id = user_message_push.getKey();
StorageReference filepath = mImageStorage.child("message_images").child(push_id + ".jpg");
filepath.putFile(imageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
String download_url = task.getResult().getDownloadUrl().toString();
Map messageMap = new HashMap();
messageMap.put("message",download_url);
messageMap.put("seen",false);
messageMap.put("type","image");
messageMap.put("time", ServerValue.TIMESTAMP);
messageMap.put("from",mCurrentUser);
Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref + "/" + push_id,messageMap);
messageUserMap.put(chat_user_ref + "/" + push_id,messageMap);
input.setText("");
mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null)
Log.d( "Chat_log: ", databaseError.getMessage().toString());
}
});
/* mRootRef.updateChildren(messageUserMap, databaseError, databaseReference){
if (databaseError != null){
Log.d("CHAT_LOG", databaseError.getMessage().toString());
}
}); */
}
}
});
}
}
private void showAllOldMessages() {
try {
adapter = new MessageAdapter(this, ChatMessage.class, R.layout.item_in_message,
FirebaseDatabase.getInstance().getReference());
listView.setAdapter(adapter);
} catch (Exception er) {
System.out.print(er.getMessage());
}
}
}
ChatMessage.Java
package com.rough.tuber.tuber;
import android.media.Image;
import java.util.Date;
public class ChatMessage {
private String messageText;
private String studentName;
private String studentID;
private String tutorName;
private String tutorID;
private String senderId;
private long messageTime;
public ChatMessage(String messageText, String studentName, String studentID, String tutorName, String tutorID, String senderId) {
this.messageText = messageText;
this.studentName = studentName;
this.studentID = studentID;
messageTime = new Date().getTime();
this.tutorID = tutorID;
this.tutorName = tutorName;
this.senderId = senderId;
}
public ChatMessage() {
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public String getSenderId() {
return senderId;
}
public String getTutorID() {
return tutorID;
}
public void setSenderId(String senderId) {
this.senderId = senderId;
}
public void setTutorID(String tutorID) {
this.tutorID = tutorID;
}
public String getTutorName() {
return tutorName;
}
public void setTutorName(String tutorName) {
this.tutorName = tutorName;
}
public String getMessageText() {
return messageText;
}
public void setMessageText(String messageText) {
this.messageText = messageText;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public long getMessageTime() {
return messageTime;
}
public void setMessageTime(long messageTime) {
this.messageTime = messageTime;
}
}
MessageAdapter.Java
package com.rough.tuber.tuber;
import android.text.format.DateFormat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseListAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
public class MessageAdapter extends FirebaseListAdapter<ChatMessage> {
private StudentChatActivity activity;
public MessageAdapter(StudentChatActivity activity, Class<ChatMessage> modelClass, int modelLayout, DatabaseReference ref) {
super(activity, modelClass, modelLayout, ref);
this.activity = activity;
}
#Override
protected void populateView(View v, ChatMessage model, int position) {
if (v != null) {
TextView messageText = (TextView) v.findViewById(R.id.message_text);
TextView messageUser = (TextView) v.findViewById(R.id.message_user);
TextView messageTime = (TextView) v.findViewById(R.id.message_time);
// ImageView messagaImage = (ImageView) v.fin
messageText.setText(model.getMessageText());
if (model.getSenderId() != null && model.getSenderId().equals(FirebaseAuth.getInstance().getCurrentUser().getUid())) {
messageUser.setText("You");
} else {
messageUser.setText(model.getTutorName());
}
// Format the date before showing it
messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", model.getMessageTime()));
}
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
ChatMessage chatMessage = getItem(position);
if (chatMessage.getTutorID() != null && chatMessage.getStudentID() != null && chatMessage.getSenderId() != null && chatMessage.getStudentID().equals(FirebaseAuth.getInstance().getCurrentUser().getUid()) && chatMessage.getTutorID().equals(StudentChatActivity.tutorID)) {
if (chatMessage.getSenderId() != null && chatMessage.getSenderId().equals(FirebaseAuth.getInstance().getCurrentUser().getUid())
)
view = activity.getLayoutInflater().inflate(R.layout.item_out_message, viewGroup, false);
else
view = activity.getLayoutInflater().inflate(R.layout.item_in_message, viewGroup, false);
//generating view
populateView(view, chatMessage, position);
return view;
}
view = activity.getLayoutInflater().inflate(R.layout.item_empty, viewGroup, false);
return view;
}
#Override
public int getViewTypeCount() {
// return the total number of view types. this value should never change
// at runtime
return 2;
}
#Override
public int getItemViewType(int position) {
// return a value between 0 and (getViewTypeCount - 1)
return position % 2;
}
}
I am receiving this error.
This the error message.
FATAL EXCEPTION: main
Process: com.rough.tuber.tuber, PID: 3931
java.lang.NullPointerException: Attempt to invoke interface method 'int java.lang.CharSequence.length()' on a null object reference
at java.util.regex.Matcher.reset(Matcher.java:1052)
at java.util.regex.Matcher.(Matcher.java:180)
at java.util.regex.Pattern.matcher(Pattern.java:1006)
at com.google.android.gms.internal.zzelv.zzqh(Unknown Source:2)
at com.google.firebase.database.DataSnapshot.hasChild(Unknown Source:12)
at com.rough.tuber.tuber.StudentChatActivity$1.onDataChange(StudentChatActivity.java:92)
at com.google.android.gms.internal.zzegf.zza(Unknown Source:13)
at com.google.android.gms.internal.zzeia.zzbyc(Unknown Source:2)
at com.google.android.gms.internal.zzeig.run(Unknown Source:71)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Firebase enter image description hereenter image description here
On your onCreate() method, you are calling valueEventListener on mRootRef though you have not initialized it. Also database path should be from 'current_uid' as per your database structure.
Instead of initializing mRootRef on onActivityResult initialize it on onCreateMethod():
.......
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
........
mRootRef = FirebaseDatabase.getInstance().getReference();
.......
mRootRef.child("Chat").child(current_uid)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
.........
Update
Updated for your persisting error.
From your error log its clear.
com.google.firebase.database.DatabaseException: Invalid Firebase
Database path: com.google.firebase.auth.internal.zzh#329c22b. Firebase
Database paths must not contain '.', '#', '$', '[', or ']'
Your Database path is containing some non expected characters in path. you need to avoid that .
So print your database path and ensure that there is no any '.', '#', '$', '[', or ']'

Custom Adapter with Search Not working

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 :)

Categories