I have two class PremiumAdapter & PreviewActivity, and now I want to access data in PremiumAdapter and the data located inside onBindViewHolder methods from PreviewActivity trough Onclick method.
Here is data in PremiumAdapter.java:
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
PremiumVideo video = data.get(position);
final VH vh = (VH) holder;
String price_id = video.price; // target data
String content_id** = video.content_id; // target data
and here is where the data will accessed on PreviewActivity.java:
public void onClick(DialogInterface dialogInterface, int i) {
// Here
}
here is my full code PreviewActivity:
public class PremiumVideoPreviewActivity extends BaseActivity {
private TextView Nama;
private TextView Judul;
private TextView Harga;
private Button btnBuy;
private ImageView imgPreview;
private VideoView video;
MediaController mediaController;
private ProgressBar progressBar;
List<PremiumVideo> premiumVideoList = new ArrayList<>();
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_premium_video_preview);
setDefaultToolbar(true);
Nama = findViewById(R.id.txtNamaPreview);
Judul = findViewById(R.id.txtJudulPreview);
Harga = findViewById(R.id.txtHargaPreview);
imgPreview = findViewById(R.id.imgPreview);
video = findViewById(R.id.vv_preview);
btnBuy = findViewById(R.id.btnBuy);
progressBar = new ProgressBar(this);
mediaController = new MediaController(this);
mediaController.setAnchorView(mediaController);
video.setMediaController(mediaController);
video.setZOrderOnTop(true);
video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.setLooping(true);
}
});
video.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
return false;
}
});
loadPremiumVideo();
PremiumVideo premiumVideo = new PremiumVideo();
String nama = premiumVideo.name;
final String judul = premiumVideo.judul;
final String harga = premiumVideo.price;
String img = premiumVideo.thumb_pic;
Nama.setText(nama);
Judul.setText(judul);
Harga.setText(harga);
Picasso.with(imgPreview.getContext())
.load(img)
.into(imgPreview);
btnBuy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final AlertDialog.Builder adb = new AlertDialog.Builder(PremiumVideoPreviewActivity.this);
adb.setTitle("Konfirmasi Belangganan");
adb.setMessage("\n Anda akan berlangganan video ini..");
adb.setCancelable(false);
adb.setPositiveButton("Iya", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
progressBar.setVisibility(View.VISIBLE);
ContactItem caller = SessionManager.getProfile(PremiumVideoPreviewActivity.this);
// i want use data from PremiumAdapter here
Call<APIResponse<DataJsonCharging>> call = ServicesFactory.getService().getCharging(/* Then passing here */);
call.enqueue(new Callback<APIResponse<DataJsonCharging>>() {
#Override
public void onResponse(Call<APIResponse<DataJsonCharging>> call, Response<APIResponse<DataJsonCharging>> response) {
int status = response.code();
APIResponse<DataJsonCharging> chargingResponse = response.body();
Log.d("SetVideoActivity", "onResponse: " + status);
progressBar.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<APIResponse<DataJsonCharging>> call, Throwable t) {
Log.d("SetVideoActivity", "onFailure: " + t.getMessage());
progressBar.setVisibility(View.GONE);
}
});
PremiumVideoModelCharging judul = new PremiumVideoModelCharging();
String judulVideo = judul.getJudul();
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(PremiumVideoPreviewActivity.this);
LayoutInflater inflater = (LayoutInflater) PremiumVideoPreviewActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = inflater.inflate(R.layout.popup_pembelian, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setTitle("Berhasil Berlangganan");
TextView txtJudul = dialogView.findViewById(R.id.txtNoteJudul);
txtJudul.setText(judulVideo);
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.getWindow().setLayout(400, 600);
alertDialog.setIcon(R.drawable.logo_1);
alertDialog.show();
Button button = (Button) dialogView.findViewById(R.id.btn_check_collection);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent checkCollectionIntent = new Intent(view.getContext(), UploadVideoToneActivity.class);
view.getContext().startActivity(checkCollectionIntent);
alertDialog.dismiss();
}
});
}
});
adb.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = adb.create();
alertDialog.show();
}
});
}
private void loadPremiumVideo() {
Call<APIResponse<List<PremiumVideo>>> call = ServicesFactory.getService().getPremiumVideo();
call.enqueue(new Callback<APIResponse<List<PremiumVideo>>>() {
#Override
public void onResponse(Call<APIResponse<List<PremiumVideo>>> call, Response<APIResponse<List<PremiumVideo>>> response) {
if (response.isSuccessful() && response.body().isSuccessful()) {
List<PremiumVideo> data = response.body().data;
if (data != null) {
premiumVideoList.clear();
premiumVideoList.addAll(data);
}
} else {
Toast.makeText(PremiumVideoPreviewActivity.this, response.errorBody().toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<APIResponse<List<PremiumVideo>>> call, Throwable t) {
Toast.makeText(PremiumVideoPreviewActivity.this, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_UPLOAD) {
if (OwnVideoManager.isOwnVideoExist(this)) {
Uri ownVideoUri = OwnVideoManager.getOwnVideoUri(this);
video.setVideoURI(ownVideoUri);
video.seekTo(100);
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
here is my PremiumAdapter :
public class PremiumVideoAdapter extends
RecyclerView.Adapter<RecyclerView.ViewHolder> {
static List<PremiumVideo> data;
private ClickCallback clickCallback;
public PremiumVideoAdapter(List<PremiumVideo> data) {
this.data = data;
}
public void setClickCallback(ClickCallback clickCallback) {
this.clickCallback = clickCallback;
}
public interface ClickCallback {
void itemClick(PremiumVideo video);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
PremiumVideo video = data.get(position);
final VH vh = (VH) holder; //Target data
String harga = video.price; //Target Data
You need to:
Create interface in Adapter
public interface ClickCallback {
void itemClick(PremiumVideo video);
}
Add field and setter in Adapter
private ClickCallback clickCallback;
public void setClickCallback(ClickCallback clickCallback) {
this.clickCallback = clickCallback;
}
Set and implement callback in Activity
episodeAdapter.setClickCallback(this);
Add onClickListener in ViewHolder
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(clickCallback!=null){
clickCallback.itemClick(date.get(getAdapterPosition()));
}
}
});
Related
I have a RecyclerView of questions (which are saved and retrieved from database) and seekbars (which I save in database).
Link to image
After clicking on SUBMIT EXTRA QUESTIONS there is a dialog which appears
Link to image
I want after clicking on Okay the progress of ALL seekbars to be 0.
I tried to do this submitExpenseData(jsonArrayQuestion.toString(), getId, jsonArrayAnswer.toString(), formatter.format(date));
holder.seekBar.setProgress(0);
But It changes only the progress of the last seekbar. Does anyone have any idea?
public class ExtraQuestionAdapter extends RecyclerView.Adapter<ExtraQuestionAdapter.ExtraQuestionViewHolder> {
private Context mCntx;
private List<ExtraQuestion> extraQuestionList;
private OnExtraAnswerListener onExtraAnswerListener;
private Button btn_submit_extra_questions;
private View rootView;
ArrayList<Integer> answersArray;
private Integer[] array = {};
String getId;
SessionManager sessionManager;
private Dialog dialog;
public ExtraQuestionAdapter(Context mCntx, List<ExtraQuestion> extraQuestionList, OnExtraAnswerListener onExtraAnswerListener) {
this.mCntx = mCntx;
this.extraQuestionList = extraQuestionList;
this.onExtraAnswerListener = onExtraAnswerListener;
}
#NonNull
#Override
public ExtraQuestionViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCntx);
View view = inflater.inflate(R.layout.extra_question_layout, parent, false);
sessionManager = new SessionManager(mCntx);
HashMap<String, String> user = sessionManager.getUserDetail();
mCntx = parent.getContext();
rootView = ((Activity) mCntx).getWindow().getDecorView().findViewById(android.R.id.content);
//set the size of the array with answers to be equal to the size of the array with questions
array = new Integer[extraQuestionList.size()];
//initialise the array with answers with 0
for (int i = 0; i < extraQuestionList.size(); i++) {
array[i] = 0;
}
getId = user.get(sessionManager.ID);
btn_submit_extra_questions = rootView.findViewById(R.id.btn_submit_extra_questions);
ExtraQuestionViewHolder extraQuestionViewHolder = new ExtraQuestionViewHolder(view, onExtraAnswerListener);
return extraQuestionViewHolder;
}
#Override
public void onBindViewHolder(#NonNull ExtraQuestionViewHolder holder, int position) {
ExtraQuestion extraQuestion = extraQuestionList.get(position);
holder.title.setText(extraQuestion.getExtra_question());
holder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
array[holder.getAdapterPosition()] = seekBar.getProgress();
}
});
btn_submit_extra_questions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog = new Dialog(mCntx);
dialog.setContentView(R.layout.dialog_submit);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
dialog.getWindow().setBackgroundDrawable(mCntx.getDrawable(R.drawable.dialog_background));
}
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(true);
Button finalSubmit = dialog.findViewById(R.id.btn_submit);
Button cancelSubmit = dialog.findViewById(R.id.btn_cancel);
ImageView info = dialog.findViewById(R.id.info);
TextView termsConditions = dialog.findViewById(R.id.textView3);
// Cancel button in the dialog
cancelSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
//Okay button in the dialog
finalSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//fill the arraylist of answers with the array of answers
answersArray = new ArrayList<>(Arrays.asList(array));
ArrayList<Integer> FAnswerArray = new ArrayList<>();
ArrayList<Integer> FQuestionArray = new ArrayList<>();
if (!answersArray.isEmpty()) {
for (int i = 0; i < answersArray.size(); i++) {
FAnswerArray.add(answersArray.get(i));
FQuestionArray.add(i + 1);
}
}
JSONArray jsonArrayQuestion = new JSONArray();
for (Integer question : FQuestionArray) {
jsonArrayQuestion.put(question);
}
JSONArray jsonArrayAnswer = new JSONArray();
for (Integer answer : FAnswerArray) {
jsonArrayAnswer.put(answer);
}
dialog.dismiss();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date(System.currentTimeMillis());
submitExpenseData(jsonArrayQuestion.toString(), getId, jsonArrayAnswer.toString(), formatter.format(date));
}
});
//Info button in the dialog
info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mCntx.getApplicationContext(), TermsConditionsActivity.class);
mCntx.startActivity(intent);
}
});
//Terms and conditions in the dialog
termsConditions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mCntx.getApplicationContext(), TermsConditionsActivity.class);
mCntx.startActivity(intent);
}
});
dialog.show();
}
});
}
private void submitExpenseData(String extra_questions_id, String users_id, String extra_answer, String timeStamp_date) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.EXTRA_ANSWERS_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//we get the successful in String response
Log.e("response", response);
try {
JSONObject jsonObject = new JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
String success = jsonObject.getString("success");
if (success.equals("1")) {
sessionManager.saveAnswersOfTheDay(extra_questions_id, users_id, extra_answer, timeStamp_date);
Toast.makeText(mCntx.getApplicationContext(), R.string.successQuestionsOfTheDay, Toast.LENGTH_SHORT).show();
}
if (success.equals("alreadySubmitted")) {
Toast.makeText(mCntx.getApplicationContext(), R.string.submit_extra_questions_once_a_day, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(mCntx.getApplicationContext(), "Error! " + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("sellresponseerror", "" + error.toString());
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("extra_questions_id", extra_questions_id);
params.put("users_id", users_id);
params.put("extra_answer", extra_answer);
params.put("timeStamp_date", timeStamp_date);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(mCntx);
requestQueue.add(stringRequest);
}
#Override
public int getItemCount() {
return extraQuestionList.size();
}
public class ExtraQuestionViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
SeekBar seekBar;
OnExtraAnswerListener onExtraAnswerListener;
public ExtraQuestionViewHolder(#NonNull View itemView, OnExtraAnswerListener onExtraAnswerListener) {
super(itemView);
title = itemView.findViewById(R.id.textViewTitle);
seekBar = itemView.findViewById(R.id.seekBar);
this.onExtraAnswerListener = onExtraAnswerListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onExtraAnswerListener.onExtraAnswerClick(getAdapterPosition());
}
}
public interface OnExtraAnswerListener {
void onExtraAnswerClick(int position);
}
}
Here is so far my implementation. I am trying to get the list of Bluetooth devices after the scan is finished. But the observer is not returning a list of devices.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int REQUEST_CODE_OPEN_GPS = 1;
private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
BluetoothAdapter bluetoothAdapter;
private MutableLiveData<List<DataModel>> deviceLiveData;
public static List<BleDevice> bleDeviceList;
private List<BleDevice> deviceList = new ArrayList<>();
private RecyclerView rvDevices;
private MAdapter devicesAdapter;
private MainViewModel mainViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bleDeviceList = new ArrayList<>();
rvDevices = findViewById(R.id.main_rv);
BleManager.getInstance().init(getApplication());
BleManager.getInstance()
.enableLog(true)
.setReConnectCount(5, 5000)
.setConnectOverTime(20000)
.setOperateTimeout(5000);
checkPermissions();
}
private void checkPermissions() {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!bluetoothAdapter.isEnabled()) {
Toast.makeText(this, getString(R.string.please_open_blue), Toast.LENGTH_LONG).show();
return;
}
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
List<String> permissionDeniedList = new ArrayList<>();
for (String permission : permissions) {
int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
onPermissionGranted(permission);
} else {
permissionDeniedList.add(permission);
}
}
if (!permissionDeniedList.isEmpty()) {
String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
}
}
Observer<List<BleDevice>> userListUpdateObserver = new Observer<List<BleDevice>>() {
#Override
public void onChanged(List<BleDevice> userArrayList) {
devicesAdapter = new MAdapter(MainActivity.this, userArrayList, new MAdapter.OnClick() {
#Override
public void onItemClick(View v) {
Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
}
});
rvDevices.setLayoutManager(new LinearLayoutManager(MainActivity.this));
rvDevices.setAdapter(devicesAdapter);
devicesAdapter.notifyDataSetChanged();
}
};
private void onPermissionGranted(String permission) {
switch (permission) {
case Manifest.permission.ACCESS_FINE_LOCATION:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
new AlertDialog.Builder(this)
.setTitle("Prompt")
.setMessage(R.string.gpsNotifyMsg)
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setPositiveButton(R.string.setting,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
}
})
.setCancelable(false)
.show();
} else {
startScan();
mainViewModel = new ViewModelProvider(MainActivity.this).get(MainViewModel.class);
mainViewModel.getUserMutableLiveData().observe(this, userListUpdateObserver);
}
break;
}
}
private boolean checkGPSIsOpen() {
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (locationManager == null)
return false;
return locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_OPEN_GPS) {
if (checkGPSIsOpen()) {
startScan();
}
}
}
#Override
public final void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE_PERMISSION_LOCATION:
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
onPermissionGranted(permissions[i]);
}
}
}
break;
}
}
public static void startScan() {
BleManager.getInstance().scan(new BleScanCallback() {
#Override
public void onScanStarted(boolean success) {
}
#Override
public void onLeScan(BleDevice bleDevice) {
super.onLeScan(bleDevice);
}
#Override
public void onScanning(BleDevice bleDevice) {
}
#Override
public void onScanFinished(List<BleDevice> scanResultList) {
bleDeviceList.addAll(scanResultList);
}
});
}
public static void clearScanDevice() {
for (int i = 0; i < bleDeviceList.size(); i++) {
BleDevice device = bleDeviceList.get(i);
if (!BleManager.getInstance().isConnected(device)) {
bleDeviceList.remove(i);
}
}
}
public void addDevice(BleDevice bleDevice) {
removeDevice(bleDevice);
String newBleDeviceName = bleDevice.getMac();
if (newBleDeviceName == null) return;
}
public void removeDevice(BleDevice bleDevice) {
for (int i = 0; i < bleDeviceList.size(); i++) {
BleDevice device = bleDeviceList.get(i);
if (bleDevice.getKey().equals(device.getKey())) {
bleDeviceList.remove(i);
}
}
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setTitle("Exit?");
builder1.setMessage("Are you sure you want to disconnect?.");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
BleManager.getInstance().disconnectAllDevice();
BleManager.getInstance().destroy();
Toast.makeText(MainActivity.this, "Disconnected", Toast.LENGTH_SHORT).show();
dialog.cancel();
finish();
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
#Override
protected void onDestroy() {
super.onDestroy();
BleManager.getInstance().disconnectAllDevice();
BleManager.getInstance().destroy();
}
#Override
protected void onResume() {
super.onResume();
}
public void clearConnectedDevice() {
for (int i = 0; i < bleDeviceList.size(); i++) {
BleDevice device = bleDeviceList.get(i);
if (BleManager.getInstance().isConnected(device)) {
bleDeviceList.remove(i);
}
}
}
}
I have the startScan() method in MainActivity.java. There I can get the list of discoverable BleDevices in onScanFinished(). I am trying to implement the same method in the repository class MainDataRepository.java. I am getting null data from that class in MainViewModel.java. Here is my implementation of all classes.
MainDataRepository.java
public class MainDataRepository {
private static final String TAG = "MainDataRepository";
private static final MainDataRepository ourInstance = new MainDataRepository();
private MutableLiveData<List<BleDevice>> deviceListLiveData = new MutableLiveData<>();
public static MainDataRepository getInstance() {
return ourInstance;
}
public MutableLiveData<List<BleDevice>> getTodos() {
BleManager.getInstance().scan(new BleScanCallback() {
#Override
public void onScanStarted(boolean success) {
Log.d("View Model", "scAN started");
}
#Override
public void onLeScan(BleDevice bleDevice) {
super.onLeScan(bleDevice);
Log.d("onLeScan", "onLeScan: View Model");
}
#Override
public void onScanning(BleDevice bleDevice) {
Log.d("View Model", "scannig");
}
#Override
public void onScanFinished(List<BleDevice> scanResultList) {
Log.d("View Model", "onScanFinished: " + scanResultList.size());
for (int i = 0; i < scanResultList.size(); i++) {
Log.d("View Model", "onScanFinished: " + scanResultList.get(i).getName() + " and " + scanResultList.get(i).getMac());
}
}
});
return deviceListLiveData;
}
}
MainViewModel.java
public class MainViewModel extends ViewModel {
private MutableLiveData<List<BleDevice>> userLiveData;
public static List<BleDevice> deviceArrayList = new ArrayList<>();
private MainDataRepository repository = MainDataRepository.getInstance();
public MainViewModel() {
super();
userLiveData = new MutableLiveData<>();
userLiveData = repository.getTodos();
Log.d("View Model", "MainViewModel: " + userLiveData.getValue());
init();
}
public MutableLiveData<List<BleDevice>> getUserMutableLiveData() {
return userLiveData;
}
public void init() {
populateList();
userLiveData.setValue(deviceArrayList);
}
public void populateList() {
deviceArrayList = new ArrayList<>();
Log.d("Inside Populate", "populateList: ");
}
}
MAdapter.java
public class MAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private List<BleDevice> bleDeviceList;
public OnClick click;
public MAdapter(Context mContext, List<BleDevice> bleDeviceList, OnClick click) {
this.mContext = mContext;
this.bleDeviceList = bleDeviceList;
this.click = click;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View rootView = LayoutInflater.from(mContext).inflate(R.layout.card_ll, parent, false);
return new MViewHolder(rootView);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
BleDevice device = bleDeviceList.get(position);
((MViewHolder) holder).tvName.setText(device.getName());
((MViewHolder) holder).tvMac.setText(device.getMac());
((MViewHolder) holder).btnConnect.setText("Pair");
((MViewHolder) holder).btnConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click.onItemClick(v);
((MViewHolder) holder).btnConnect.setText("Paired");
((MViewHolder) holder).btnConnect.setClickable(false);
}
});
}
#Override
public int getItemCount() {
return bleDeviceList.size();
}
static class MViewHolder extends RecyclerView.ViewHolder {
private TextView tvName, tvMac;
private Button btnConnect;
public MViewHolder(#NonNull View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.device_name);
tvMac = itemView.findViewById(R.id.device_mac_address);
btnConnect = itemView.findViewById(R.id.btn_connect);
}
}
public interface OnClick {
public void onItemClick(View v);
}
}
Thanks in advance.
I followed a Tutorial and was Successfully able to Load the data in Firebase and also retrieve it back in RecyclerView and also Learned How to Delete data but now I'm Stuck that how to update this data in the Firebase and show it in RecyclerView.I have used Picasso for the Images.
This is my Gallery.java file
public class Gallery extends AppCompatActivity {
private static final int PICK_IMAGE_REQUEST= 1;
private Button mButtonChooseImage;
private Button mButtonUpload;
private TextView mTextViewShowGallery;
private EditText mEditTextFileName,mEditTextDesc;
private ImageView mImageView;
private ProgressBar mProgressBar;
private Uri mImageUri;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef;
private StorageTask mUploadTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
mButtonChooseImage = (Button)findViewById(R.id.btnChoose);
mButtonUpload = (Button)findViewById(R.id.btnUpload);
mTextViewShowGallery = (TextView)findViewById(R.id.tvShow);
mImageView = (ImageView)findViewById(R.id.imgView);
mProgressBar = (ProgressBar)findViewById(R.id.progress_bar);
mEditTextFileName = (EditText)findViewById(R.id.txtName);
mEditTextDesc = (EditText)findViewById(R.id.txtDesc);
mStorageRef = FirebaseStorage.getInstance().getReference("uploads");
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mButtonChooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
mButtonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mUploadTask != null && mUploadTask.isInProgress())
{
Toast.makeText(Gallery.this, "Upload In Progress", Toast.LENGTH_SHORT).show();
}
else
{
uploadFile();
}
}
});
mTextViewShowGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openImagesActivity();
}
});
}
private void openFileChooser ()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null)
{
mImageUri = data.getData();
Picasso.with(this).load(mImageUri).into(mImageView);
}
}
private String getFileExtension(Uri uri)
{
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void uploadFile()
{
if (mImageUri != null)
{
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
},500);
Toast.makeText(Gallery.this, "Upload Successful", Toast.LENGTH_LONG).show();
UploadImage uploadImage = new UploadImage(mEditTextFileName.getText().toString().trim(),
mEditTextDesc.getText().toString().trim(),taskSnapshot.getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(uploadImage);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Gallery.this,e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnPausedListener(new OnPausedListener<UploadTask.TaskSnapshot>() {
#Override
public void onPaused(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mProgressBar.setProgress((int)progress);
}
});
} else {
Toast.makeText(this, "No File Selected", Toast.LENGTH_SHORT).show();
}
}
private void openImagesActivity()
{
Intent intent = new Intent(Gallery.this,ImagesActivity.class);
startActivity(intent);
}
}
This below one is the ImagesActivity which is for the recyclerview, here the delete operation works, as I mentioned and I have used the AlertDialog to open and update the details I tried to Mimic some things from gallery.java but was not able to figure out how they should be Arranged.
public class ImagesActivity extends AppCompatActivity implements ImageAdapter.OnItemClickListener {
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
private ProgressBar mProgressCircle;
private static final int PICK_IMAGE_REQUEST= 1;
private StorageTask mUploadTask;
private Uri mImageUri;
private StorageReference mStorageRef;
private FirebaseStorage mStorage;
private DatabaseReference mDatabaseRef;
private ValueEventListener mDBListener;
private List<UploadImage> mUploads;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_images);
mRecyclerView = findViewById(R.id.recycler_view);
mProgressCircle= findViewById(R.id.progress_circle);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mUploads = new ArrayList<>();
mAdapter = new ImageAdapter(ImagesActivity.this,mUploads);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(ImagesActivity.this);
mStorage = FirebaseStorage.getInstance();
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
mDBListener = mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUploads.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
UploadImage uploadImage = postSnapshot.getValue(UploadImage.class);
uploadImage.setKey(postSnapshot.getKey());
mUploads.add(uploadImage);
}
mAdapter.notifyDataSetChanged();
mProgressCircle.setVisibility(View.INVISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ImagesActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
mProgressCircle.setVisibility(View.INVISIBLE);
}
});
}
private String getFileExtension(Uri uri)
{
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
#Override
public void onItemClick(int position) {
Toast.makeText(this, "Normal Click", Toast.LENGTH_SHORT).show();
}
#Override
public void onUpdateClick(int position) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.update_dialog, null);
dialogBuilder.setView(dialogView);
final EditText TextName = (EditText) dialogView.findViewById(R.id.txtName);
final EditText TextDesc = (EditText) dialogView.findViewById(R.id.txtDesc);
final ImageView ImageView = (ImageView) dialogView.findViewById(R.id.imgView);
final Button chooseFile = (Button) dialogView.findViewById(R.id.btnChoose);
final Button UpdateDetails = (Button) dialogView.findViewById(R.id.btnUpdate);
dialogBuilder.setTitle("Update Details");
final AlertDialog b = dialogBuilder.create();
b.show();
chooseFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
UpdateDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mUploadTask != null && mUploadTask.isInProgress())
{
Toast.makeText(ImagesActivity.this, "Upload In Progress", Toast.LENGTH_SHORT).show();
}
else
{
if (mImageUri != null)
{
StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
+ "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(ImagesActivity.this, "Update Successful", Toast.LENGTH_LONG).show();
UploadImage uploadImage = new UploadImage(TextName.getText().toString().trim(),
TextDesc.getText().toString().trim(),taskSnapshot.getDownloadUrl().toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.setValue(uploadImage);
mDatabaseRef.child(uploadId).setValue(uploadImage);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ImagesActivity.this,e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(ImagesActivity.this, "No File Selected", Toast.LENGTH_SHORT).show();
}
}
b.dismiss();
}
});
UploadImage selectedItem = mUploads.get(position);
final String selectedKey = selectedItem.getKey();
// Toast.makeText(this, "Update Clicked", Toast.LENGTH_SHORT).show();
}
private void openFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,PICK_IMAGE_REQUEST);
}
#Override
public void onDeleteClick(int position) {
UploadImage selectedItem = mUploads.get(position);
final String selectedKey = selectedItem.getKey();
StorageReference imageRef = mStorage.getReferenceFromUrl(selectedItem.getImageUrl());
imageRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mDatabaseRef.child(selectedKey).removeValue();
Toast.makeText(ImagesActivity.this, "Item Deleted", Toast.LENGTH_SHORT).show();
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
mDatabaseRef.removeEventListener(mDBListener);
}
}
This below one is for set and get methods named as UploadImage.java
public class UploadImage {
private String mName;
private String mDesc;
private String mImageUrl;
private String mKey;
public UploadImage()
{
//Empty Constructor Needed
}
public UploadImage(String name, String desc, String imageUrl)
{
if (name.trim().equals(""))
{
name = "No Name";
desc = "No Description";
}
mName = name;
mDesc = desc;
mImageUrl = imageUrl;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getDesc() {
return mDesc;
}
public void setDesc(String desc) {
mDesc=desc;
}
public String getImageUrl() {
return mImageUrl;
}
public void setImageUrl(String imageUrl) {
mImageUrl=imageUrl;
}
#Exclude
public String getKey(){
return mKey;
}
#Exclude
public void setKey(String key){
mKey = key;
}
}
The following one for the Adapter
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context mContext;
private List<UploadImage> mUploads;
private OnItemClickListener mListener;
public ImageAdapter(Context context, List<UploadImage> uploads){
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item,parent,false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
UploadImage uploadImageCurrent = mUploads.get(position);
holder.textViewName.setText(uploadImageCurrent.getName());
Picasso.with(mContext)
.load(uploadImageCurrent.getImageUrl())
.placeholder(R.drawable.ic_image_black_24dp)
.fit()
.centerCrop()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener{
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_view_name);
imageView = itemView.findViewById(R.id.image_view_upload);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
if (mListener != null)
{
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
//To Handle Normal Item Clicks
mListener.onItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select Action");
MenuItem Update = menu.add(Menu.NONE, 1, 1, "Update");
MenuItem Delete = menu.add(Menu.NONE, 2, 2, "Delete");
Update.setOnMenuItemClickListener(this);
Delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if (mListener != null)
{
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
//To Check Which Menu Item Was Clicked
switch (item.getItemId())
{
case 1:
mListener.onUpdateClick(position);
return true;
case 2:
mListener.onDeleteClick(position);
return true;
}
}
}
return false;
}
}
public interface OnItemClickListener{
void onItemClick(int position);
void onUpdateClick(int position);
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
}
Any Solution for this how can I update it.
There is no update method in firebase storage, So for a workaround:
get the name the file you want to delete
delete the file you want to update
upload the new file
rename file with the previous file name
I have 2 Activities in my application.
activityMain contain 3 Fragments
The third fragment is a conversations list. This is a recylerView where each Item leads to a specific chat.
activityConversation contains a Chat.
First, i would like to sort the conversations in the the recyclerView in order of "Last actives". The most recent active should be displayed on top of the list, the second last active on second postition etc...
Secondly, each Item of the recyclerView contains a Textview. For each item, I would like to display the last message posted in the related chat in this Texview.
Finally, i would like to display these Item textViews in Bold since the conversation has not been opened until the last chat update.
Has anyone an Idea to help me achieve that?
Here my Chat Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversation);
getWindow().setBackgroundDrawableResource(R.drawable._background_black_lchatxxxhdpi) ;
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
LinearLayout leftNav = (LinearLayout)findViewById(R.id.conv_left_nav);
LinearLayout helperAdmin = (LinearLayout) getLayoutInflater().inflate(R.layout.list_participant_admin, leftNav, false);
leftNav.addView(helperAdmin);
final EditText input_post = (EditText)findViewById(R.id.input_post);
context = this;
input_post.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
ImageButton btn_submit = (ImageButton)findViewById(R.id.btn_submit);
btn_submit.setEnabled(!TextUtils.isEmpty(s.toString().trim()));
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Intent intent = getIntent();
if (intent.hasExtra("conversationId"))
conversationId = intent.getStringExtra("conversationId");
rpcHelper = new RPCHelper(context, this);
String unique_device_id = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
Log.i("US", unique_device_id);
rpcHelper.loginOrRegister(unique_device_id, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
refreshConversation();
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
dbHelper = new DataBaseHelper(context, "us", null, Statics.DB_VERSION);
userInConv = dbHelper.dbReader.getUserInConversation(Integer.parseInt(conversationId));
storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
leftRecycler = (RecyclerView) helperAdmin.findViewById(R.id.conv_left_recycler);
//mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
leftLayoutManager = new LinearLayoutManager(this);
leftRecycler.setLayoutManager(leftLayoutManager);
leftAdapter = new ConvLeftAdapter(userInConv, storageDir, Integer.parseInt(conversationId));
leftRecycler.setAdapter(leftAdapter);
helpersImg = new View[3];
helpers = new DataBaseReader.User[3];
photos = dbHelper.dbReader.getPhotosInConversation(Integer.parseInt(conversationId));
photoRecycler = (RecyclerView) findViewById(R.id.photo_recycler);
photoLayoutManager = new GridLayoutManager(this, Math.max(photos.length, 1));
photoRecycler.setLayoutManager(photoLayoutManager);
rightAdapter = new ConvRightAdapter(photos, storageDir, context);
photoRecycler.setAdapter(rightAdapter);
IntentFilter filter = new IntentFilter(Statics.ACTION_NEW_POST);
this.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context ctx, Intent intent) {
Log.d("new", " message");
refreshConversation();
}
}, filter);
}
#Override
public void onNewIntent(Intent intent){
if (intent.hasExtra("conversationId"))
conversationId = intent.getStringExtra("conversationId");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_conversation, menu);
DataBaseReader.Conversation conversation = dbHelper.dbReader.getConversation(conversationId);
DataBaseReader.User owner = dbHelper.dbReader.getConversationOwner(conversationId);
final ImageView owner_img = (ImageView)findViewById(R.id.img_userprofilpic);
TextView owner_name = (TextView)findViewById(R.id.lbl_username_owner);
TextView owner_city = (TextView)findViewById(R.id.lbl_usercity_owner);
TextView conversation_question = (TextView)findViewById(R.id.question_text);
owner_name.setText(owner.name);
owner_city.setText(owner.city);
conversation_question.setText(conversation.question.text);
conversation_question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView text = (TextView)findViewById(R.id.question_text);
int maxLines = TextViewCompat.getMaxLines(text);
if (maxLines==2){
text.setMaxLines(Integer.MAX_VALUE);
}
else{
text.setMaxLines(2);
}
}
});
rpcHelper.getPhoto(storageDir + "/", owner.photo, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
owner_img.setImageBitmap(bm);
}
#Override
public void onPreExecute() {
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
public void refreshConversation(){
dbHelper.dbSyncer.syncPosts(rpcHelper.user_id, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
DataBaseReader.Post[] posts = dbHelper.dbReader.getPosts(conversationId);
postsRecycler = (RecyclerView) findViewById(R.id.posts_recycler);
postsLayoutManager = new LinearLayoutManager(context);
postsRecycler.setLayoutManager(postsLayoutManager);
postsAdapter = new PostsAdapter(posts, storageDir, rpcHelper);
postsRecycler.setAdapter(postsAdapter);
postsRecycler.scrollToPosition(postsAdapter.getItemCount() - 1);
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
/*
rpcHelper.getPosts(conversationId, new AsyncResponseListener(){
#Override
public void onResponse(JSONArray response) throws JSONException {
LinearLayout posts_root = (LinearLayout) findViewById(R.id.posts_root);
posts_root.removeAllViews();
for (int i = 0; i < response.length(); i++){
Log.d("Conv refresh", response.get(i) + "");
final JSONObject jConversation = (JSONObject) response.get(i);
LinearLayout post;
if (jConversation.getString("userId") == rpcHelper.user_id) {
post = (LinearLayout) getLayoutInflater().inflate(R.layout.item_chatpost_sent, posts_root, false);
}
else{
post = (LinearLayout) getLayoutInflater().inflate(R.layout.item_chatpost_received, posts_root, false);
((TextView)post.findViewById(R.id.post_name_)).setText(jConversation.getString("name"));
}
((TextView)post.findViewById(R.id.lbl_message_chat)).setText(jConversation.getString("text"));
posts_root.addView(post);
}
hideProcessDialog();
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});*/
}
public void onSubmit(View v){
final EditText input_post = (EditText)findViewById(R.id.input_post);
String post_text = input_post.getText().toString();
rpcHelper.post(conversationId, post_text, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
refreshConversation();
input_post.setText("");
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
}
Button no = (Button)alertDialog.findViewById(R.id.btn_cancel);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
helpersImg[0] = null;
helpersImg[1] = null;
helpersImg[2] = null;
helpers[0] = null;
helpers[1] = null;
helpers[2] = null;
alertDialog.dismiss();
}
});
}
public void onSelectUser(View v){
View vi = snapHelper.findSnapView(participantsLayoutManager);
if (helpersImg[0] == vi || helpersImg[1] == vi || helpersImg[2] == vi)
return;
Log.i("get helper Id", ""+ participantsAdapter.selectedUserId);
ImageView photo = (ImageView) vi.findViewById(R.id.img_userprofilpic);
photo.setDrawingCacheEnabled(true);
Bitmap bmap = photo.getDrawingCache();
ImageView helperImage = null;
if (helpersImg[0] == null) {
helperImage = (ImageView) alertDialog.findViewById(R.id.reward_dialog_helper0);
helpersImg[0] = vi;
helperImage.setImageBitmap(bmap);
photo.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);
helpers[0] = userInConv[participantsAdapter.selectedUserId];
}
else if (helpersImg[1] == null){
helperImage = (ImageView) alertDialog.findViewById(R.id.reward_dialog_helper1);
helpersImg[1] = vi;
helperImage.setImageBitmap(bmap);
photo.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);
helpers[1] = userInConv[participantsAdapter.selectedUserId];
}
else if (helpersImg[2] == null){
helperImage = (ImageView) alertDialog.findViewById(R.id.reward_dialog_helper2);
helpersImg[2] = vi;
helperImage.setImageBitmap(bmap);
photo.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);
helpers[1] = userInConv[participantsAdapter.selectedUserId];
}
else{
return;
}
}
/**private void showTipDialog(){
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
LayoutInflater inflater = LayoutInflater.from(context);
final View dialogView = inflater.inflate(R.layout.dialog_add_tip, null);
final EditText value = (EditText) dialogView.findViewById(R.id.tip_value);
final SeekBar sb = (SeekBar) dialogView.findViewById(R.id.seekBar);
sb.setMax(50);
sb.setProgress(5);
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
progress = (Math.round(progress/5 ))*5;
seekBar.setProgress(progress);
value.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
value.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Convert text to integer. Do you already use editText.setInputType(InputType.TYPE_CLASS_NUMBER), don't you?
Integer enteredProgress = Integer.valueOf(s.toString());
sb.setProgress(enteredProgress);
}
#Override
public void afterTextChanged(Editable s) {}});
dialogBuilder.setView(dialogView);
alertDialog = dialogBuilder.create();
alertDialog.show();
Button ok = (Button)alertDialog.findViewById(R.id.btn_ok);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
Button no = (Button)alertDialog.findViewById(R.id.btn_no);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
}*/
public void removeHelper(View v){
int index = 0;
if (v == alertDialog.findViewById(R.id.reward_dialog_helper0)){
index = 0;
}
else if (v == alertDialog.findViewById(R.id.reward_dialog_helper1)){
index = 1;
}
else if (v == alertDialog.findViewById(R.id.reward_dialog_helper2)){
index = 2;
}
if (helpersImg[index] == null){
return;
}
ImageView photo = (ImageView) helpersImg[index].findViewById(R.id.img_userprofilpic);
photo.setDrawingCacheEnabled(true);
photo.clearColorFilter();
helpersImg[index] = null;
helpers[index] = null;
ImageView imv = (ImageView)v;
imv.setImageResource(R.drawable.stroke_rounded_corners_white);
}
private void showProcessDialog(){
pd = new ProgressDialog(this);
pd.setTitle("Processing");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
private void hideProcessDialog(){
pd.hide();
}
#Override
public void onInternetConnectionLost() {
}
#Override
public void onInternetConnectionFound() {
}
public void onTakePicture(View v){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, Statics.REQUEST_IMAGE_CAPTURE);
}
}
public void onTakePictureFromGallery(View v){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), Statics.REQUEST_PROFILE_IMAGE_GALLERY);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap imageBitmap;
if ((requestCode == Statics.REQUEST_IMAGE_CAPTURE || requestCode == Statics.REQUEST_IMAGE_CAPTURE_0
|| requestCode == Statics.REQUEST_IMAGE_CAPTURE_1 || requestCode == Statics.REQUEST_IMAGE_CAPTURE_2) && resultCode == RESULT_OK && data != null) {
Bundle extras = data.getExtras();
if (extras == null){
return;
}
imageBitmap = (Bitmap) extras.get("data");
addPhoto(imageBitmap);
}
else if (requestCode == Statics.REQUEST_PROFILE_IMAGE_GALLERY && resultCode == RESULT_OK){
try {
imageBitmap = getBitmapFromUri(data.getData());
addPhoto(imageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void addPhoto(Bitmap image) {
DataBaseReader.Conversation c = dbHelper.dbReader.getConversation(conversationId);
String encodedImage = encodeBitmap(image);
rpcHelper.addPhotosToQuestion("" + c.question.id, encodedImage, null, null, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
dbHelper.dbSyncer.sync(rpcHelper.user_id, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
photos = dbHelper.dbReader.getPhotosInConversation(Integer.parseInt(conversationId));
photoRecycler = (RecyclerView) findViewById(R.id.photo_recycler);
photoLayoutManager = new GridLayoutManager(context, Math.max(photos.length, 1));
photoRecycler.setLayoutManager(photoLayoutManager);
rightAdapter = new ConvRightAdapter(photos, storageDir, context);
photoRecycler.setAdapter(rightAdapter);
}
#Override
public void onResponse() {
photos = dbHelper.dbReader.getPhotosInConversation(Integer.parseInt(conversationId));
photoRecycler = (RecyclerView) findViewById(R.id.photo_recycler);
photoLayoutManager = new GridLayoutManager(context, Math.max(photos.length, 1));
photoRecycler.setLayoutManager(photoLayoutManager);
rightAdapter = new ConvRightAdapter(photos, storageDir, context);
photoRecycler.setAdapter(rightAdapter);
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
}
private String encodeBitmap(Bitmap bitmap){
try{
bitmap = Bitmap.createScaledBitmap(bitmap, Statics.BITMAP_WIDTH, Statics.BITMAP_HEIGHT, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
final byte[] imageInByte = stream.toByteArray();
return Base64.encodeToString(imageInByte, Base64.DEFAULT);
}
catch(Exception e){
return "";
}
}
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
}
This is my Fragment with conversations List:
public class ConversationFragment extends Fragment {
private View v;
private OnFragmentInteractionListener mListener;
public ConversationFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment ConversationFragment.
*/
// TODO: Rename and change types and number of parameters
public static ConversationFragment newInstance() {
ConversationFragment fragment = new ConversationFragment();
Bundle args = new Bundle();
//args.putString(ARG_PARAM1, param1);
//args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if (v == null) {
v = inflater.inflate(R.layout.fragment_conversation, container, false);
}
final SwipeRefreshLayout swipeRefresh = (SwipeRefreshLayout)v.findViewById(R.id.swiperefreshconv);
swipeRefresh.post(new Runnable() {
#Override
public void run() {
swipeRefresh.setRefreshing(true);
}
});
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mListener.syncDb();
}
});
return v;
}
#Override
public void onStart(){
super.onStart();
mListener.refreshConversations();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
This is my Conversation Adapter:
public class ConversationsAdapter extends RecyclerView.Adapter {
private final File mStorageDir;
private final RPCHelper mRPCHelper;
private DataBaseReader.Conversation[] mDataset;
Context context;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public View mView;
public ViewHolder(View v) {
super(v);
mView = v;
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public ConversationsAdapter(DataBaseReader.Conversation[] myDataset, File storageDir) {
mDataset = myDataset;
mStorageDir = storageDir;
mRPCHelper = new RPCHelper();
}
// Create new views (invoked by the layout manager)
#Override
public ConversationsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_conversations, parent, false);
ViewHolder vh = new ViewHolder(v);
context = parent.getContext();
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
Log.d("recy", "bind called");
TextView username = (TextView)holder.mView.findViewById(R.id.lbl_username);
final TextView message = (TextView)holder.mView.findViewById(R.id.question_text);
TextView date_and_time = (TextView)holder.mView.findViewById(R.id.lbl_date_and_time);
ImageView status_pending = (ImageView)holder.mView.findViewById(R.id.lbl_status_conversation_pending);
ImageView status_in = (ImageView)holder.mView.findViewById(R.id.lbl_status_conversation_in);
TextView keyword0 = (TextView)holder.mView.findViewById(R.id.post_keywords0);
TextView keyword1 = (TextView)holder.mView.findViewById(R.id.post_keywords1);
TextView keyword2 = (TextView)holder.mView.findViewById(R.id.post_keywords2);
ImageView userprofilpic = (ImageView)holder.mView.findViewById(R.id.img_userprofilpic);
LinearLayout answer_info = (LinearLayout) holder.mView.findViewById(R.id.answer_info);
Button delete_coversation = (Button) holder.mView.findViewById(R.id.btn_confirm_delete);
userprofilpic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, UserProfileActivity.class);
i.putExtra("userId", mDataset[position].question.userId);
context.startActivity(i);
}
});
username.setText(mDataset[position].question.userName);
message.setText(mDataset[position].question.text);
keyword0.setText(mDataset[position].question.keywords[0]);
keyword1.setText(mDataset[position].question.keywords[1]);
keyword2.setText(mDataset[position].question.keywords[2]);
addImgToView(mDataset[position].question.photo, userprofilpic);
if (Integer.parseInt(mDataset[position].confirmed) == 1) {
status_pending.setEnabled(false);
status_pending.setVisibility(View.GONE);
status_in.setVisibility(View.VISIBLE);
answer_info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
message.setTypeface(Typeface.DEFAULT);
message.onSaveInstanceState();
int convId = mDataset[position].id;
Intent i = new Intent(context, ConversationActivity.class);
i.putExtra("conversationId", "" + convId);
context.startActivity(i);
}
});
}
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.length;
}
private void addImgToView(final String uri, final ImageView v){
mRPCHelper.getPhoto(mStorageDir + "/", uri, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
v.setImageBitmap(bm);
}
#Override
public void onPreExecute() {
}
});
}
}
Thank you in advance for your time.
maintain a flag in data level to know is it read or unread,based on that you can apply the styles.
There is two way to do this.
First you can ask to backend to write server side to query to handle last activity bases of timestamp .In this case you have to send your particular timestamp to server when you open particular conversation .
Other you can make local database ex-(sql database) and handle it in your own code by updating query when you reading or undreading conversation.
I am using a ViewPager to be able to swipe between views. The problem that I am facing is, the first page does not render properly(only the static members from layout file get rendered), but the second page and further pages are rendered properly. Also, when I go to third or later page and then come swiping back to the first page, it gets rendered perfectly.
I know that ViewPager loads the first page as well second page in the beginning and does the same for every next page. Is this the reason why my first page is not rendered properly? I am making a network call on each page and the data returned is being displayed on the page.
Here is the code for my Adapter:
public class SlidingImageDetailAdapter extends PagerAdapter implements GoogleApiClient.OnConnectionFailedListener {
Context context;
List<ImageDetailData> list;
List<LatestComment> latestComments;
LayoutInflater layoutInflater;
GaApplication application;
protected GoogleApiClient mGoogleApiClient;
TinyDB tinyDB;
MixpanelAPI mixpanel;
RestAdapter restAdapter;
public final String TAG = getClass().getSimpleName();
private static int radius = Utils.dpToPx(40);
private String googlePlaceId = null;
private String finalPlace = null;
private String commentId = null;
private String imageId = null;
private String imageUrl = null;
private boolean updateNeeded;
private PlaceAutocompleteAdapter mAdapter;
ImageGalleryAdapter imageGalleryAdapter;
ImageCommentAdapter imageCommentAdapter;
ViewHolder holder = null;
private static final LatLngBounds BOUNDS_GREATER_SYDNEY = new LatLngBounds(
new LatLng(-34.041458, 150.790100), new LatLng(-33.682247, 151.383362));
public SlidingImageDetailAdapter(Context context, List<ImageDetailData> list) {
this.context = context;
this.list = list;
layoutInflater = LayoutInflater.from(context);
application = (GaApplication) ((AppCompatActivity) context).getApplication();
String API = application.getAPI();
tinyDB = new TinyDB(context);
mixpanel = MixpanelAPI.getInstance(context, application.getMixpanelId());
final String token = tinyDB.getString(AppConstants.GA_ACCESS_TOKEN);
OkHttpClient okHttpClient = new OkHttpClient();
RequestInterceptor requestInterceptor = new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
request.addHeader("Accept", "application/json");
request.addHeader("Authorization", "Token " + token);
}
};
restAdapter = new RestAdapter.Builder()
.setClient(new OkClient(okHttpClient))
.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint(API)
.setRequestInterceptor(requestInterceptor)
.build();
mGoogleApiClient = new GoogleApiClient.Builder(context)
.enableAutoManage((ImageDetailSliderActivity)context, 0 /* clientId */, this)
.addApi(Places.GEO_DATA_API)
.build();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LogUtil.i(TAG, "instantiateItem called");
View view = layoutInflater.inflate(R.layout.viewpager_image_detail, container, false);
holder = new ViewHolder(view);
final ImageDetailData item = list.get(position);
imageId = item.getPhotoId();
holder.bar.setVisibility(View.INVISIBLE);
holder.deletePhoto.setVisibility(View.INVISIBLE);
holder.locationIcon.setVisibility(View.GONE);
holder.galleryList.setFocusable(false);
holder.commentList.setFocusable(false);
googlePlaceId = null;
finalPlace = null;
updateNeeded = false;
commentId = null;
imageUrl = null;
final ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Loading...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
if (!TextUtils.isEmpty(item.getPhotoUrl())) {
imageUrl = item.getPhotoUrl();
Uri uri = Uri.parse(item.getPhotoUrl());
ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
.setProgressiveRenderingEnabled(true)
.build();
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setImageRequest(request)
.setOldController(holder.image.getController())
.build();
holder.image.setController(controller);
}
Picasso.with(context)
.load(tinyDB.getString(AppConstants.USER_DP))
.resize(radius, radius)
.centerCrop()
.transform(new CircleTransform())
.into(holder.userDp);
TextWatcher textWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
Picasso.with(context)
.load(R.drawable.cta_button_post)
.into(holder.postButton);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (TextUtils.isEmpty(holder.writeComment.getText().toString().trim())) {
Picasso.with(context)
.load(R.drawable.cta_button_post_in_active)
.into(holder.postButton);
} else {
Picasso.with(context)
.load(R.drawable.cta_button_post)
.into(holder.postButton);
}
}
};
holder.writeComment.addTextChangedListener(textWatcher);
holder.comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
scrollToComment();
}
});
holder.seeAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, AllGalleriesActivity.class);
intent.putExtra(KEY_SEND_ALL_GALLERY_PHOTO_ID, item.getPhotoId());
context.startActivity(intent);
}
});
//show and hide fab based on whether autocomplete textview has focus or not
holder.autoCompleteTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
((ImageDetailSliderActivity)context).hideFab();
} else {
((ImageDetailSliderActivity)context).showFab();
}
}
});
LogUtil.i(TAG, "Id of image = " + item.getPhotoId());
PhotoAPI photoAPI = restAdapter.create(PhotoAPI.class);
photoAPI.getFeed(item.getPhotoId(), new Callback<ImageItem>() {
#Override
public void success(final ImageItem photoDetails, Response response) {
LogUtil.i(TAG, "photo api successful");
DialogUtils.safelyDismissDialog(progressDialog);
holder.locationIcon.setVisibility(View.VISIBLE);
if (TextUtils.isEmpty(item.getPhotoUrl())) {
imageUrl = photoDetails.getPhotoUrl();
item.setPhotoUrl(photoDetails.getPhotoUrl());
Uri uri = Uri.parse(photoDetails.getPhotoUrl());
ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
.setProgressiveRenderingEnabled(true)
.build();
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setImageRequest(request)
.setOldController(holder.image.getController())
.build();
holder.image.setController(controller);
}
if (photoDetails.isOwner()) {
holder.buttonBookmark.setVisibility(View.GONE);
holder.bar.setVisibility(View.VISIBLE);
holder.deletePhoto.setVisibility(View.VISIBLE);
holder.separator.setVisibility(View.VISIBLE);
if (TextUtils.isEmpty(photoDetails.getCaption())) {
holder.addCaption.setVisibility(View.VISIBLE);
} else {
holder.updateCaption1.setVisibility(View.VISIBLE);
}
if (TextUtils.isEmpty(photoDetails.getLocation())) {
holder.loc.setVisibility(View.GONE);
showAutoComplete();
} else {
holder.loc.setVisibility(View.VISIBLE);
holder.location.setText(photoDetails.getLocation());
showEditOrRemove();
}
if (photoDetails.getCampaignInfo() != null) {
showCleartripCampaign(photoDetails.getCampaignInfo());
} else {
showAddToExisting();
}
} else {
if (TextUtils.isEmpty(photoDetails.getLocation())) {
holder.loc.setVisibility(View.GONE);
} else {
holder.loc.setVisibility(View.VISIBLE);
holder.location.setText(photoDetails.getLocation());
}
}
if (!TextUtils.isEmpty(photoDetails.getCaption())) {
holder.caption.setText(photoDetails.getCaption());
} else {
holder.caption.setVisibility(View.GONE);
}
holder.time.setText(photoDetails.getTime());
holder.username.setText(photoDetails.getUserName());
holder.userFives.setText(String.format("%s Karma", Integer.toString(photoDetails.getUserKarma())));
holder.numComments.setText(Integer.toString(photoDetails.getNumComments()));
holder.numComments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, CommentsActivity.class);
intent.putExtra(KEY_SEND_PHOTO_ID, item.getPhotoId());
context.startActivity(intent);
}
});
holder.commentIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, CommentsActivity.class);
intent.putExtra(KEY_SEND_PHOTO_ID, item.getPhotoId());
context.startActivity(intent);
}
});
holder.updateCaption1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateCaption();
}
});
holder.addCaption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateCaption();
}
});
Picasso.with(context)
.load(photoDetails.getProfilePic())
.placeholder(R.drawable.feed_shape_profile_pic)
.resize(radius, radius)
.centerCrop()
.transform(new CircleTransform())
.into(holder.profilePic);
holder.profilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, UserProfileActivity.class);
intent.putExtra(KEY_SEND_USER_ID, Integer.toString(photoDetails.getOwnerPk()));
context.startActivity(intent);
}
});
imageGalleryAdapter = new ImageGalleryAdapter(context, photoDetails.getGalleries(), item.getPhotoId());
holder.galleryList.setAdapter(imageGalleryAdapter);
setListViewHeightBasedOnChildren(holder.galleryList);
latestComments = photoDetails.getLatestComments();
imageCommentAdapter = new ImageCommentAdapter(context, latestComments);
holder.commentList.setAdapter(imageCommentAdapter);
setListViewHeightBasedOnChildren(holder.commentList);
if (photoDetails.isBookmarked()) {
Picasso.with(context)
.load(R.drawable.cta_button_bookmark_secondary_state)
.into(holder.buttonBookmark);
} else {
Picasso.with(context)
.load(R.drawable.cta_button_bookmark_default_state)
.into(holder.buttonBookmark);
}
holder.buttonBookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!photoDetails.isBookmarked()) {
Picasso.with(context)
.load(R.drawable.cta_button_bookmark_secondary_state)
.into(holder.buttonBookmark);
photoDetails.setIsBookmarked(true);
BookmarkUserAPI api = restAdapter.create(BookmarkUserAPI.class);
api.post(Integer.toString(photoDetails.getOwnerPk()), new Callback<ActionResponse>() {
#Override
public void success(ActionResponse actionResponse, Response response) {
LogUtil.i(TAG, "bookmark successful");
}
#Override
public void failure(RetrofitError error) {
LogUtil.i(TAG, "bookmark failed");
}
});
} else {
Picasso.with(context)
.load(R.drawable.cta_button_bookmark_default_state)
.into(holder.buttonBookmark);
photoDetails.setIsBookmarked(false);
UnBookmarkUserAPI api = restAdapter.create(UnBookmarkUserAPI.class);
api.post(Integer.toString(photoDetails.getOwnerPk()), new Callback<ActionResponse>() {
#Override
public void success(ActionResponse actionResponse, Response response) {
LogUtil.i(TAG, "unbookmark successful");
}
#Override
public void failure(RetrofitError error) {
LogUtil.i(TAG, "unbookmark failed");
}
});
}
}
});
holder.deletePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
updateNeeded = true;
FeedFragment.updateDelete(updateNeeded);
GalleryActivity.updateDelete(updateNeeded);
updateNeeded = !updateNeeded;
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_delete);
dialog.show();
TextView cancel = (TextView) dialog.findViewById(R.id.textView174);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogUtils.safelyDismissDialog(dialog);
}
});
TextView deleteButton = (TextView) dialog.findViewById(R.id.textView175);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DeletePhotoAPI deletePhotoAPI = restAdapter.create(DeletePhotoAPI.class);
deletePhotoAPI.delete(item.getPhotoId(), new Callback<ActionResponse>() {
#Override
public void success(ActionResponse actionResponse, Response response) {
LogUtil.i(TAG, "image deleted successfully");
Toast.makeText(context.getApplicationContext(), "Image deleted successfully", Toast.LENGTH_SHORT).show();
((ImageDetailSliderActivity) context).finish();
}
#Override
public void failure(RetrofitError error) {
LogUtil.i(TAG, "image could not be deleted");
}
});
}
});
}
});
commentId = Integer.toString(photoDetails.getPk());
holder.postButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
postComment();
}
});
holder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, AlternateFullImageActivity.class);
intent.putExtra(KEY_SEND_PHOTO_ID, item.getPhotoId());
intent.putExtra(KEY_SEND_PHOTO_URL, item.getPhotoUrl());
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
((ImageDetailSliderActivity)context).overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
});
}
#Override
public void failure(RetrofitError error) {
LogUtil.i(TAG, "photo api failed");
}
});
container.addView(view);
return view;
}
#Override
public int getCount() {
return list == null ? 0 : list.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
LogUtil.i(TAG, "onConnectionFailed called");
}
public static class ViewHolder {
#Bind(R.id.imageView102)
SimpleDraweeView image;
#Bind(R.id.textView38)
TextView caption;
#Bind(R.id.textView39)
TextView time;
#Bind(R.id.textView45)
TextView username;
#Bind(R.id.textView46)
TextView userFives;
#Bind(R.id.imageView107)
ImageView profilePic;
#Bind(R.id.listView2)
ListView galleryList;
#Bind(R.id.textView57)
TextView seeAll;
#Bind(R.id.listView6)
ListView commentList;
#Bind(R.id.editText6)
EditText writeComment;
#Bind(R.id.imageView108)
ImageView buttonBookmark;
#Bind(R.id.imageView233)
ImageView editButton;
#Bind(R.id.textView151)
TextView numComments;
#Bind(R.id.textView82)
TextView bar;
#Bind(R.id.textView83)
TextView deletePhoto;
#Bind(R.id.textView79)
TextView comment;
#Bind(R.id.imageView116)
ImageView userDp;
#Bind(R.id.rel)
RelativeLayout rel;
#Bind(R.id.imageView131)
ImageView postButton;
#Bind(R.id.editText15)
EditText editCaption;
#Bind(R.id.textView184)
TextView separator;
#Bind(R.id.textView185)
TextView updateCaption1;
#Bind(R.id.textView186)
TextView updateCaption2;
#Bind(R.id.loc)
LinearLayout loc;
#Bind(R.id.textView115)
TextView location;
#Bind(R.id.locAuto)
RelativeLayout locAuto;
#Bind(R.id.autoCompleteTextView)
AutoCompleteTextView autoCompleteTextView;
#Bind(R.id.locEdit)
LinearLayout locEdit;
#Bind(R.id.editLocation)
TextView editLocation;
#Bind(R.id.removeLocation)
TextView removeLocation;
#Bind(R.id.scrollView)
ScrollView scrollView;
#Bind(R.id.imageView173)
ImageView locationIcon;
#Bind(R.id.textView5)
TextView addCaption;
#Bind(R.id.imageView11)
ImageView commentIcon;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
just add this method to your Class
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
it will render every time when you enter to particular layout. this is the override method of pagerAdapter.