When I run the codes, it does not show any error. I have no problem to login as guardian but when I try to login as elderly it couldn't and I don't know what's the problem. What I want is when a user input the username and password, it will validate from database and direct the user according to different user type.
Segment codes of Login.java:
private Boolean validateUsername() {
String val = username.getEditText().getText().toString();
if (val.isEmpty()) {
username.setError("Field cannot be empty");
return false;
} else {
username.setError(null);
username.setErrorEnabled(false);
return true;
}
}
private Boolean validatePassword() {
String val = password.getEditText().getText().toString();
if (val.isEmpty()) {
password.setError("Field cannot be empty");
return false;
} else {
password.setError(null);
password.setErrorEnabled(false);
return true;
}
}
public void loginUser(View view) {
//validate login info
if (!validateUsername() || !validatePassword()) {
return;
} else {
isUser();
}
}
private void isUser() {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("user").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String input1 = username.getEditText().getText().toString();
String input2 = password.getEditText().getText().toString();
if (dataSnapshot.child(input1).exists()) {
if (dataSnapshot.child(input1).child("password").getValue(String.class).equals(input2)) {
if (active.isChecked()) {
if (dataSnapshot.child(input1).child("radioGuardian").getValue(String.class).equals("Guardian")) {
preferences.setDataLogin(Login.this, true);
preferences.setDataAs(Login.this, "Guardian");
startActivity(new Intent(Login.this, dashboardGuardian.class));
} else if (dataSnapshot.child(input1).child("radioElderly").getValue(String.class).equals("Elderly")) {
preferences.setDataLogin(Login.this, true);
preferences.setDataAs(Login.this, "Elderly");
startActivity(new Intent(Login.this, dashboardUser.class));
}
} else {
if (dataSnapshot.child(input1).child("radioGuardian").getValue(String.class).equals("Guardian")) {
preferences.setDataLogin(Login.this, false);
startActivity(new Intent(Login.this, dashboardGuardian.class));
} else if (dataSnapshot.child(input1).child("radioElderly").getValue(String.class).equals("Elderly")) {
preferences.setDataLogin(Login.this, false);
startActivity(new Intent(Login.this, dashboardUser.class));
}
}
} else {
password.setError("Wrong Password");
password.requestFocus();
}
} else {
username.setError("No such User exist");
username.requestFocus();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
protected void onStart() {
super.onStart();
if (preferences.getDataLogin(this)) {
if (preferences.getDataAs(this).equals("Guardian")) {
startActivity(new Intent(this, dashboardGuardian.class));
finish();
} else {
startActivity(new Intent(this, dashboardUser.class));
finish();
}
}
}
}
Codes of Register.java:
public class Register extends AppCompatActivity {
//Variables
TextInputLayout regUsername, regEmail, regPhoneNo, regPassword;
RadioGroup radioGroup;
RadioButton selectedElderly, selectedGuardian;
Button regBtn, regToLoginBtn;
UserHelperClass helperClass;
int i = 0;
FirebaseDatabase rootNode;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//Hooks to all xml elements in activity_register.xml
regUsername = findViewById(R.id.reg_username);
regEmail = findViewById(R.id.reg_email);
regPhoneNo = findViewById(R.id.reg_phoneNo);
regPassword = findViewById(R.id.reg_password);
regBtn = findViewById(R.id.reg_btn);
regToLoginBtn = findViewById(R.id.reg_login_btn);
radioGroup = findViewById(R.id.radio_type);
selectedGuardian = findViewById(R.id.radioGuardian);
selectedElderly = findViewById(R.id.radioElderly);
helperClass = new UserHelperClass();
regBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validateUsername() && validateEmail() && validatePhoneNo() && validateUserType() && validatePassword() == true) {
Intent intent = new Intent(Register.this, Login.class);
startActivity(intent);
} else {
validateUsername();
validateEmail();
validatePhoneNo();
validateUserType();
validatePassword();
}
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("user");
//Get all the values
String m1 = selectedElderly.getText().toString();
String m2 = selectedGuardian.getText().toString();
String username = regUsername.getEditText().getText().toString();
String password = regPassword.getEditText().getText().toString();
helperClass.setUsername(regUsername.getEditText().getText().toString());
helperClass.setEmail(regEmail.getEditText().getText().toString());
helperClass.setPhoneNo(regPhoneNo.getEditText().getText().toString());
helperClass.setPassword(regPassword.getEditText().getText().toString());
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
} else {
helperClass.setRadioGuardian(m2);
}
reference.child(username).setValue(helperClass);
}
});
regToLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Register.this, Login.class);
startActivity(intent);
}
});
}
private Boolean validateUsername() {
String val = regUsername.getEditText().getText().toString();
String noWhiteSpace = "\\A\\w{4,20}\\z";
if (val.isEmpty()) {
regUsername.setError("Field cannot be empty");
return false;
} else if (val.length() >= 15) {
regUsername.setError("Username too long");
return false;
} else if (!val.matches(noWhiteSpace)) {
regUsername.setError("White space is not allowed");
return false;
} else {
regUsername.setError(null);
regUsername.setErrorEnabled(false);
return true;
}
}
private Boolean validateEmail() {
String val = regEmail.getEditText().getText().toString();
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (val.isEmpty()) {
regEmail.setError("Field cannot be empty");
return false;
} else if (!val.matches(emailPattern)) {
regEmail.setError("Invalid email address");
return false;
} else {
regEmail.setError(null);
return true;
}
}
private Boolean validatePhoneNo() {
String val = regPhoneNo.getEditText().getText().toString();
if (val.isEmpty()) {
regPhoneNo.setError("Field cannot be empty");
return false;
} else {
regPhoneNo.setError(null);
return true;
}
}
private Boolean validateUserType() {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(this, "Please select user type", Toast.LENGTH_SHORT).show();
return false;
} else {
return true;
}
}
private Boolean validatePassword() {
String val = regPassword.getEditText().getText().toString();
String passwordVal = "^" +
"(?=.*[0-9])" + //at least 1 digit
"(?=.*[a-z])" + //at least 1 lower case letter
"(?=.*[A-Z])" + //at least 1 upper case letter
"(?=.*[a-zA-Z])" + //any letter
"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=\\S+$)" + //no white space
".{4,}" + //at least 4 characters
"$";
if (val.isEmpty()) {
regPassword.setError("Field cannot be empty");
return false;
} else if (!val.matches(passwordVal)) {
regPassword.setError("Password is too weak");
return false;
} else {
regPassword.setError(null);
regPassword.setErrorEnabled(false);
return true;
}
}
public void registerUser(View view) {
if (!validateUsername() | !validatePassword() | !validatePhoneNo() | !validateEmail() | validateUserType()) {
return;
}
//Get all the values
String m1 = selectedElderly.getText().toString();
String m2 = selectedGuardian.getText().toString();
helperClass.setUsername(regUsername.getEditText().getText().toString());
helperClass.setEmail(regEmail.getEditText().getText().toString());
helperClass.setPhoneNo(regPhoneNo.getEditText().getText().toString());
helperClass.setPassword(regPassword.getEditText().getText().toString());
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
} else {
helperClass.setRadioGuardian(m2);
}
reference.child(String.valueOf(i + 1)).setValue(helperClass);
}
}
Database structure
If you post your database structure that would be more helpful.
As per your code.
you have two children in input1
'radioGuardian' and 'radioElderly'
have you added both values on registration? Or it will be null. And it will produce nullPointEx.
Hence the issue is here!
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
} else {
helperClass.setRadioGuardian(m2);
}
Try to change it to:-
if (selectedElderly.isChecked()) {
helperClass.setRadioElderly(m1);
helperClass.setRadioGuardian("NA");
} else {
helperClass.setRadioGuardian(m2);
helperClass.setRadioElderly("NA");
}
I have a calculator app that crashes when the equals button is pressed and there is nothing in the EditText that it getTexts from. I have looked at the other questions with similar situations, but those suggestions are not working. I am new to android and would like any help. I also have the issue if I have a "0" in my EditText.setText(), the "0" stays in front of the other numbers when they are pressed. Please let me know if you need more of the code to help.
Here is the Logcat info
09-08 07:58:32.915 13726-13726/com.ruthadeaton.bld3.calculator
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ruthadeaton.bld3.calculator, PID: 13726
java.lang.NumberFormatException: empty String
atsun.misc.FloatingDecimal.readJavaFormatString
(FloatingDecimal.java:1842)
at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
at java.lang.Float.parseFloat(Float.java:451)
at com.ruthadeaton.bld3.calculator.MainActivity$26.onClick
(MainActivity.java :346)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run
(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Here is my code:
buttonEqual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mValueTwo=Float.parseFloat(edt1.getText() + "");
if (mAddition == true) {
edt1.setText(mValueOne + mValueTwo + "");
mAddition=false;
}
if (mSubtract == true) {
edt1.setText(mValueOne - mValueTwo + "");
mSubtract=false;
}
if (mMultiplication == true) {
edt1.setText(mValueOne * mValueTwo + "");
mMultiplication=false;
}
if (mDivision == true) {
edt1.setText(mValueOne / mValueTwo + "");
mDivision=false;
}
}
});
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edt1.setText(edt1.getText() + "0");
}
});
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mValueOne=Float.parseFloat(edt1.getText() + "");
mAddition=true;
edt1.setText(null);
}
});
buttonSub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mValueOne=Float.parseFloat(edt1.getText() + "");
mSubtract=true;
edt1.setText(null);
}
});
buttonMul.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mValueOne=Float.parseFloat(edt1.getText() + "");
mMultiplication=true;
edt1.setText(null);
}
});
buttonDivision.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mValueOne=Float.parseFloat(edt1.getText() + "");
mDivision=true;
edt1.setText(null);
}
});
I have a calculator app that crashes when the equals button is pressed
and there is nothing in the EditText that it getTexts from.
Because you do not validate the input from users is valid or not. Obviously empty string is not a number that why the app crashes with NumberFormatExecption.
I also have the issue if I have a "0" in my EditText.setText(), the
"0" stays in front of the other numbers when they are pressed.
You can use TextWatcher to update the text view based on input from users.
I will guide you step by step how to fix those issues
First, define a method which validates input from users is a valid number or not.
private boolean isValidNumber(String numberInString) {
try {
Float.parseFloat(numberInString);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Second, each time users press on a arithmetic operator (+, -, *, /) or equal (=) the app will get value from the edt1. Then write a method to do that to avoid duplicate code.
/**
* Get current input from user and try parse it to a number.
*
* #return a number if input is valid, otherwise return null.
*/
private Float getInputValue() {
Float possibleNumber = null;
String numberInString = edt1.getText().toString();
if (isValidNumber(numberInString)) {
possibleNumber = Float.parseFloat(numberInString);
}
return possibleNumber;
}
Third, prevent user from adding more than one zero number by using TextWatcher.
edt1.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) {
}
#Override
public void afterTextChanged(Editable s) {
String content = s.toString();
if (content.startsWith("0") && content.length() == 2 && Character.isDigit(content.charAt(1))) {
edt1.setText(String.valueOf(content.charAt(1)));
edt1.setSelection(1);
}
}
});
Finally put it together.
public class MainActivity extends AppCompatActivity {
// Your variables here
...
// Make these two variables is Float instead of float.
Float mValueOne;
Float mValueTwo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Your init view here
...
edt1.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) {
}
#Override
public void afterTextChanged(Editable s) {
String content = s.toString();
if (content.startsWith("0") && content.length() == 2 && Character.isDigit(content.charAt(1))) {
edt1.setText(String.valueOf(content.charAt(1)));
edt1.setSelection(1);
}
}
});
buttonEqual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mValueTwo = getInputValue();
if (mValueOne == null || mValueTwo == null) {
// One of there or both of two values are not valid then do nothing.
return;
}
if (mAddition) {
edt1.setText(String.valueOf(mValueOne + mValueTwo));
mAddition = false;
}
if (mSubtract) {
edt1.setText(String.valueOf(mValueOne + mValueTwo));
mSubtract = false;
}
if (mMultiplication) {
edt1.setText(String.valueOf(mValueOne + mValueTwo));
mMultiplication = false;
}
if (mDivision) {
edt1.setText(String.valueOf(mValueOne + mValueTwo));
mDivision = false;
}
}
});
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edt1.setText(String.valueOf(edt1.getText().toString() + "0"));
edt1.setSelection(edt1.getText().length());
}
});
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mValueOne = getInputValue();
mAddition = true;
edt1.setText(null);
}
});
buttonSub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mValueOne = getInputValue();
mSubtract = true;
edt1.setText(null);
}
});
buttonMul.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mValueOne = getInputValue();
mMultiplication = true;
edt1.setText(null);
}
});
buttonDivision.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mValueOne = getInputValue();
mDivision = true;
edt1.setText(null);
}
});
}
/**
* Get current input from user and try parse it to a number.
*
* #return a number if input is valid, otherwise return null.
*/
private Float getInputValue() {
Float possibleNumber = null;
String numberInString = edt1.getText().toString();
if (isValidNumber(numberInString)) {
possibleNumber = Float.parseFloat(numberInString);
}
return possibleNumber;
}
private boolean isValidNumber(String numberInString) {
try {
Float.parseFloat(numberInString);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
It can't do a
mValueTwo=Float.parseFloat(edt1.getText() + "");
if edt1.getText() is empty.
You can correct this using a try-catch.
buttonEqual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
mValueTwo=Float.parseFloat(edt1.getText() + "");
if (mAddition == true) {
edt1.setText(mValueOne + mValueTwo + "");
mAddition=false;
}
if (mSubtract == true) {
edt1.setText(mValueOne - mValueTwo + "");
mSubtract=false;
}
if (mMultiplication == true) {
edt1.setText(mValueOne * mValueTwo + "");
mMultiplication=false;
}
if (mDivision == true) {
edt1.setText(mValueOne / mValueTwo + "");
mDivision=false;
}
}catch(Exception e){
//eventually logging here
}
}
});
Else you can make some controls before doing the parseFloat
buttonEqual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String edt = edt1.getText().toString();
if(edt.matches("")){
//something like a toast to signal
}else{
mValueTwo=Float.parseFloat(edt1.getText() + "");
if (mAddition == true) {
edt1.setText(mValueOne + mValueTwo + "");
mAddition=false;
}
if (mSubtract == true) {
edt1.setText(mValueOne - mValueTwo + "");
mSubtract=false;
}
if (mMultiplication == true) {
edt1.setText(mValueOne * mValueTwo + "");
mMultiplication=false;
}
if (mDivision == true) {
edt1.setText(mValueOne / mValueTwo + "");
mDivision=false;
}
}
}
});
You can set a hint attribute in your edit text that way it disappears anytime a number is actually inserted.
android:hint="0"
Also for the 0 being in front, maybe you want your edit text to be of the number format
android:inputType = "numberDecimal"
You didn't paste a stacktrace of the crash but I will assume it's a null pointer exception
if (edt1.getText != null) { /* do whatever executions */}
Im using Exoplayer for HLS Streaming in my App. Its playing nicely but when i disconnect the internet connection and enable it again,Exo player does not resume the video play.
Exoplayer is handling this by default or do i need to manually handle this?
here is my code..`
public class PlayerActivity extends Activity implements SurfaceHolder.Callback, OnClickListener,
DemoPlayer.Listener, DemoPlayer.CaptionListener, DemoPlayer.Id3MetadataListener,
AudioCapabilitiesReceiver.Listener { public class PlayerActivity extends Activity implements SurfaceHolder.Callback, OnClickListener,
DemoPlayer.Listener, DemoPlayer.CaptionListener, DemoPlayer.Id3MetadataListener,
AudioCapabilitiesReceiver.Listener {
// For use within demo app code.
public static final String CONTENT_ID_EXTRA = "content_id";
public static final String CONTENT_TYPE_EXTRA = "content_type";
public static final String PROVIDER_EXTRA = "provider";
// For use when launching the demo app using adb.
private static final String CONTENT_EXT_EXTRA = "type";
private static final String TAG = "PlayerActivity";
private static final int MENU_GROUP_TRACKS = 1;
private static final int ID_OFFSET = 2;
private static final CookieManager defaultCookieManager;
static {
defaultCookieManager = new CookieManager();
defaultCookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
}
private EventLogger eventLogger;
private MediaController mediaController;
private View debugRootView;
private View shutterView;
private AspectRatioFrameLayout videoFrame;
private SurfaceView surfaceView;
private TextView debugTextView;
private TextView playerStateTextView;
private SubtitleLayout subtitleLayout;
private Button videoButton;
private Button audioButton;
private Button textButton;
private Button retryButton;
static TextView bitrateTextView;
private static DemoPlayer player;
private DebugTextViewHelper debugViewHelper;
private boolean playerNeedsPrepare;
private long playerPosition;
private boolean enableBackgroundAudio;
private Uri contentUri;
private int contentType;
private String contentId;
private String provider;
RotateAnimation rotate;
ImageView rotateLoad=null;
ImageView loadMid=null;
FrameLayout videoLoad;
private String vidLink ="";
private String title =""; private TextView vodTitle;
private String description =""; private TextView vodDesc;
private String vodimage =""; private ImageView vodThumb;
private String chimage =""; private ImageView chLogo;
private String datetitle =""; private TextView vodTimeDesc, videoCurrentTime, videoTimeEnd;
private Bitmap vodImgThumb, chImgLogo;
private static FrameLayout guideInfo;
private FrameLayout seekBar;
private FrameLayout playPause;
private int rewindRate = 1;
private int forwardRate = 1, stopPosition ;
private SeekBar sb;
CountDownTimer ct;
int infoFade = 0 , seekFade =0 , height, width;
private boolean isPlaying = false;
static long storeBitRate;
private AudioCapabilitiesReceiver audioCapabilitiesReceiver;
// Activity lifecycle
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_activity);
View root = findViewById(R.id.root);
shutterView = findViewById(R.id.shutter);
debugRootView = findViewById(R.id.controls_root);
videoFrame = (AspectRatioFrameLayout) findViewById(R.id.video_frame);
surfaceView = (SurfaceView) findViewById(R.id.surface_view);
surfaceView.getHolder().addCallback(this);
debugTextView = (TextView) findViewById(R.id.debug_text_view);
playerStateTextView = (TextView) findViewById(R.id.player_state_view);
subtitleLayout = (SubtitleLayout) findViewById(R.id.subtitles);
mediaController = new KeyCompatibleMediaController(this);
mediaController.setAnchorView(root);
// retryButton = (Button) findViewById(R.id.retry_button);
// retryButton.setOnClickListener(this);
videoButton = (Button) findViewById(R.id.video_controls);
audioButton = (Button) findViewById(R.id.audio_controls);
textButton = (Button) findViewById(R.id.text_controls);
playPause = (FrameLayout)findViewById(R.id.videoPlayPause);
videoLoad = (FrameLayout) findViewById(R.id.videoLoad);
sb = (SeekBar)findViewById(R.id.seekBar1);
// Guide Info Animator
guideInfo = (FrameLayout)findViewById(R.id.guide_info);
seekBar = (FrameLayout)findViewById(R.id.video_seek);
playPause = (FrameLayout)findViewById(R.id.videoPlayPause);
videoCurrentTime = (TextView)findViewById(R.id.video_timestart);
bitrateTextView=(TextView)findViewById(R.id.bitratetext);
videoTimeEnd = (TextView)findViewById(R.id.video_timeend);
seekBar.setVisibility(View.GONE);
playPause.setVisibility(View.GONE);
root.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_ESCAPE
|| keyCode == KeyEvent.KEYCODE_MENU) {
return false;
}
if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
}
return mediaController.dispatchKeyEvent(event);
}
});
CookieHandler currentHandler = CookieHandler.getDefault();
if (currentHandler != defaultCookieManager) {
CookieHandler.setDefault(defaultCookieManager);
}
audioCapabilitiesReceiver = new AudioCapabilitiesReceiver(this, this);
audioCapabilitiesReceiver.register();
}
#Override
public void onNewIntent(Intent intent) {
releasePlayer();
playerPosition = 0;
setIntent(intent);
}
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
Bundle extras = getIntent().getExtras();
contentUri = intent.getData();
contentType = Util.TYPE_HLS;
title = extras.getString("title", title);
description = extras.getString("description", description);
vodimage = extras.getString("vodimage", vodimage);
chimage = extras.getString("chimage", chimage);
datetitle = extras.getString("datetitle", datetitle);
// Set Data
vodTitle = (TextView)findViewById(R.id.vodTitle);
vodTitle.setText(title);
vodDesc = (TextView)findViewById(R.id.vodDesc);
/* DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter(player.getMainHandler(), null);
String dfg=bandwidthMeter.getBitrateEstimate()+"";*/
vodDesc.setText(description);
vodThumb = (ImageView)findViewById(R.id.vodThumb);
chLogo = (ImageView)findViewById(R.id.chLogo);
vodTimeDesc = (TextView)findViewById(R.id.vodTimeDesc);
vodTimeDesc.setText(datetitle);
rotate = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(2000);
rotate.setRepeatCount(Animation.INFINITE);
rotate.setInterpolator(new LinearInterpolator());
rotateLoad= (ImageView) findViewById(R.id.lycaLoadMid_rotate);
loadMid = (ImageView) findViewById(R.id.lycaLoadMid);
rotateLoad.startAnimation(rotate);
videoLoad = (FrameLayout) findViewById(R.id.videoLoad);
//Gathering images
LoadImages loadImage= new LoadImages ();
loadImage.execute(vodimage,chimage);
if (player == null) {
// if (!maybeRequestPermission()) {
preparePlayer(true);
//}
} else {
player.setBackgrounded(false);
}
}
#Override
public void onPause() {
super.onPause();
if (!enableBackgroundAudio) {
releasePlayer();
} else {
player.setBackgrounded(true);
}
shutterView.setVisibility(View.VISIBLE);
}
#Override
public void onDestroy() {
super.onDestroy();
audioCapabilitiesReceiver.unregister();
releasePlayer();
}
// OnClickListener methods
#Override
public void onClick(View view) {
if (view == retryButton) {
preparePlayer(true);
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
// AudioCapabilitiesReceiver.Listener methods
#Override
public void onAudioCapabilitiesChanged(AudioCapabilities audioCapabilities) {
if (player == null) {
return;
}
boolean backgrounded = player.getBackgrounded();
boolean playWhenReady = player.getPlayWhenReady();
releasePlayer();
preparePlayer(playWhenReady);
player.setBackgrounded(backgrounded);
}
// Permission request listener method
// Internal methods
private RendererBuilder getRendererBuilder() {
String userAgent = Util.getUserAgent(this, "ExoPlayerDemo");
switch (contentType) {
case Util.TYPE_SS:
return new SmoothStreamingRendererBuilder(this, userAgent, contentUri.toString(),
new SmoothStreamingTestMediaDrmCallback());
case Util.TYPE_DASH:
return new DashRendererBuilder(this, userAgent, contentUri.toString(),
new WidevineTestMediaDrmCallback(contentId, provider));
case Util.TYPE_HLS:
return new HlsRendererBuilder(this, userAgent, contentUri.toString());
case Util.TYPE_OTHER:
return new ExtractorRendererBuilder(this, userAgent, contentUri);
default:
throw new IllegalStateException("Unsupported type: " + contentType);
}
}
private void preparePlayer(boolean playWhenReady) {
if (player == null) {
player = new DemoPlayer(getRendererBuilder());
player.addListener(this);
player.setCaptionListener(this);
player.setMetadataListener(this);
player.seekTo(playerPosition);
playerNeedsPrepare = true;
mediaController.setMediaPlayer(player.getPlayerControl());
mediaController.setEnabled(true);
eventLogger = new EventLogger();
eventLogger.startSession();
player.addListener(eventLogger);
player.setInfoListener(eventLogger);
player.setInternalErrorListener(eventLogger);
//debugViewHelper = new DebugTextViewHelper(player, debugTextView);
// debugViewHelper.start();
}
if (playerNeedsPrepare) {
player.prepare();
playerNeedsPrepare = false;
updateButtonVisibilities();
}
player.setSurface(surfaceView.getHolder().getSurface());
player.setPlayWhenReady(playWhenReady);
guideInfo.setVisibility(View.VISIBLE);
guideInfo.postDelayed(new Runnable() { public void run() { guideInfo.setVisibility(View.GONE); } }, 5000);
}
private void releasePlayer() {
if (player != null) {
debugViewHelper.stop();
debugViewHelper = null;
playerPosition = player.getCurrentPosition();
player.release();
player = null;
eventLogger.endSession();
eventLogger = null;
}
}
// DemoPlayer.Listener implementation
#Override
public void onStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == ExoPlayer.STATE_ENDED) {
showControls();
}
if (playbackState == ExoPlayer.STATE_BUFFERING) {
if(videoLoad.getVisibility()==View.GONE){
videoLoad.setVisibility(View.VISIBLE);
}
}
if (playbackState == ExoPlayer.STATE_READY) {
videoLoad.setVisibility(View.GONE);
}
if (playbackState == ExoPlayer.STATE_ENDED) {
videoLoad.setVisibility(View.GONE);
finish();
}
if(playWhenReady){
}
String text = "playWhenReady=" + playWhenReady + ", playbackState=";
switch(playbackState) {
case ExoPlayer.STATE_BUFFERING:
text += "buffering";
break;
case ExoPlayer.STATE_ENDED:
text += "ended";
break;
case ExoPlayer.STATE_IDLE:
text += "idle";
break;
case ExoPlayer.STATE_PREPARING:
text += "preparing";
break;
case ExoPlayer.STATE_READY:
text += "ready";
break;
default:
text += "unknown";
break;
}
// playerStateTextView.setText(text);
updateButtonVisibilities();
}
#Override
public void onError(Exception e) {
String errorString = null;
if (e instanceof UnsupportedDrmException) {
// Special case DRM failures.
UnsupportedDrmException unsupportedDrmException = (UnsupportedDrmException) e;
errorString = getString(Util.SDK_INT < 18 ? R.string.error_drm_not_supported
: unsupportedDrmException.reason == UnsupportedDrmException.REASON_UNSUPPORTED_SCHEME
? R.string.error_drm_unsupported_scheme : R.string.error_drm_unknown);
} else if (e instanceof ExoPlaybackException
&& e.getCause() instanceof DecoderInitializationException) {
// Special case for decoder initialization failures.
DecoderInitializationException decoderInitializationException =
(DecoderInitializationException) e.getCause();
if (decoderInitializationException.decoderName == null) {
if (decoderInitializationException.getCause() instanceof DecoderQueryException) {
errorString = getString(R.string.error_querying_decoders);
} else if (decoderInitializationException.secureDecoderRequired) {
errorString = getString(R.string.error_no_secure_decoder,
decoderInitializationException.mimeType);
} else {
errorString = getString(R.string.error_no_decoder,
decoderInitializationException.mimeType);
}
}
else {
errorString = getString(R.string.error_instantiating_decoder,
decoderInitializationException.decoderName);
}
}
if (errorString != null) {
Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_LONG).show();
}
playerNeedsPrepare = true;
updateButtonVisibilities();
showControls();
}
#Override
public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees,
float pixelWidthAspectRatio) {
shutterView.setVisibility(View.GONE);
videoFrame.setAspectRatio(
height == 0 ? 1 : (width * pixelWidthAspectRatio) / height);
}
// User controls
private void updateButtonVisibilities() {
// retryButton.setVisibility(playerNeedsPrepare ? View.VISIBLE : View.GONE);
videoButton.setVisibility(haveTracks(DemoPlayer.TYPE_VIDEO) ? View.VISIBLE : View.GONE);
audioButton.setVisibility(haveTracks(DemoPlayer.TYPE_AUDIO) ? View.VISIBLE : View.GONE);
textButton.setVisibility(haveTracks(DemoPlayer.TYPE_TEXT) ? View.VISIBLE : View.GONE);
}
private boolean haveTracks(int type) {
return player != null && player.getTrackCount(type) > 0;
}
public void showVideoPopup(View v) {
PopupMenu popup = new PopupMenu(this, v);
configurePopupWithTracks(popup, null, DemoPlayer.TYPE_VIDEO);
popup.show();
}
public void showAudioPopup(View v) {
PopupMenu popup = new PopupMenu(this, v);
Menu menu = popup.getMenu();
menu.add(Menu.NONE, Menu.NONE, Menu.NONE, R.string.enable_background_audio);
final MenuItem backgroundAudioItem = menu.findItem(0);
backgroundAudioItem.setCheckable(true);
backgroundAudioItem.setChecked(enableBackgroundAudio);
OnMenuItemClickListener clickListener = new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
if (item == backgroundAudioItem) {
enableBackgroundAudio = !item.isChecked();
return true;
}
return false;
}
};
configurePopupWithTracks(popup, clickListener, DemoPlayer.TYPE_AUDIO);
popup.show();
}
public void showTextPopup(View v) {
PopupMenu popup = new PopupMenu(this, v);
configurePopupWithTracks(popup, null, DemoPlayer.TYPE_TEXT);
popup.show();
}
public void showVerboseLogPopup(View v) {
PopupMenu popup = new PopupMenu(this, v);
Menu menu = popup.getMenu();
menu.add(Menu.NONE, 0, Menu.NONE, R.string.logging_normal);
menu.add(Menu.NONE, 1, Menu.NONE, R.string.logging_verbose);
menu.setGroupCheckable(Menu.NONE, true, true);
menu.findItem((VerboseLogUtil.areAllTagsEnabled()) ? 1 : 0).setChecked(true);
popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == 0) {
VerboseLogUtil.setEnableAllTags(false);
} else {
VerboseLogUtil.setEnableAllTags(true);
}
return true;
}
});
popup.show();
}
private void configurePopupWithTracks(PopupMenu popup,
final OnMenuItemClickListener customActionClickListener,
final int trackType) {
if (player == null) {
return;
}
int trackCount = player.getTrackCount(trackType);
if (trackCount == 0) {
return;
}
popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
return (customActionClickListener != null
&& customActionClickListener.onMenuItemClick(item))
|| onTrackItemClick(item, trackType);
}
});
Menu menu = popup.getMenu();
// ID_OFFSET ensures we avoid clashing with Menu.NONE (which equals 0).
menu.add(MENU_GROUP_TRACKS, DemoPlayer.TRACK_DISABLED + ID_OFFSET, Menu.NONE, R.string.off);
for (int i = 0; i < trackCount; i++) {
menu.add(MENU_GROUP_TRACKS, i + ID_OFFSET, Menu.NONE,
buildTrackName(player.getTrackFormat(trackType, i)));
}
menu.setGroupCheckable(MENU_GROUP_TRACKS, true, true);
menu.findItem(player.getSelectedTrack(trackType) + ID_OFFSET).setChecked(true);
}
private static String buildTrackName(MediaFormat format) {
if (format.adaptive) {
return "auto";
}
String trackName;
if (MimeTypes.isVideo(format.mimeType)) {
trackName = joinWithSeparator(joinWithSeparator(buildResolutionString(format),
buildBitrateString(format)), buildTrackIdString(format));
} else if (MimeTypes.isAudio(format.mimeType)) {
trackName = joinWithSeparator(joinWithSeparator(joinWithSeparator(buildLanguageString(format),
buildAudioPropertyString(format)), buildBitrateString(format)),
buildTrackIdString(format));
} else {
trackName = joinWithSeparator(joinWithSeparator(buildLanguageString(format),
buildBitrateString(format)), buildTrackIdString(format));
}
return trackName.length() == 0 ? "unknown" : trackName;
}
private static String buildResolutionString(MediaFormat format) {
return format.width == MediaFormat.NO_VALUE || format.height == MediaFormat.NO_VALUE
? "" : format.width + "x" + format.height;
}
private static String buildAudioPropertyString(MediaFormat format) {
return format.channelCount == MediaFormat.NO_VALUE || format.sampleRate == MediaFormat.NO_VALUE
? "" : format.channelCount + "ch, " + format.sampleRate + "Hz";
}
private static String buildLanguageString(MediaFormat format) {
return TextUtils.isEmpty(format.language) || "und".equals(format.language) ? ""
: format.language;
}
private static String buildBitrateString(MediaFormat format) {
String s=format.bitrate == MediaFormat.NO_VALUE ? ""
: String.format(Locale.US, "%.2fMbit", format.bitrate / 1000000f);
// Toast.makeText(con, s, Toast.LENGTH_LONG).show();
return s;
}
private static String joinWithSeparator(String first, String second) {
return first.length() == 0 ? second : (second.length() == 0 ? first : first + ", " + second);
}
private static String buildTrackIdString(MediaFormat format) {
return format.trackId == null ? "" : " (" + format.trackId + ")";
}
private boolean onTrackItemClick(MenuItem item, int type) {
if (player == null || item.getGroupId() != MENU_GROUP_TRACKS) {
return false;
}
player.setSelectedTrack(type, item.getItemId() - ID_OFFSET);
return true;
}
private void toggleControlsVisibility() { /*/////////////////////////////////// Showing defalut controllers */
if (mediaController.isShowing()) {
mediaController.hide();
debugRootView.setVisibility(View.GONE);
} else {
showControls();
}
}
private void showControls() {
mediaController.show(0);
debugRootView.setVisibility(View.VISIBLE);
}
// DemoPlayer.CaptionListener implementation
#Override
public void onCues(List<Cue> cues) {
subtitleLayout.setCues(cues);
}
// DemoPlayer.MetadataListener implementation
#Override
public void onId3Metadata(Map<String, Object> metadata) {
for (Map.Entry<String, Object> entry : metadata.entrySet()) {
if (TxxxMetadata.TYPE.equals(entry.getKey())) {
TxxxMetadata txxxMetadata = (TxxxMetadata) entry.getValue();
Log.i(TAG, String.format("ID3 TimedMetadata %s: description=%s, value=%s",
TxxxMetadata.TYPE, txxxMetadata.description, txxxMetadata.value));
} else if (PrivMetadata.TYPE.equals(entry.getKey())) {
PrivMetadata privMetadata = (PrivMetadata) entry.getValue();
Log.i(TAG, String.format("ID3 TimedMetadata %s: owner=%s",
PrivMetadata.TYPE, privMetadata.owner));
} else if (GeobMetadata.TYPE.equals(entry.getKey())) {
GeobMetadata geobMetadata = (GeobMetadata) entry.getValue();
Log.i(TAG, String.format("ID3 TimedMetadata %s: mimeType=%s, filename=%s, description=%s",
GeobMetadata.TYPE, geobMetadata.mimeType, geobMetadata.filename,
geobMetadata.description));
} else {
Log.i(TAG, String.format("ID3 TimedMetadata %s", entry.getKey()));
}
}
}
// SurfaceHolder.Callback implementation
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (player != null) {
player.setSurface(holder.getSurface());
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// Do nothing.
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (player != null) {
player.blockingClearSurface();
}
}
private void configureSubtitleView() {
CaptionStyleCompat style;
float fontScale;
if (Util.SDK_INT >= 19) {
style = getUserCaptionStyleV19();
fontScale = getUserCaptionFontScaleV19();
} else {
style = CaptionStyleCompat.DEFAULT;
fontScale = 1.0f;
}
subtitleLayout.setStyle(style);
subtitleLayout.setFractionalTextSize(SubtitleLayout.DEFAULT_TEXT_SIZE_FRACTION * fontScale);
}
#TargetApi(19)
private float getUserCaptionFontScaleV19() {
CaptioningManager captioningManager =
(CaptioningManager) getSystemService(Context.CAPTIONING_SERVICE);
return captioningManager.getFontScale();
}
#TargetApi(19)
private CaptionStyleCompat getUserCaptionStyleV19() {
CaptioningManager captioningManager =
(CaptioningManager) getSystemService(Context.CAPTIONING_SERVICE);
return CaptionStyleCompat.createFromCaptionStyle(captioningManager.getUserStyle());
}
/**
* Makes a best guess to infer the type from a media {#link Uri} and an optional overriding file
* extension.
*
* #param uri The {#link Uri} of the media.
* #param fileExtension An overriding file extension.
* #return The inferred type.
*/
private static int inferContentType(Uri uri, String fileExtension) {
String lastPathSegment = !TextUtils.isEmpty(fileExtension) ? "." + fileExtension
: uri.getLastPathSegment();
return Util.inferContentType(lastPathSegment);
}
private static final class KeyCompatibleMediaController extends MediaController {
private MediaController.MediaPlayerControl playerControl;
public KeyCompatibleMediaController(Context context) {
super(context);
}
#Override
public void setMediaPlayer(MediaController.MediaPlayerControl playerControl) {
super.setMediaPlayer(playerControl);
this.playerControl = playerControl;
}
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
int keyCode = event.getKeyCode();
if (playerControl.canSeekForward() && keyCode == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
playerControl.seekTo(playerControl.getCurrentPosition() + 15000); // milliseconds
BandwidthMeter bm=player.getBandwidthMeter();
Long l=bm.getBitrateEstimate();
storeBitRate=l;
bitrateTextView.setText(storeBitRate+" bits/sec");
show();
}
return true;
} else if (playerControl.canSeekBackward() && keyCode == KeyEvent.KEYCODE_MEDIA_REWIND) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
playerControl.seekTo(playerControl.getCurrentPosition() - 15000); // milliseconds
show();
}
return true;
}
return super.dispatchKeyEvent(event);
}
}
private class LoadImages extends AsyncTask<String, String, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//pDialog.setVisibility(View.VISIBLE);
}
protected Void doInBackground(String... args) {
try {
vodImgThumb = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
chImgLogo = BitmapFactory.decodeStream((InputStream)new URL(args[1]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
vodThumb.setImageBitmap(vodImgThumb);
chLogo.setImageBitmap(chImgLogo);
}
}
}
`
In demo of ExoPlayer this issue handle with retry button see how implemented here.
First of all set an ErrorListener to determined some error happened then just call following piece of code fix the issue:
if (playerNeedsPrepare) {
player.prepare();
playerNeedsPrepare = false;
updateButtonVisibilities();
}
player.setSurface(surfaceView.getHolder().getSurface());
player.setPlayWhenReady(playWhenReady);
ExoPlayer version 2.9 provides error handling customization via LoadErrorHandlingPolicy.
public final class CustomPolicy
extends DefaultLoadErrorHandlingPolicy {
#Override
public long getRetryDelayMsFor(
int dataType,
long loadDurationMs,
IOException exception,
int errorCount) {
// Replace NoConnectivityException with the corresponding
// exception for the used DataSource.
if (exception instanceof NoConnectivityException) {
return 5000; // Retry every 5 seconds.
} else {
return C.TIME_UNSET; // Anything else is surfaced.
}
}
#Override
public int getMinimumLoadableRetryCount(int dataType) {
return Integer.MAX_VALUE;
}
}
More https://medium.com/google-exoplayer/load-error-handling-in-exoplayer-488ab6908137
playbackPreparer will be called when playButton clicked while player.getPlaybackState() == Player.STATE_IDLE
PlayerControlView.java#L1111
playerView.setPlaybackPreparer {
simpleExoPlayer.prepare(
ExtractorMediaSource.Factory(source).createMediaSource(video),
false,
true
)
}
Create resume fun and do something like this:
player = [your exoPlayer]
fun resumeTrack() {
if (player.playbackError != null) {
player.retry();
}
setPlayWhenReady(true);
exoPlayer.playWhenReady = true
}
You can also do something like :
protected void play() {
if (null != getPlaybackError()) {
retry();
}
setPlayWhenReady(true);
}
Before you call player.play() in your onClick() method, just check if the player has a sourceException in playerError and call player.prepare() before calling play() like this in Kotlin:
player.playerError.takeIf { it?.sourceException is IOException }?.run {
player.prepare()
}
I am trying to sort the collection in custom arrayadapter and making a call to update the view . However, the view does not gets updated.
There are two values over which I want to sort (date and amount) and have a custom comparators for them.
I can see that the data itself has changed (i.e if a list item has gone outside of view after sorting and when it gets the view, the data it show is the correct data that should exist after sorting).
The second question is about the filter. The way the filter is implemented right now, it does not update the views either.
Here is code
public class SearchActivity extends BListActivity {
private Bundle sessionInfo;
private TransactionDetailsHandler transactionDetailsHandler = new TransactionDetailsHandler();
private static boolean ascDate = false;
private static boolean ascAmount = false;
private ArrayList<TransactionDetails> transactionDetails;
private ArrayList<TransactionDetails> filterResults;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sessionInfo = getIntent().getExtras();
final String sessionId = sessionInfo.getString("sessionId");
final String transactionResponse = sessionInfo
.getString(C.TRN_DETAIL_KEY);
try {
Xml.parse(transactionResponse, transactionDetailsHandler);
} catch (Exception ex) {
ex.printStackTrace();
}
final ArrayAdapter<TransactionDetails> adapter = getArrayAdapter();
findViewById(R.id.amount_btn).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
if (ascDate) {
adapter.sort(new TransactionDetailAmountComparatorAsc());
ascDate = false;
} else {
adapter.sort(new TransactionDetailAmountComparatorDesc());
ascDate = true;
}
adapter.notifyDataSetChanged();
}
});
findViewById(R.id.date_btn).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
if (ascAmount) {
adapter.sort(new TransactionDetailDateComparatorAsc());
ascAmount = false;
} else {
adapter.sort(new TransactionDetailDateComparatorDesc());
ascAmount = true;
}
adapter.notifyDataSetChanged();
}
});
findViewById(R.id.search_btn).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
findViewById(R.id.buttonLL).setVisibility(View.GONE);
findViewById(R.id.searchLL).setVisibility(View.VISIBLE);
}
});
findViewById(R.id.cancel_btn).setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
findViewById(R.id.searchLL).setVisibility(View.GONE);
findViewById(R.id.buttonLL).setVisibility(View.VISIBLE);
}
});
TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
System.out.println("XXXX Constraint = " + s);
adapter.getFilter().filter(s);
}
};
EditText et = (EditText) findViewById(R.id.edit_box);
et.addTextChangedListener(filterTextWatcher);
}
protected ArrayAdapter<TransactionDetails> getArrayAdapter() {
transactionDetails = transactionDetailsHandler
.getTransactionDetailsList();
filterResults = transactionDetails;
return new SearchListAdapter(this,
(List<TransactionDetails>) transactionDetails);
}
protected class SearchListAdapter extends ArrayAdapter<TransactionDetails> {
private int rId;
private List<TransactionDetails> data;
private Filter filter;
public SearchListAdapter(Context context, List<TransactionDetails> data) {
super(context, R.layout.search_list_item, data);
this.rId = R.layout.search_list_item;
this.data = data;
}
#Override
public View getView(int position, View cv, ViewGroup parent) {
cv = getLayoutInflater().inflate(rId, parent, false);
TransactionDetails item = data.get(position);
((TextView) cv.findViewById(R.id.t_id)).setText(item.getTrnId());
((TextView) cv.findViewById(R.id.date)).setText(item
.getTrnDatetime());
((TextView) cv.findViewById(R.id.amount)).setText(item
.getTrnAmount());
((TextView) cv.findViewById(R.id.card_num))
.setText("XXXX XXXX XXXX " + item.getTrnMaskedCard());
try {
if (item.getTrnCardType() != null
&& item.getTrnCardType().trim().length() > 0)
((ImageView) cv.findViewById(R.id.card_img))
.setImageResource(Integer.parseInt(item
.getTrnCardType()));
} catch (Exception ex) {
ex.printStackTrace();
}
((TextView) cv.findViewById(R.id.result)).setText(item
.getTrnStatus());
return cv;
}
#Override
public Filter getFilter() {
if (filter == null)
filter = new TransactionDetailFilter();
return filter;
}
private class TransactionDetailFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
System.out.println("XXXX Started filtering with Constraint = "
+ constraint);
FilterResults results = new FilterResults();
String prefix = constraint.toString().toLowerCase();
if (prefix == null || prefix.length() == 0) {
ArrayList<TransactionDetails> list = new ArrayList<TransactionDetails>(
transactionDetails);
results.values = list;
results.count = list.size();
} else {
final ArrayList<TransactionDetails> list = new ArrayList<TransactionDetails>(
transactionDetails);
final ArrayList<TransactionDetails> nlist = new ArrayList<TransactionDetails>();
int count = list.size();
System.out
.println("XXXX List to be search size = " + count);
for (int i = 0; i < count; i++) {
final TransactionDetails details = list.get(i);
System.out.println("XXXX List to be searched = "
+ details.toString());
if (details.getTrnId().startsWith(prefix)
|| details.getTrnDatetime().startsWith(prefix)
|| details.getTrnAmount().startsWith(prefix)
|| details.getTrnMaskedCard()
.startsWith(prefix)
|| details.getTrnStatus().startsWith(prefix)) {
System.out.println("XXXX Adding result "
+ details.toString());
nlist.add(details);
}
}
results.values = nlist;
results.count = nlist.size();
}
System.out.println("XXXX Ended filtering with Constraint = "
+ constraint + " . Result size = " + results.count);
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
System.out.println("XXXX Preparing to publish results. Result size = "+ results.count);
ArrayList<TransactionDetails> fitems = (ArrayList<TransactionDetails>) results.values;
clear();
int count = fitems.size();
for (int i = 0; i < count; i++) {
TransactionDetails details = (TransactionDetails) fitems
.get(i);
add(details);
}
notifyDataSetChanged();
System.out.println("XXXX Finished publishing results.");
}
}
#Override
public void add(TransactionDetails item) {
System.out.println("XXXX Adding items to be published." + item.toString());
filterResults.add(item);
}
}
// -------------------------------------------------------------------------------------------------------------------------------------------------
class TransactionDetailAmountComparatorAsc implements
Comparator<TransactionDetails> {
public int compare(TransactionDetails detail1,
TransactionDetails detail2) {
float f = Float.parseFloat(detail1.getTrnAmount())
- Float.parseFloat(detail2.getTrnAmount());
if (f > 0)
return 1;
if (f < 1)
return -1;
return 0;
}
}
class TransactionDetailAmountComparatorDesc implements
Comparator<TransactionDetails> {
public int compare(TransactionDetails detail1,
TransactionDetails detail2) {
float f = Float.parseFloat(detail1.getTrnAmount())
- Float.parseFloat(detail2.getTrnAmount());
if (f > 0)
return -1;
if (f < 1)
return 1;
return 0;
}
}
class TransactionDetailDateComparatorAsc implements
Comparator<TransactionDetails> {
public int compare(TransactionDetails detail1,
TransactionDetails detail2) {
detail1.getTrnDatetime();
detail2.getTrnDatetime();
String pattern = "MM/dd/yy HH:mm";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date1 = format.parse(detail1.getTrnDatetime());
Date date2 = format.parse(detail2.getTrnDatetime());
return date1.compareTo(date2);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
class TransactionDetailDateComparatorDesc implements
Comparator<TransactionDetails> {
public int compare(TransactionDetails detail1,
TransactionDetails detail2) {
detail1.getTrnDatetime();
detail2.getTrnDatetime();
String pattern = "MM/dd/yy HH:mm";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date1 = format.parse(detail1.getTrnDatetime());
Date date2 = format.parse(detail2.getTrnDatetime());
return -(date1.compareTo(date2));
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
position -= ((ListView) parent).getHeaderViewsCount();
TransactionDetails details = (TransactionDetails) parent.getAdapter()
.getItem(position);
Bundle b = new Bundle(sessionInfo);
b.putSerializable(C.TRN_DETAIL_KEY, details);
Util.openView(SearchActivity.this, TransDetailActivity.class, b);
}
#Override
protected int getContentView() {
return R.layout.search_layout;
}
#Override
protected int getStringArrayID() {
return 0;
}
#Override
protected Class<?>[] getDestinations() {
return null;
}
#Override
protected int getTitleId() {
return R.string.search;
}
}