i work about a vtc app and I need to display on the main screen the orders of the client.
I chose the way of customing the list view with an adapter but when i launch the app nothing on the screen except the title of the page.
i divided the adapter code and the fragment code (yeah i work in a fragment) and i want to have your opinion about my code.
Here the Fragment :
package com.cmn.cmnvtc;
import android.Manifest;
import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainPageFragment1 extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private LinearLayout containerView;
private TextView NoCommand;
private UserLocalStore userLocalStore;
private List<Courses> coursesList;
private ListView lvCourses;
private CoursesAdapter coursesAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main1, container, false);
userLocalStore = new UserLocalStore(getActivity());
NoCommand = (TextView) v.findViewById(R.id.NoCommand);
lvCourses = (ListView) v.findViewById(R.id.lvCourses);
coursesList = new ArrayList<>();
final Response.Listener<String> responseListener = new Response.Listener<String>(){
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
if(success){
int count = jsonObject.getInt("count");
for(int i=0; i<count; i++) {
JSONObject obj = jsonObject.getJSONObject(String.valueOf(i));
String origin = obj.getString("origin");
String destination = obj.getString("destination");
String date_depart = obj.getString("date_depart");
String heure_depart = obj.getString("heure_depart");
int nb_passagers = Integer.parseInt(obj.getString("nb_passagers"));
float prix = Float.parseFloat(obj.getString("prix"));
String mode_paiement = obj.getString("paiement");
String etat_paiement = obj.getString("course_payee");
Courses course = new Courses(origin, destination, date_depart, heure_depart, nb_passagers, prix
, mode_paiement, etat_paiement);
coursesList.add(course);
}
}else{
NoCommand.setEnabled(true);
NoCommand.setText("Oups... Vous n'avez commandé aucune course pour le moment.");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
User currentUser = userLocalStore.getLoggedInUser();
final GetAllCourseRequest getAllCourse = new GetAllCourseRequest(currentUser.user_id,responseListener);
RequestQueue queue = Volley.newRequestQueue(getActivity());
queue.add(getAllCourse);
coursesAdapter = new CoursesAdapter(getActivity(), coursesList);
lvCourses.setAdapter(coursesAdapter);
lvCourses.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(), "CLicked", Toast.LENGTH_SHORT).show();
}
});
if (googleServicesAvailable()) {
containerView = (LinearLayout) v.findViewById(R.id.containerView);
askForPermission();
}
return v;
}
public boolean googleServicesAvailable() {
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int isAvaibable = api.isGooglePlayServicesAvailable(getActivity());
if (isAvaibable == ConnectionResult.SUCCESS) {
return true;
} else if (api.isUserResolvableError(isAvaibable)) {
Dialog dialog = api.getErrorDialog(getActivity(), isAvaibable, 0);
dialog.show();
} else {
Toast.makeText(getActivity(), "Can't connect to play services", Toast.LENGTH_SHORT).show();
}
return false;
}
private void explain() {
Snackbar.make(containerView, "Cette permission est nécessaire pour vous géolocalisez", Snackbar.LENGTH_LONG).setAction("Activer", new View.OnClickListener() {
#Override
public void onClick(View view) {
askForPermission();
}
}).show();
}
private void askForPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 2) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(permissions[0]) == false) {
displayOptions();
} else {
explain();
}
}
if (grantResults[1] == PackageManager.PERMISSION_GRANTED) {
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(permissions[1]) == false) {
displayOptions();
} else {
explain();
}
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void displayOptions() {
Snackbar.make(containerView, "Vous avez désactivé la permission", Snackbar.LENGTH_LONG).setAction("Paramètres", new View.OnClickListener() {
#Override
public void onClick(View view) {
final Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
final Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
}).show();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
My custom adapter :
package com.cmn.cmnvtc;
import android.content.Context;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.List;
/**
* Created by Wild Shadow on 18/06/2017.
*/
public class CoursesAdapter extends BaseAdapter {
private List<Courses> coursesList;
private Context ctx;
public CoursesAdapter(Context context, List<Courses> coursesList) {
this.ctx = context;
this.coursesList = coursesList;
}
#Override
public int getCount() {
return coursesList.size();
}
#Override
public Object getItem(int position) {
return coursesList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = View.inflate(ctx, R.layout.row_courses, null);
TextView adrOrigin = (TextView) v.findViewById(R.id.adrOriginList);
TextView adrDestinaiton = (TextView)
v.findViewById(R.id.adrDestList);
TextView dateDepart = (TextView) v.findViewById(R.id.dateDepList);
TextView heureDepart = (TextView)
v.findViewById(R.id.heureDepList);
ImageButton viewDetails = (ImageButton)
v.findViewById(R.id.viewDetailsCourse);
adrOrigin.setText(coursesList.get(position).getOrigin());
adrDestinaiton.setText(coursesList.get(position).getDestination());
dateDepart.setText(coursesList.get(position).getDate_depart());
heureDepart.setText(coursesList.get(position).getHeure_depart());
return v;
}
}
the model layout :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="6dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_depart_courselist"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/adrOriginList"
android:textSize="17dp"
android:textColor="#000"
android:paddingTop="3dp"
android:text=" : Adresse de départ"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_destination_courselist"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/adrDestList"
android:paddingTop="3dp"
android:textColor="#000"
android:textSize="17dp"
android:text=" : Adresse d'arrivée"
android:layout_marginBottom="5dp"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_date_depart_courselist"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/dateDepList"
android:paddingTop="3dp"
android:textColor="#000"
android:textSize="17dp"
android:text=" : date de départ"
android:layout_marginBottom="3dp"
android:layout_marginRight="20dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_heure_dep_courselist"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/heureDepList"
android:paddingTop="3dp"
android:textColor="#000"
android:textSize="17dp"
android:text=" : Heure"
android:layout_marginBottom="3dp"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_details_courselist"
android:layout_marginLeft="65dp"
android:id="#+id/viewDetailsCourse"
android:paddingTop="5dp"
android:background="?android:selectableItemBackground"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
and the listview :
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="10dp"
android:theme="#style/AppTheme"
tools:context="com.cmn.cmnvtc.MainPageFragment1">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:id="#+id/TitleListCommand"
android:textSize="25dp"
android:layout_marginBottom="15dp"
android:textColor="#727574"
android:text="Liste de mes courses "/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/TitleListCommand"
android:layout_alignParentStart="true"
android:id="#+id/lvCourses"></ListView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:textColor="#969696"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:textSize="15dp"
android:textAlignment="center"
android:id="#+id/NoCommand"
android:text=""
android:enabled="false"/>
</RelativeLayout>
</ScrollView>
I hope you will help me to find the error and if you want more, try to explain me how i can optimize my code. TY
You should call notifyDataSetChanged() in the ResponseListener after filling your list.
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
if(success){
int count = jsonObject.getInt("count");
for(int i=0; i<count; i++) {
...
coursesList.add(course);
}
//notify adapter about change in data
coursesAdapter.notifyDataSetChanged();
}else{
NoCommand.setEnabled(true);
NoCommand.setText("Oups... Vous n'avez commandé aucune course pour le moment.");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Related
I want to create an activity to search for users by full name. I created everything I needed and it worked properly, except for one thing. When I press search button the result are not show in recyclerview. I need to go back and the the results are shown. I need to do these 2 steps to see the results.
Yes the search bar and view holder are overlap, I will try to fixed later. Do you know how to make it so that once searched the results are displayed immediately without having to go back
This is my layout for view holder
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="75dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:id="#+id/parent_layout"
android:background="#drawable/recycler_view_border">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/imageProfile"
android:layout_width="60dp"
android:layout_height="60dp"
android:tint="#808080"
android:layout_marginStart="10dp"
android:layout_marginTop="7dp"
app:civ_border_color="#color/dark_blue"
app:civ_border_width="2dp"
app:srcCompat="#drawable/defaultimage"/>
<TextView
android:id="#+id/userFullName"
android:layout_toEndOf="#+id/imageProfile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_marginEnd="20dp"
android:layout_marginStart="10dp"
android:gravity="center"
android:text="#string/fullname"
android:textSize="16sp"
android:textColor="#color/black"/>
<com.google.android.material.button.MaterialButton
android:id="#+id/buttonAdd"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginTop="13dp"
android:layout_marginEnd="10dp"
android:layout_marginStart="340dp"
android:background="#drawable/btn_background"
app:cornerRadius="8dp"
android:drawableTop="#drawable/ic_action_add" />
</RelativeLayout>
This is my layout for activity
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SendFriendRequests">
<LinearLayout
android:id="#+id/linearlayout"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginLeft="13dp"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="#+id/searchUsername"
android:layout_width="318dp"
android:layout_height="45dp"
android:layout_marginTop="20dp"
android:background="#drawable/edt_background"
android:hint="#string/searchFriends"
android:imeOptions="actionNext"
android:importantForAutofill="no"
android:inputType="text"
android:paddingStart="16dp"
android:paddingEnd="16dp" />
<com.google.android.material.button.MaterialButton
android:id="#+id/buttonSearch"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginStart="333dp"
android:layout_marginTop="-47dp"
android:layout_marginEnd="10dp"
android:background="#drawable/btn_background"
android:drawableTop="#drawable/ic_action_search"
app:cornerRadius="8dp" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="580dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearlayout"
app:layout_constraintVertical_bias="0.99"
tools:layout_editor_absoluteX="-16dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is my adapter
package com.example.chatappjava;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.mikhaellopez.circularimageview.CircularImageView;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
public class SendFriendRequestAdapter extends RecyclerView.Adapter<SendFriendRequestAdapter.ViewHolder> {
private static final String TAG = "ContactsAdapter";
private ArrayList<UserData> arrayListUserData = new ArrayList<>();
private Context context;
public SendFriendRequestAdapter(ArrayList<UserData> arrayListUserData, Context context) {
this.arrayListUserData = arrayListUserData;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_send_friend_request_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, #SuppressLint("RecyclerView") int position) {
Log.d(TAG, "onBindViewHolder: called.");
Glide.with(context)
.asBitmap()
.load(arrayListUserData.get(position).image)
.into(holder.userProfileImage);
holder.userFullName.setText(arrayListUserData.get(position).name);
holder.buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Connection conn = DatabaseConnection.createDatabaseConnection();
PreparedStatement st1 = conn.prepareStatement(
" insert into FRIEND_REQUESTS values (?,?,?)");
st1.setString(1, arrayListUserData.get(position).friendId);
st1.setString(2, arrayListUserData.get(position).userId);
st1.setInt(3, 0);
st1.execute();
showToast("Friend request is sended");
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("IdAccount", arrayListUserData.get(position).userId);
context.startActivity(intent);
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context.getApplicationContext(), specificchat.class);
intent.putExtra("userId", arrayListUserData.get(position).userId);
intent.putExtra("friendId", arrayListUserData.get(position).friendId);
intent.putExtra("friendName", arrayListUserData.get(position).name);
intent.putExtra("friendImage", arrayListUserData.get(position).image);
context.startActivity(intent);
}
});
}
private void showToast(String message) {
Toast.makeText(context.getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
return arrayListUserData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircularImageView userProfileImage;
TextView userFullName;
RelativeLayout parentLayout;
Button buttonAdd;
public ViewHolder(View itemView) {
super(itemView);
userProfileImage = itemView.findViewById(R.id.imageProfile);
userFullName = itemView.findViewById(R.id.userFullName);
parentLayout = itemView.findViewById(R.id.parent_layout);
buttonAdd = itemView.findViewById(R.id.buttonAdd);
}
}
}
And this is my java class which use the adapter
package com.example.chatappjava;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class SendFriendRequests extends AppCompatActivity {
private ArrayList<UserData> arrayListUserData = new ArrayList<>();
private Button searchButton;
private EditText searchUsername;
private String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
userId = intent.getStringExtra("IdAccount");
setContentView(R.layout.activity_send_friend_request);
searchButton = findViewById(R.id.buttonSearch);
searchUsername = findViewById(R.id.searchUsername);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Connection conn = DatabaseConnection.createDatabaseConnection();
Statement statement = conn.createStatement();
ResultSet resultat = statement.executeQuery("select ID, FULLNAME, IMAGE from USERS where ID not in (select FRIEND_ID from FRIENDSLIST where USER_ID = " + userId + ") and FULLNAME like '%" + searchUsername.getText().toString() + "%' and ID not in (select RECEIVER_ID from FRIEND_REQUESTS where SENDER_ID = " + userId + ")");
while (resultat.next()) {
arrayListUserData.add(new UserData(resultat.getString("FULLNAME"), resultat.getString("IMAGE"), resultat.getString("ID"), userId));
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
initRecycleView();
}
});
}
private void initRecycleView() {
RecyclerView recyclerView = findViewById(R.id.recyclerView);
SendFriendRequestAdapter adapter = new SendFriendRequestAdapter(arrayListUserData, this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
I think it's the RecyclerView in your XML that needs to be adjusted at android:layout_height = "0dp"
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearlayout"/>
> I have used MVVM to backup my data when screen orientation changes,
> the data loads perfectly but when i set the data to the adapter class
> recylerview goes empty even when onbind and getItem count gets called.
first i thought my data not getting loaded but then i tracked the data loads and everything goes fine but recycler view shows no view inside it.
**ConsumerListActivit.java**
package com.conformiz.riderapp.Activities.ConsumersList;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.transition.Visibility;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import com.conformiz.riderapp.Adapters.CustomerListAdapter;
import com.conformiz.riderapp.Model.CustomersList.CustomersListRootResponseData;
import com.conformiz.riderapp.Model.CustomersList.CustomersListRootResponseDataProductList;
import com.conformiz.riderapp.R;
import com.conformiz.riderapp.Utilities.SharedPreferenceUtil;
import com.facebook.shimmer.Shimmer;
import com.facebook.shimmer.ShimmerFrameLayout;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
import android.widget.EditText;
public class ConsumerListActivity extends AppCompatActivity {
public static final String TAG = "ConsumersListActivity";
private RecyclerView rvCustomersList;
private Toolbar consumersListToolbar;
private ArrayList<CustomersListRootResponseData> customersListData = new ArrayList<CustomersListRootResponseData>();
private CustomerListAdapter customerListAdapter;
private ProgressDialog progressDialog;
private EditText etSearchCustomers;
private ShimmerFrameLayout customersListShimmer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consumer_list);
setFrontEnd();
final ConsumerListViewModel consumerListViewModel = ViewModelProviders.of(this).get(ConsumerListViewModel.class);
consumerListViewModel.setUserId(String.valueOf(SharedPreferenceUtil.getInstance(this).getUserId()));
consumerListViewModel.getCustomersList().observe(this, new Observer<ArrayList<CustomersListRootResponseData>>() {
#Override
public void onChanged(ArrayList<CustomersListRootResponseData> customersListRootResponseData) {
Log.d(TAG, "OnChaned: "+new Gson().toJson(customersListRootResponseData).toString());
if (customersListRootResponseData == null) {
Snackbar emptyData = Snackbar.make(findViewById(R.id.activity_consumer),
R.string.no_data_found_string, Snackbar.LENGTH_SHORT);
emptyData.show();
} else {
customersListData = customersListRootResponseData;
customerListAdapter.addDataToList(customersListData);
}
}
});
consumerListViewModel.getLoadingStatus().observe(this, new Observer<Boolean>() {
#Override
public void onChanged(Boolean aBoolean) {
if(aBoolean == true){
// showProgress();
customersListShimmer.setVisibility(View.VISIBLE);
customersListShimmer.startShimmer();
rvCustomersList.setVisibility(View.GONE);
}
else{
// hideProgress();
if(customersListShimmer.getVisibility() == View.VISIBLE) {
customersListShimmer.stopShimmer();
customersListShimmer.setVisibility(View.GONE);
rvCustomersList.setVisibility(View.VISIBLE);
}
}
}
});
}
private void setFrontEnd()
{
//Setting Shimmer Layout
customersListShimmer = findViewById(R.id.customersListShimmer);
//Setting Search Edit Text
etSearchCustomers = findViewById(R.id.etSearchClient);
etSearchCustomers.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
customerListAdapter.getFilter().filter(charSequence);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
//Setting tool bar
consumersListToolbar = findViewById(R.id.topToolbar);
consumersListToolbar.setTitle("Customers List");
consumersListToolbar.setTitleTextColor(Color.WHITE);
consumersListToolbar.setNavigationIcon(R.drawable.ic_back_arrow);
consumersListToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
consumersListToolbar.setElevation(10f);
}
//Setting Recycler View
rvCustomersList = findViewById(R.id.consumerListRv);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
rvCustomersList.setLayoutManager(layoutManager);
//Setting Adapter
customerListAdapter = new CustomerListAdapter(customersListData);
rvCustomersList.setAdapter(customerListAdapter);
Log.d(TAG,"Initializing the front end");
}
private void showProgress(){
progressDialog = new ProgressDialog(ConsumerListActivity.this);
progressDialog.setMessage("Getting Data....");
progressDialog.setCancelable(false);
progressDialog.show();
}
private void hideProgress(){
if(progressDialog != null){
progressDialog.dismiss();
}
progressDialog = null;
}
}
**ConsumerListAdapter.java**
package com.conformiz.riderapp.Adapters;
import android.content.Context;
import android.opengl.Visibility;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import com.conformiz.riderapp.Model.CustomersList.CustomersListRootResponseData;
import com.conformiz.riderapp.Model.CustomersList.CustomersListRootResponseDataProductList;
import com.conformiz.riderapp.R;
import com.conformiz.riderapp.ViewHolders.CustomerListVH;
import com.conformiz.riderapp.ViewHolders.ProductsVH;
import com.conformiz.riderapp.ViewHolders.ProductsViewHolder;
import java.util.ArrayList;
import java.util.List;
import java.util.function.IntToLongFunction;
import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class CustomerListAdapter extends RecyclerView.Adapter<CustomerListVH> implements Filterable {
private List<CustomersListRootResponseData> customersListData = new ArrayList<>();
private List<CustomersListRootResponseData> customersListDataFull;
private RecyclerView customersProductsRv;
Context context;
public CustomerListAdapter(List<CustomersListRootResponseData> mList) {
this.customersListData = mList;
customersListDataFull = new ArrayList<>(this.customersListData);
}
#NonNull
#Override
public CustomerListVH onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_assignment, parent, false);
CustomerListVH customerListVH = new CustomerListVH(view);
return customerListVH;
}
#Override
public void onBindViewHolder(#NonNull final CustomerListVH holder, final int position) {
Log.d("onbinding", "HERE");
final CustomersListRootResponseData customerData = customersListData.get(position);
//Setting Child's Adapter Class for Customers Orders Product //
// ClientsProductsPerCountListAdapter clientsProductsPerCountListAdapter = new ClientsProductsPerCountListAdapter(customerData.getProductList(), position);
// holder.getRvCustomersProducts().setAdapter(clientsProductsPerCountListAdapter);
// LinearLayoutManager layoutManager = new LinearLayoutManager(context, RecyclerView.VERTICAL, false);
// holder.getRvCustomersProducts().setLayoutManager(layoutManager);
//
holder.getTvCustomerName().setText(customerData.getFullname());
holder.getTvCustomerAddress().setText(customerData.getAddress().trim());
holder.getTvCustomerPhone().setText(customerData.getCell_no_1());
holder.getEditProductIV().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.getRvCustomersProducts().getVisibility() == View.VISIBLE) {
holder.getRvCustomersProducts().setVisibility(View.GONE);
} else {
holder.getRvCustomersProducts().setVisibility(View.VISIBLE);
}
}
}
);
}
#Override
public int getItemCount() {
return this.customersListData.size();
}
public void addDataToList(ArrayList<CustomersListRootResponseData> customersListData) {
if (customersListData != null && customersListData.size() > 0) {
this.customersListData.clear();
this.customersListData.addAll(customersListData);
this.notifyDataSetChanged();
}
}
#Override
public Filter getFilter() {
return customersListFilter;
}
private Filter customersListFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
List<CustomersListRootResponseData> filteredList = new ArrayList<>();
if (charSequence == null || charSequence.length() == 0) {
filteredList.addAll(customersListDataFull);
} else {
String filterPattern = charSequence.toString().toLowerCase().trim();
for (CustomersListRootResponseData data : customersListDataFull) {
if (data.getFullname().toLowerCase().contains(filterPattern) || data.getAddress().toLowerCase().contains(filterPattern)) {
filteredList.add(data);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = filteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
customersListData.clear();
customersListData.addAll((List) filterResults.values);
notifyDataSetChanged();
}
};
}
This is the row_assignment.xml which i am inflating in the oncreateViewholder
inside the adapter class this is the layout which wasn't working to load on landscape mode. But i have now created a new resource with landscape and copied the same code from the row_assignment.xml and it worked. I am not sure why it wasn't working because by default android would have picked up the simple row_assignment.xml even if the row_assignment.xml (landscape) wasn't present.
row_assignment.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/margin_2dp">
<androidx.cardview.widget.CardView
android:id="#+id/container"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv_customer_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:text="TextView"
android:textStyle="bold"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
app:layout_constraintEnd_toStartOf="#+id/tv_customer_phone"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tv_customer_phone"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:text="TextView"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
android:textColor="#color/liteBlueColor"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/tv_customer_address"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:maxLines="1"
android:text="TextView"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Small"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tv_customer_name" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/constraintLayout3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toTopOf="#+id/rvCustomersProducts"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tv_customer_address"
>
<ImageView
android:id="#+id/iv_payments"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/iv_product_edit"
app:layout_constraintTop_toTopOf="parent"
android:background="#drawable/ic_payment_true" />
<ImageView
android:id="#+id/iv_product_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
app:layout_constraintEnd_toStartOf="#+id/iv_payments"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/iv_not_delivered_tick"
app:layout_constraintTop_toTopOf="parent"
android:background="#drawable/ic_edit" />
<ImageView
android:id="#+id/iv_not_delivered_tick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
app:layout_constraintEnd_toStartOf="#+id/iv_product_edit"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/iv_delivered_tick"
app:layout_constraintTop_toTopOf="parent"
android:background="#drawable/ic_not_deliver"/>
<ImageView
android:id="#+id/iv_delivered_tick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:background="#drawable/ic_deliver"
app:layout_constraintEnd_toStartOf="#+id/iv_not_delivered_tick"
app:layout_constraintHorizontal_bias="0.07"
app:layout_constraintHorizontal_chainStyle="packed"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvCustomersProducts"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/constraintLayout3"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
I have created the CreateEvent.java module to upload the data to firebase. But how to retrieve the data and show in the Cardlist? For example show in the xml file below. And also if there was more than 1 data in firebase, how to show in with multiple cardlist that I have created in the xml file?
CreateEvent.java
package com.example.edward.eventmanagementsystem.ManageEvent;
import android.Manifest;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.edward.eventmanagementsystem.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import static android.widget.Toast.LENGTH_SHORT;
public class CreateEvent extends Activity {
private static final String TAG = "activity_create_event";
private Uri filePath;
private TextView mDisplayDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;
private DatabaseReference mDatabaseReference;
private Button mRegisterButton;
EditText mEventNameText, mContactNumText, mEventLocationText;
TextView mEventDate;
RadioGroup mEventType;
FirebaseStorage storage;
StorageReference storageRef,imageRef;
ProgressDialog progressDialog;
UploadTask uploadTask;
Uri uriImage = Uri.parse("com.example.edward.eventmanagementsystem.ManageEvent/"+ R.drawable.ic_launcher_background);
public static final int PICK_IMAGE = 1;
ImageView mimageToUpload;
#Override
protected void onCreate(Bundle savedInstanceState) {
FirebaseDatabase firebaseDatabase;
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("ListEventInformation").push();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_event);
mRegisterButton = (Button)findViewById(R.id.btnRegisterEvent);
storage = FirebaseStorage.getInstance();
storageRef = storage.getReference();
mDisplayDate = (TextView) findViewById(R.id.RegisterEventStartDate);
mDisplayDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(
CreateEvent.this,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
mDateSetListener,
year, month, day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
month = month + 1;
Log.d(TAG, "onDateSet: date: mm/dd/yyyy: " + month + "/" + day + "/" + year);
String date = month + "/" + day + "/" + year;
mDisplayDate.setText(date);
}
};
//perform action upload image
mimageToUpload = (ImageView) findViewById(R.id.imageToUpload);
//insert data to database
mEventNameText = (EditText) findViewById(R.id.RegisterEventName);
mContactNumText = (EditText) findViewById(R.id.RegisterContactNumber);
mEventDate = (TextView) findViewById(R.id.RegisterEventStartDate);
mEventType = (RadioGroup) findViewById(R.id.RegisterEventRadiogroup);
mEventLocationText = (EditText) findViewById(R.id.RegisterEventLocation);
mimageToUpload = (ImageView) findViewById(R.id.imageToUpload);
mRegisterButton = (Button) findViewById(R.id.btnRegisterEvent);
mimageToUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(CreateEvent.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
selectPdf();
}
else {
ActivityCompat.requestPermissions(CreateEvent.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},9);
}
}
});
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedId = mEventType.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton)findViewById(selectedId);
final String name = mEventNameText.getText().toString().trim();
final String contact = mContactNumText.getText().toString().trim();
final String date = mEventDate.getText().toString().trim();
final String type = radioButton.getText().toString().trim();
final String location = mEventLocationText.getText().toString().trim();
if (TextUtils.isEmpty(name)) {
mEventNameText.setError("Enter First Name!");
return;
}
if (TextUtils.isEmpty(date)) {
mEventDate.setError("Enter Date!");
return;
}
if (TextUtils.isEmpty(type)) {
radioButton.setError("Enter Phone Number!");
return;
}
if(isValidPhone(contact)){
Toast.makeText(getApplicationContext(),"Phone number is valid",Toast.LENGTH_SHORT).show();
}else {
mContactNumText.setError("Phone number is not valid");
Toast.makeText(getApplicationContext(),"Phone number is not valid",Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(location)) {
mEventLocationText.setError("Enter Location!");
return;
}
Map userInfo = new HashMap();
userInfo.put("mEventNameText", name);
userInfo.put("mContactNumText", contact);
userInfo.put("mEventDate", date);
userInfo.put("radioButton", type);
userInfo.put("mEventLocationText", location);
mDatabaseReference.updateChildren(userInfo);
final String fileName = System.currentTimeMillis()+"";
if(uriImage != null) {
StorageReference storageReference = storage.getReference();
storageReference.child("profileImageUrl").child(fileName).putFile(uriImage)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String url = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
mDatabaseReference.child("profileImageUrl").setValue(url).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){ }
else{
Toast.makeText(getApplicationContext(),"File not Successfully Uploaded",LENGTH_SHORT).show(); }
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(),"File not Successfully Uploaded",LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}else{
}
Toast.makeText(getApplicationContext(),"New event created successfully!",LENGTH_SHORT).show();
Intent ManageEventMenu = new Intent(CreateEvent.this, com.example.edward.eventmanagementsystem.ManageEvent.ManageEventMenu.class);
startActivity(ManageEventMenu);
}
});
}
public boolean isValidPhone(CharSequence phone) {
boolean check=false;
if(!Pattern.matches("[a-zA-Z]+", phone))
{
if(phone.length() < 10 || phone.length() > 11)
{
check = false;
}
else
{
check = true;
}
}
else
{
check=false;
}
return check;
}
private void selectPdf() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
startActivityForResult(intent,86);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 86 && resultCode == RESULT_OK && data != null){
final Uri imageUri = data.getData();
uriImage = imageUri;
mimageToUpload.setImageURI(uriImage);
}
else {
Toast.makeText(getApplicationContext(),"Please select file", LENGTH_SHORT).show();
}
}
}
I would like to show the data in this way.
The sample of xml file I would like to display the data create from Firebase in upload from CreateEvent.java
activity_list_of_event.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/gradientwallpaper">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Events"
android:layout_marginLeft="10dp"
android:textStyle="bold"
android:layout_marginTop="20dp"
android:textSize="24dp"
android:textColor="#color/white"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Total Created Event"
android:layout_marginLeft="10dp"
android:textSize="16dp"
android:textColor="#color/white"
android:layout_marginTop="10dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="10dp"
android:layout_marginBottom="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Upcoming"
android:layout_marginLeft="10dp"
android:textSize="16dp"
android:textColor="#color/white"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Pass"
android:gravity="right"
android:layout_marginRight="10dp"
android:textSize="16dp"
android:textColor="#color/white"/>
</LinearLayout>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:padding="10dp"
android:weightSum="10">
<LinearLayout
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="4"
android:orientation="vertical">
<TextView
android:id="#+id/item_month"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Month" />/ android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
<TextView
android:id="#+id/item_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Date" />/ android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
</LinearLayout>
<LinearLayout
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:orientation="vertical">
<TextView
android:id="#+id/item_eventName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Event Name"
android:textStyle="bold" />/android:textScaleX="18sp"
<TextView
android:id="#+id/item_contactNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Contact Number"
android:textStyle="bold" />
<TextView
android:id="#+id/item_type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Type of event"
android:textStyle="bold" />
<TextView
android:id="#+id/itemLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Location"
android:textStyle="bold" />
</LinearLayout>
<ImageView
android:id="#+id/item_image"
android:layout_width="75dp"
android:layout_height="75dp"
android:background="#color/white"
android:scaleType="centerCrop"
android:src="#drawable/pic1" />
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
So, I tried putting a recyclerView in a "popup" dialog using a firebaseRecyclerAdapter.
My problem is, that I know for sure the adapter gets filled because I was using the Logcat to tell me when it adds another "user" to the adapter, but it wont show anything in the recyclerview in the dialog.
I'm having this problem for a couple of days and couldn't find an answer yet, glad if you could help me :)
I'm using a main screen which changes fragments, and from a certain fragment I'm calling this specific dialog.
These are my files:
UserViewHolder - the class which holds the "sets" for the cardview:
public static class UserViewHolder extends RecyclerView.ViewHolder
{
View mView;
public UserViewHolder(View itemView)
{
super(itemView);
mView=itemView;
}
public void setName(String name)
{
TextView teacherName=(TextView) mView.findViewById(R.id.txtNameTea);
teacherName.setText(name);
}
public void setEmail(String email)
{
TextView txtEmailTea=(TextView) mView.findViewById(R.id.txtEmailTea);
txtEmailTea.setText(email);
}
public void setImage(final Context ctx, Uri imageUri, User cUser)
{
final ImageView imgProfileTea=(ImageView) mView.findViewById(R.id.imgProfileTea);
Picasso.with(ctx).load(cUser.getImageUri()).into(imgProfileTea);
if(imgProfileTea.getDrawable()==null) {
StorageReference load = FirebaseStorage.getInstance().getReference().child("usersProfilePic/" + cUser.getImageName());
load.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.with(ctx).load(uri.toString()).into(imgProfileTea);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_LONG);
}
});
}
}
}
Schedules - the fragment which calls the dialog from its toolbar:
package com.example.android.aln4;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.github.sundeepk.compactcalendarview.CompactCalendarView;
import com.github.sundeepk.compactcalendarview.domain.Event;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import static com.example.android.aln4.LoginActivity.myUser;
import static com.example.android.aln4.dataBase.mDatabaseReference;
import static com.example.android.aln4.dataBase.mFirebaseDatabase;
import static com.example.android.aln4.dataBase.mStorageRef;
import static com.example.android.aln4.navDrawerMain.firebaseRecyclerAdapter;
import static java.lang.System.in;
import static com.example.android.aln4.navDrawerMain.studentsQuery;
public class Schedules extends Fragment {
private Toolbar ScheduleToolbar;
private Button addEvent;
//private TextView txt;
private RecyclerView mRecyclerViewStudentEvent;
private CompactCalendarView compactCalendar;
private SimpleDateFormat dateFormatMonth = new SimpleDateFormat("MMMM-yyyy", Locale.getDefault());
private String[] monthName = {"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addEvent:
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(getContext());
View mView = getLayoutInflater().inflate(R.layout.dialog_event_creation, null);
mRecyclerViewStudentEvent = (RecyclerView) mView.findViewById(R.id.mRecyclerViewStudentEvent);
mRecyclerViewStudentEvent.setHasFixedSize(true);
mRecyclerViewStudentEvent.setLayoutManager(new LinearLayoutManager(getContext()));
setStudentsList();
mView = getLayoutInflater().inflate(R.layout.dialog_event_creation, null);
final EditText edtEventTitle = (EditText) mView.findViewById(R.id.edtEventTitle);
final TextView txtEventStartTime = (TextView) mView.findViewById(R.id.txtEventStartTime);
final TextView txtEventEndTime = (TextView) mView.findViewById(R.id.txtEventEndTime);
final EditText edtEventLocation = (EditText) mView.findViewById(R.id.edtEventLocation);
Button btnOfferEvent = (Button) mView.findViewById(R.id.btnOfferEvent);
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
btnOfferEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar startTime = Calendar.getInstance();
Calendar endTime = Calendar.getInstance();
int startHour = Integer.parseInt(txtEventStartTime.getText().toString().substring(0, 2));
int startMinute = Integer.parseInt(txtEventStartTime.getText().toString().substring(3, 5));
startTime.set(Calendar.HOUR_OF_DAY, startHour);
startTime.set(Calendar.MINUTE, startMinute);
int endHour = Integer.parseInt(txtEventEndTime.getText().toString().substring(0, 2));
int endMinute = Integer.parseInt(txtEventEndTime.getText().toString().substring(3, 5));
endTime.set(Calendar.HOUR_OF_DAY, endHour);
endTime.set(Calendar.MINUTE, endMinute);
String mId =/*dataSelected+*/ String.valueOf(startHour) + String.valueOf(startMinute);//+selectedUserID
EventCreation newEvent = new EventCreation(mId, startTime, endTime, edtEventTitle.getText().toString(), edtEventLocation.getText().toString(), R.color.colorPrimary);
dialog.dismiss();
}
});
dialog.show();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setHasOptionsMenu(true);
ScheduleToolbar = (Toolbar) getView().findViewById(R.id.schedule_toolbar);
// Setting toolbar as the ActionBar with setSupportActionBar() call
((AppCompatActivity) getActivity()).setSupportActionBar(ScheduleToolbar);
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference("users");
mStorageRef = FirebaseStorage.getInstance().getReference();
Calendar cal = Calendar.getInstance();
String month = monthName[cal.get(Calendar.MONTH)];
int year = cal.get(Calendar.YEAR);
getActivity().setTitle(month + "-" + year);
compactCalendar = (CompactCalendarView) getView().findViewById(R.id.compactcalendar_view);
compactCalendar.setUseThreeLetterAbbreviation(true);
long millis = System.currentTimeMillis() % 1000;
Event ev1 = new Event(Color.RED, millis, "First try");
compactCalendar.addEvent(ev1);
compactCalendar.setListener(new CompactCalendarView.CompactCalendarViewListener() {
#Override
public void onDayClick(Date dateClicked) {
//put events into scroll view adapter
}
#Override
public void onMonthScroll(Date firstDayOfNewMonth) {
getActivity().setTitle(dateFormatMonth.format(firstDayOfNewMonth));
}
});
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.schedules, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
}
private void setStudentsList() {
studentsQuery=mDatabaseReference.orderByChild("teacherNum").equalTo(myUser.getTeacherNum());
firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<User, navDrawerMain.UserViewHolder>(
User.class,R.layout.card_view_teacher,navDrawerMain.UserViewHolder.class,studentsQuery) {
#Override
protected void populateViewHolder(navDrawerMain.UserViewHolder viewHolder, User model, int position) {
viewHolder.setName(model.getFirstName() + " " + model.getLastName());
viewHolder.setEmail(model.getEmail());
viewHolder.setImage(getContext(), Uri.parse(model.getImageUri()), model);
}
};
mRecyclerViewStudentEvent.setAdapter(firebaseRecyclerAdapter);
}
}
The dialog xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/title"/>
<EditText
android:id="#+id/edtEventTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="כותרת"
android:layout_marginRight="50dp"/>
<android.support.v7.widget.RecyclerView
android:layout_marginTop="50dp"
android:id="#+id/mRecyclerViewStudentEvent"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="20dp"
android:orientation="vertical">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/clock"/>
<TextView
android:layout_width="wrap_content"
android:layout_marginRight="50dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="שעת התחלה"
android:textSize="20dp" />
<TextView
android:id="#+id/txtEventStartTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:layout_marginRight="50dp"
android:layout_marginTop="5dp"
android:text="21:00" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="25dp"
android:layout_marginRight="50dp"
android:background="#color/darkgray" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="50dp"
android:layout_alignParentRight="true"
android:layout_marginTop="26dp"
android:text="שעת סיום"
android:textSize="20dp" />
<TextView
android:id="#+id/txtEventEndTime"
android:layout_width="match_parent"
android:layout_marginRight="50dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:layout_marginTop="30dp"
android:text="21:45" />
</RelativeLayout>
<RelativeLayout
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="50dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_marginTop="20dp"
android:src="#mipmap/location"/>
<EditText
android:id="#+id/edtEventLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="מיקום תחילת השיעור"
android:layout_marginRight="50dp"/>
</RelativeLayout>
<Button
android:id="#+id/btnOfferEvent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_gravity="center_horizontal"
android:text="הצע שיעור"/>
</LinearLayout>
One more thing is that I know is that I'm already able to bring up users into the recyclerView in other fragments.. Here's the code in another fragment:
package com.example.android.aln4;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import static com.example.android.aln4.dataBase.mDatabaseReference;
import static com.example.android.aln4.dataBase.mFirebaseDatabase;
import static com.example.android.aln4.dataBase.mStorageRef;
import static com.example.android.aln4.navDrawerMain.firebaseRecyclerAdapter;
import static com.example.android.aln4.navDrawerMain.teachersQuery;
public class TeachersList extends Fragment {
private RecyclerView mRecyclerViewTeacher;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("מורים");
mFirebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mFirebaseDatabase.getReference("users");
mStorageRef = FirebaseStorage.getInstance().getReference();
mRecyclerViewTeacher=(RecyclerView) getView().findViewById(R.id.mRecyclerViewTeacher);
mRecyclerViewTeacher.setHasFixedSize(true);
mRecyclerViewTeacher.setLayoutManager(new LinearLayoutManager(getContext()));
setTeachersList();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.teachers_list_frag,container,false);
}
private void setTeachersList() {
teachersQuery=mDatabaseReference.orderByChild("type").equalTo("Teacher");
firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<User, navDrawerMain.UserViewHolder>(
User.class,R.layout.card_view_teacher,navDrawerMain.UserViewHolder.class,teachersQuery) {
#Override
protected void populateViewHolder(navDrawerMain.UserViewHolder viewHolder, User model, int position) {
viewHolder.setName(model.getFirstName()+" "+model.getLastName());
viewHolder.setEmail(model.getEmail());
viewHolder.setImage(getContext(), Uri.parse(model.getImageUri()),model);
}
};
mRecyclerViewTeacher.setAdapter(firebaseRecyclerAdapter);
}
}
and its xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/mRecyclerViewTeacher"
android:layout_marginTop="57dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
It's one of my first questions here so I apologize if I missed something :)
Any help would be appriciated.
Solved. All I did was regenerating the SHA1 in the firebase settings, and removing the setHasFixedSize line from Schedules activity and it worked just fine.
I created a custom ListView with Custom list view adapter. I want to set current time in every list item in the list. Items in the list box must update the current time every second.
MainActivity.java
package com.example.examapp;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.example.exambp.*;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.LabeledIntent;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
ListView lv;
Activity act=this;
List<ListViewItem> items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items=new ArrayList<ListViewItem>();
lv=(ListView)findViewById(R.id.listView1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
public void showData(View v)
{
IntentIntegrator i=new IntentIntegrator(this);
i.initiateScan();
}
String[] onedata;
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
String x=scanResult.getContents();
EditText et=(EditText)findViewById(R.id.editText1);
et.setText(x);
addToList(x);
}
}
ListViewItem li;
CustomListViewAdapter adapter;
public void addToList(String str)
{
onedata=str.split("/");
li=new ListViewItem();
li.enrollId="EnrollmentID: "+onedata[0].toString();
li.ExamId="ExamID: "+onedata[1].toString();
li.UserId="UserId: "+onedata[2].toString();
li.StartedTime=onedata[3].toString();
li.Duration=onedata[4].toString();
li.AvailableTime="jiukjh";
items.add(li);
adapter=new CustomListViewAdapter(this, items);
lv.setAdapter(adapter);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_marginLeft="60dp"
android:ems="10"
android:inputType="text" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:onClick="showData"
android:text="#string/btn_val" />
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:orientation="vertical" >
</LinearLayout>
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView9"
android:layout_toRightOf="#+id/linearLayout2" >
</ListView>
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/button1"
android:text="Started Exams"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtAvailability"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/txtEnrollmentId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtAvailability"
android:text="TextView" />
<TextView
android:id="#+id/txtUserId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/txtEnrollmentId"
android:layout_alignBottom="#+id/txtEnrollmentId"
android:layout_marginLeft="78dp"
android:layout_toRightOf="#+id/txtAvailability"
android:text="TextView" />
<TextView
android:id="#+id/txtExamId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtEnrollmentId"
android:text="TextView" />
<TextView
android:id="#+id/txtStartTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/txtExamId"
android:layout_alignBottom="#+id/txtExamId"
android:layout_alignLeft="#+id/txtUserId"
android:text="TextView" />
</RelativeLayout>
CustomListViewAdapter.java
package com.example.examapp;
import java.util.Date;
import java.util.List;
import com.example.exambp.*;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class CustomListViewAdapter extends BaseAdapter
{
LayoutInflater inflater;
List<ListViewItem> items;
Activity act;
public CustomListViewAdapter(Activity context, List<ListViewItem> items) {
super();
this.items = items;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.act=context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
View vi;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ListViewItem item=items.get(position);
vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item_row, null);
//ImageView imgThumbnail=(ImageView)vi.findViewById(R.id.imgThumbnail);
TextView txtAvailableTime1=(TextView)vi.findViewById(R.id.txtAvailability);
TextView txtEnrollmentId1=(TextView)vi.findViewById(R.id.txtEnrollmentId);
TextView txtUserId1=(TextView)vi.findViewById(R.id.txtUserId);
TextView txtExamId1=(TextView)vi.findViewById(R.id.txtExamId);
TextView txtStartedTime1=(TextView)vi.findViewById(R.id.txtStartTime);
//imgThumbnail.setImageResource(item.ThumbnailResource);
txtAvailableTime1.setText(item.AvailableTime.toString());
txtEnrollmentId1.setText(item.enrollId.toString());
txtUserId1.setText(item.UserId.toString());
txtExamId1.setText(item.ExamId.toString());
txtStartedTime1.setText(item.StartedTime.toString());
Thread myThread = null;
Runnable runnable = new CountDownRunner();
myThread= new Thread(runnable);
myThread.start();
return vi;
}
public void doWork() {
act.runOnUiThread(new Runnable() {
public void run() {
try{
TextView txtCurrentTime=(TextView)vi.findViewById(R.id.txtAvailability);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":" + minutes + ":" + seconds;
txtCurrentTime.setText(curTime);
}catch (Exception e) {
//TextView txtCurrentTime=(TextView)vi.findViewById(R.id.txtAvailability);
//txtCurrentTime.setText(e.getMessage());
}
}
});
}
class CountDownRunner implements Runnable{
// #Override
public void run() {
while(true){
try {
doWork();
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}catch(Exception e){
}
}
}
}
}
This is only run in one time. I want to change current time in List Items continuously.
Every second you will have to loop through each item in your List<ListViewItem> items and then update each item's time. After that call listView.notifyDataSetChanged().