I want to change my activity parent from ListActivity to AppCompatActivity, because I need to use check permission Granted and it's need AppCompat, but my activity is ListView.
I try this action, but not received a good result :(
This is my source code (Ever has ... is for no added code):
public class RingtoneSelectActivity extends ListActivity {
...
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
mShowAll = false;
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
showFinalAlert(getResources().getText(R.string.err_sdcard_readonly));
return;
}
if (status.equals(Environment.MEDIA_SHARED)) {
showFinalAlert(getResources().getText(R.string.err_sdcard_shared));
return;
}
if (!status.equals(Environment.MEDIA_MOUNTED)) {
showFinalAlert(getResources().getText(R.string.err_no_sdcard));
return;
}
Intent intent = getIntent();
mWasGetContentIntent = intent.getAction().equals(
Intent.ACTION_GET_CONTENT);
// Inflate our UI from its XML layout description.
setContentView(R.layout.media_select);
SplashHandler mHandler = new SplashHandler();
Message msg = new Message();
//Assign a unique code to the message.
//Later, this code will be used to identify the message in Handler class.
msg.what = 0;
// Send the message with a delay of 3 seconds(3000 = 3 sec).
mHandler.sendMessageDelayed(msg, 10000);
try {
mAdapter = new SimpleCursorAdapter(
this,
// Use a template that displays a text view
R.layout.media_select_row,
// Give the cursor to the list adatper
createCursor(""),
// Map from database columns...
new String[]{
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media._ID},
// To widget ids in the row layout...
new int[]{
R.id.row_artist,
R.id.row_album,
R.id.row_title,
R.id.row_icon,
R.id.row_options_button});
setListAdapter(mAdapter);
getListView().setItemsCanFocus(true);
// Normal click - open the editor
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent,
View view,
int position,
long id) {
startRingdroidEditor();
}
});
} catch (SecurityException e) {
// No permission to retrieve audio?
Log.e("Ringtone", e.toString());
// todo error 1
} catch (IllegalArgumentException e) {
// No permission to retrieve audio?
Log.e("Ringtone", e.toString());
// todo error 2
}
mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view,
Cursor cursor,
int columnIndex) {
if (view.getId() == R.id.row_options_button) {
// Get the arrow image view and set the onClickListener to open the context menu.
ImageView iv = (ImageView) view;
iv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
openContextMenu(v);
}
});
return true;
} else if (view.getId() == R.id.row_icon) {
setSoundIconFromCursor((ImageView) view, cursor);
return true;
}
return false;
}
});
// Long-press opens a context menu
registerForContextMenu(getListView());
}
}
...
}
I changed to this:
public class RingtoneSelectActivity extends AppCompatActivity {
But I received some errors in this lines:
...
setListAdapter(mAdapter);
getListView().setItemsCanFocus(true);
getListView().setOnItemClickListener(new OnItemClickListener() { ... });
...
registerForContextMenu(getListView());
My errors:
Cannot resolve method 'setListAdapter(android.widget.SimpleCursorAdapter)
Cannot resolve method 'getListView()'
How can I fix that errors?
[Edit]
My LogCat:
E/ACRA: ACRA caught a NullPointerException for ir.ari.mp3cutter
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SimpleCursorAdapter.changeCursor(android.database.Cursor)' on a null object reference
at ir.ari.mp3cutter.RingtoneSelectActivity.refreshListView(RingtoneSelectActivity.java:621)
at ir.ari.mp3cutter.RingtoneSelectActivity.onOptionsItemSelected(RingtoneSelectActivity.java:314)
at android.app.Activity.onMenuItemSelected(Activity.java:2908)
at com.android.internal.policy.PhoneWindow.onMenuItemSelected(PhoneWindow.java:1151)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
at com.android.internal.view.menu.MenuPopupHelper.onItemClick(MenuPopupHelper.java:200)
at android.widget.AdapterView.performItemClick(AdapterView.java:310)
at android.widget.AbsListView.performItemClick(AbsListView.java:1145)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3042)
at android.widget.AbsListView$3.run(AbsListView.java:3879)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Line 304 to 319:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about:
RingtoneEditActivity.onAbout(this);
return true;
case R.id.action_record:
onRecord();
return true;
case R.id.action_show_all_audio:
mShowAll = true;
refreshListView();
return true;
default:
return false;
}
}
And line 619 to 622:
private void refreshListView() {
String filterStr = mFilter.getQuery().toString();
mAdapter.changeCursor(createCursor(filterStr));
}
[notice: I'm sorry for my bad talking, because I not learned English as good :)
So don't change super class, Just check for ungranted permissions with ContextCompat.checkSelfPermission() and then request Permission by ActivityCompat.requestPermissions() and get the result in:
#Override
public void onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
Related
I have been trying to figure this out all day, as I would like to add an image depending on the outcome of the emotion may detect. Just wanted to add some some images but I'm still new to this. Can anyone help me with this one to.
btw here's my code:
public class DetectionActivity extends AppCompatActivity {
// Background task of face detection.
private class DetectionTask extends AsyncTask<InputStream, String, Face[]> {
private boolean mSucceed = true;
#Override
protected Face[] doInBackground(InputStream... params) {
// Get an instance of face service client to detect faces in image.
FaceServiceClient faceServiceClient = SampleApp.getFaceServiceClient();
try {
publishProgress("Detecting...");
// Start detection.
return faceServiceClient.detect(
params[0], /* Input stream of image to detect */
true, /* Whether to return face ID */
true, /* Whether to return face landmarks */
new FaceServiceClient.FaceAttributeType[]{
FaceServiceClient.FaceAttributeType.Emotion,
});
} catch (Exception e) {
mSucceed = false;
publishProgress(e.getMessage());
addLog(e.getMessage());
return null;
}
}
#Override
protected void onPreExecute() {
mProgressDialog.show();
addLog("Request: Detecting in image " + mImageUri);
}
#Override
protected void onProgressUpdate(String... progress) {
mProgressDialog.setMessage(progress[0]);
setInfo(progress[0]);
}
#Override
protected void onPostExecute(Face[] result) {
if (mSucceed) {
addLog("Response: Success. Detected " + (result == null ? 0 : result.length)
+ " face(s) in " + mImageUri);
}
// Show the result on screen when detection is done.
setUiAfterDetection(result, mSucceed);
}
}
// Flag to indicate which task is to be performed.
private static final int REQUEST_SELECT_IMAGE = 0;
// The URI of the image selected to detect.
private Uri mImageUri;
// The image selected to detect.
private Bitmap mBitmap;
// Progress dialog popped up when communicating with server.
ProgressDialog mProgressDialog;
// When the activity is created, set all the member variables to initial state.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detection);
//this hides the back button and I thank you
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle(getString(R.string.progress_dialog_title));
// Disable button "detect" as the image to detect is not selected.
setDetectButtonEnabledStatus(false);
LogHelper.clearDetectionLog();
}
// Save the activity state when it's going to stop.
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("ImageUri", mImageUri);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.menuAbout:
// Toast.makeText(this, "You clicked about", Toast.LENGTH_SHORT).show();
View messageView = getLayoutInflater().inflate(R.layout.about, null, false);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.smile);
builder.setTitle(R.string.app_name);
builder.setView(messageView);
builder.create();
builder.show();
break;
case R.id.menuHelp:
// Toast.makeText(this, "You clicked settings", Toast.LENGTH_SHORT).show();
// Intent help = new Intent(this, HelpActivity.class);
//startActivity(help);
// break;
View messageViewh = getLayoutInflater().inflate(R.layout.help, null, false);
AlertDialog.Builder builderh = new AlertDialog.Builder(this);
builderh.setIcon(R.drawable.smile);
builderh.setTitle(R.string.app_nameh);
builderh.setView(messageViewh);
builderh.create();
builderh.show();
break;
}
return true;
}
// Recover the saved state when the activity is recreated.
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mImageUri = savedInstanceState.getParcelable("ImageUri");
if (mImageUri != null) {
mBitmap = ImageHelper.loadSizeLimitedBitmapFromUri(
mImageUri, getContentResolver());
}
}
// Called when image selection is done.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_SELECT_IMAGE:
if (resultCode == RESULT_OK) {
// If image is selected successfully, set the image URI and bitmap.
mImageUri = data.getData();
mBitmap = ImageHelper.loadSizeLimitedBitmapFromUri(
mImageUri, getContentResolver());
if (mBitmap != null) {
// Show the image on screen.
ImageView imageView = (ImageView) findViewById(R.id.image);
imageView.setImageBitmap(mBitmap);
// Add detection log.
addLog("Image: " + mImageUri + " resized to " + mBitmap.getWidth()
+ "x" + mBitmap.getHeight());
}
// Clear the detection result.
FaceListAdapter faceListAdapter = new FaceListAdapter(null);
ListView listView = (ListView) findViewById(R.id.list_detected_faces);
listView.setAdapter(faceListAdapter);
// Clear the information panel.
setInfo("");
// Enable button "detect" as the image is selected and not detected.
setDetectButtonEnabledStatus(true);
}
break;
default:
break;
}
}
// Called when the "Select Image" button is clicked.
public void selectImage(View view) {
Intent intent = new Intent(this, SelectImageActivity.class);
startActivityForResult(intent, REQUEST_SELECT_IMAGE);
}
// Called when the "Detect" button is clicked.
public void detect(View view) {
// Put the image into an input stream for detection.
ByteArrayOutputStream output = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
ByteArrayInputStream inputStream = new ByteArrayInputStream(output.toByteArray());
// Start a background task to detect faces in the image.
new DetectionTask().execute(inputStream);
// Prevent button click during detecting.
setAllButtonsEnabledStatus(false);
}
// View the log of service calls.
public void viewLog(View view) {
Intent intent = new Intent(this, DetectionLogActivity.class);
startActivity(intent);
}
// Show the result on screen when detection is done.
private void setUiAfterDetection(Face[] result, boolean succeed) {
// Detection is done, hide the progress dialog.
mProgressDialog.dismiss();
// Enable all the buttons.
setAllButtonsEnabledStatus(true);
// Disable button "detect" as the image has already been detected.
setDetectButtonEnabledStatus(false);
if (succeed) {
// The information about the detection result.
String detectionResult;
if (result != null) {
detectionResult = result.length + " face"
+ (result.length != 1 ? "s" : "") + " detected";
// Show the detected faces on original image.
ImageView imageView = (ImageView) findViewById(R.id.image);
imageView.setImageBitmap(ImageHelper.drawFaceRectanglesOnBitmap(
mBitmap, result, true));
// Set the adapter of the ListView which contains the details of the detected faces.
FaceListAdapter faceListAdapter = new FaceListAdapter(result);
// Show the detailed list of detected faces.
ListView listView = (ListView) findViewById(R.id.list_detected_faces);
listView.setAdapter(faceListAdapter);
} else {
detectionResult = "0 face detected";
}
setInfo(detectionResult);
}
mImageUri = null;
mBitmap = null;
}
// Set whether the buttons are enabled.
private void setDetectButtonEnabledStatus(boolean isEnabled) {
Button detectButton = (Button) findViewById(R.id.detect);
detectButton.setEnabled(isEnabled);
}
// Set whether the buttons are enabled.
private void setAllButtonsEnabledStatus(boolean isEnabled) {
Button selectImageButton = (Button) findViewById(R.id.select_image);
selectImageButton.setEnabled(isEnabled);
Button detectButton = (Button) findViewById(R.id.detect);
detectButton.setEnabled(isEnabled);
// Button ViewLogButton = (Button) findViewById(R.id.view_log);
// ViewLogButton.setEnabled(isEnabled);
}
// Set the information panel on screen.
private void setInfo(String info) {
TextView textView = (TextView) findViewById(R.id.info);
textView.setText(info);
}
// Add a log item.
private void addLog(String log) {
LogHelper.addDetectionLog(log);
}
// The adapter of the GridView which contains the details of the detected faces.
private class FaceListAdapter extends BaseAdapter {
// The detected faces.
List<Face> faces;
// The thumbnails of detected faces.
List<Bitmap> faceThumbnails;
// Initialize with detection result.
FaceListAdapter(Face[] detectionResult) {
faces = new ArrayList<>();
faceThumbnails = new ArrayList<>();
if (detectionResult != null) {
faces = Arrays.asList(detectionResult);
for (Face face : faces) {
try {
// Crop face thumbnail with five main landmarks drawn from original image.
faceThumbnails.add(ImageHelper.generateFaceThumbnail(
mBitmap, face.faceRectangle));
} catch (IOException e) {
// Show the exception when generating face thumbnail fails.
setInfo(e.getMessage());
}
}
}
}
#Override
public boolean isEnabled(int position) {
return false;
}
#Override
public int getCount() {
return faces.size();
}
#Override
public Object getItem(int position) {
return faces.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater layoutInflater =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.item_face_with_description, parent, false);
}
convertView.setId(position);
// Show the face thumbnail.
((ImageView) convertView.findViewById(R.id.face_thumbnail)).setImageBitmap(
faceThumbnails.get(position));
// Show the face details.
String getEmotion;
// String improve = improveMessage(getEmotion);
DecimalFormat formatter = new DecimalFormat("#0.0");
//add
// String message = findMessage(getEmotion());
// String improve = improveMessage(getEmotion);
String face_description = String.format("Emotion: %s\n",
getEmotion(faces.get(position).faceAttributes.emotion)
);
((TextView) convertView.findViewById(R.id.text_detected_face)).setText(face_description);
return convertView;
}
private String getEmotion(Emotion emotion) {
String emotionType = "";
double emotionValue = 0.0;
String emotionInfo = "";
if (emotion.anger > emotionValue) {
emotionValue = emotion.anger;
emotionType = "Anger";
emotionInfo = "If you haven't fed him/her yet maybe this precious one is thirsty or hungry.\n Try giving your attention. If your baby is acting unusual it's best to seek for medical help.";
}
if (emotion.contempt > emotionValue) {
emotionValue = emotion.contempt;
emotionType = "Contempt";
emotionInfo = "You go girl!";
}
if (emotion.disgust > emotionValue) {
emotionValue = emotion.disgust;
emotionType = "Disgust";
emotionInfo = "Look! If your baby is feeling this way mabye she/he doesn't like this. \n If what your doing right now is good for him/her maybe you can support that.";
}
if (emotion.fear > emotionValue) {
emotionValue = emotion.fear;
emotionType = "Fear";
emotionInfo = "Your baby looks somewhat uncomfortable.\n Make your baby feel comfortable and take note of what makes them feel like that. ";
}
if (emotion.happiness > emotionValue) {
emotionValue = emotion.happiness;
emotionType = "Happiness";
emotionInfo = "Just continue what you are doing. It is important to remember what can make them happy. \n";
}
if (emotion.neutral > emotionValue) {
emotionValue = emotion.neutral;
emotionType = "Neutral";
emotionInfo = "Maybe you should just observe first";
}
if (emotion.sadness > emotionValue) {
emotionValue = emotion.sadness;
emotionType = "Sadness";
emotionInfo = "Just cuddle or dandle your baby.";
}
if (emotion.surprise > emotionValue) {
emotionValue = emotion.surprise;
emotionType = "Surprise";
emotionInfo = "Oooh look. Play with your baby. Try doing peek a boo";
}
return String.format("%s: %f \n\n%s", emotionType, emotionValue, emotionInfo);
}
}
}
Just would like to add some images like happy if that is the detected emotion. Please do help me. Any help is highly appreciated. Thank you :)
I would like to add that after the emotionInfo.
I guess detectWithStream is you want.
Official Doc: Faces.detectWithStream Method
From Java SDK, the List<DetectedFace> object will return if successful.
I have a RecyclerView that displays tasks and contains checkboxes. When user will click the checkbox, I want to check if the time ending of the task is less than the current time and if it is true, then the checkbox will remain checked, otherwise it should be unchecked. Let me clarify my problem with the help of the code.
In my adapter I created an interface:
private OnItemClickedListener listener;
public void setOnItemClickedListener(OnItemClickedListener listener){
this.listener = listener;
}
interface OnItemClickedListener {
void onItemClick(View v, int position, boolean isChecked, int time);
}
Then, in OnBindViewHolder I set onClickListener to checkbox:
#Override
public void onBindViewHolder(#NonNull final SortedViewHolder holder, final int position) {
final Sorted data = list.get(position);
holder.title.setText(data.getSortedName());
holder.date.setText(data.getSortedDate());
holder.category.setText(String.valueOf(data.getSortedCategory()));
holder.attach.setText(String.valueOf(data.isSortedAttach()));
holder.to.setText(String.valueOf(toTime(data.getSortedDuration() + data.getSortedTimeBegin())));
holder.from.setText(String.valueOf(toTime(data.getSortedTimeBegin())));
holder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null){
boolean isChecked = holder.checkBox.isChecked();
listener.onItemClick(v, position, isChecked, data.getSortedDuration() + data.getSortedTimeBegin());
}
}
});
}
(Note: I store time of the tasks in minutes, so later I will split them seperately into minutes and hours).
After that, in my activity I get this method and check the time:
//in OnCreate:
final SortedAdapter adapter = new SortedAdapter();
adapter.setOnItemClickedListener(this);
#Override
public void onItemClick(View v, int position, boolean isChecked, int time) {
if (isChecked){
//String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());
//get current day time
int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
int minute = Calendar.getInstance().get(Calendar.MINUTE);
//compare to the given
if (hour > time/60){
//save state
Toast.makeText(this, "check1", Toast.LENGTH_SHORT).show();
}
else if (hour == time/60){
if (minute > time % 60){
//save state
Toast.makeText(this, "check2", Toast.LENGTH_SHORT).show();
}
else{
//set the checkbox to false
Toast.makeText(this, "uncheck1", Toast.LENGTH_SHORT).show();
listener.onCheckBoxOff(v);
}
}
else{
Toast.makeText(this, "uncheck2", Toast.LENGTH_SHORT).show();
listener.onCheckBoxOff(v);
}
}
}
All the Toasts work fine. Now I want somehow to access my checkbox variable and change it's state. And this is my problem. I don't really understand how to do it.
I've tried to make another interface in my activity:
//outside activity class
interface CheckBoxOff {
void onCheckBoxOff(View v);
}
//in activity class before onCreate
private CheckBoxOff listener;
void setCheckboxOffListener(CheckBoxOff listener){
this.listener = listener;
}
So then I implemented it in my adapter:
#Override
public void onCheckBoxOff(View v) {
SortedViewHolder holder = new SortedViewHolder(v);
holder.checkBox.setChecked(false);
}
And in BindViewHolder I wrote(maybe here is the mistake?):
ShowSortedActivity activity = new ShowSortedActivity();
activity.setCheckboxOffListener(this);
After starting my app I got error:
java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.tryalgorithm.ui.CheckBoxOff.onCheckBoxOff(android.view.View)' on a null object reference
at com.example.tryalgorithm.ui.ShowSortedActivity.onItemClick(ShowSortedActivity.java:104)
at com.example.tryalgorithm.ui.SortedAdapter$1.onClick(SortedAdapter.java:66)
at android.view.View.performClick(View.java:6304)
at android.widget.CompoundButton.performClick(CompoundButton.java:134)
at android.view.View$PerformClick.run(View.java:24803)
at android.os.Handler.handleCallback(Handler.java:794)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:6635)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Could you please explain what am I doing wrong here? Maybe there is another way to set the checkbox to false, not with the help of interface or this way is fine? Thanks for any help.
Activity code:
public class ShowSortedActivity extends AppCompatActivity {
SortedViewModel viewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_sorted);
final SortedAdapter adapter = new SortedAdapter();
RecyclerView showSorted = findViewById(R.id.show_sorted);
showSorted.setLayoutManager(new LinearLayoutManager(this));
showSorted.setHasFixedSize(true);
showSorted.setAdapter(adapter);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);
setTitle(R.string.Sorted);
Intent intent = getIntent();
String currentDate = intent.getStringExtra("value");
viewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(SortedViewModel.class);
try {
viewModel.getSortedWhereDateIs(currentDate).observe(this, new Observer<List<Sorted>>() {
#Override
public void onChanged(List<Sorted> sorteds) {
adapter.setSortedData(sorteds);
}
});
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
public void onItemClick(View v, int position, boolean isChecked, int time) {
if (isChecked){
//get current day time
int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
int minute = Calendar.getInstance().get(Calendar.MINUTE);
//compare to the given
if (hour > time/60){
//save state
Toast.makeText(this, "check1", Toast.LENGTH_SHORT).show();
}
else if (hour == time/60){
if (minute > time % 60){
//save state
Toast.makeText(this, "check2", Toast.LENGTH_SHORT).show();
}
else{
//set the checkbox to false
Toast.makeText(this, "uncheck1", Toast.LENGTH_SHORT).show();
}
}
else{
//set the checkbox to false
Toast.makeText(this, "uncheck2", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onCheckBoxOff(View v) {
SortedViewHolder holder = new SortedViewHolder(v);
holder.checkBox.setChecked(false);
}
Your problem is you can not create view holder by self, it should be managed by adapter through onCreateViewHolder. Change your code to
#Override
public void onCheckBoxOff(View v) {
((CheckBox)v).setChecked(false);
}
But this only fix UI, you should store value of each holder to remain checkbox state when it scrolls. Following these steps:
Add isChecked to Sorted model
onBindViewHolder should update checkBox by isChecked from data
inside method onItemClick should update isChecked model in list data of adapter base on position
I have succeeded in making more data download and then put it inside Recycleview and I succeeded in doing that and I used everything well but the problem is that I try to load some elements if they contain a value of 3, for example inside the function Loadmore I tried to make a loop and then I put the value 3 and then delete all the value equal to this number
but I have not succeeded so far please help and put the appropriate code
// my code
public class Page_6Fragment extends android.support.v4.app.Fragment implements AdapterView.OnItemSelectedListener {
TextView th, tm, tt, tapm;
Spinner spin_h, spin_m, spin_apm, spin_day;
RadioButton radioReject,radioAccipt ;
RadioGroup radioGroup;
Button buttonDialogReject,buttonDialogAccipt;
Dialog dialog;
RecyclerView recyclerView;
List<Customer> customers;
CustomerAdapter adapter;
View rootView;
String TAG = "MainActivity - ";
Context context;
API api;
Boolean acceptOrNo = true;
Context c = null;
String lock;
public int[] userLock;
public static Page_6Fragment instance;
public static Page_6Fragment newInstance() {
Page_6Fragment fragment = new Page_6Fragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_customer, container, false);
this.context = getActivity();
this.instance = this;
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
customers = new ArrayList<>();
// Postion is index item inside recycleview =
adapter = new CustomerAdapter(Page_6Fragment.this,customers){
#Override
public void buttonClickEvent(int position){
// Toast.makeText(context,"posIs: "+position+" userLock.len= "+userLock.length,Toast.LENGTH_SHORT).show();
//showDialog(context,customers.get(position).user_id , Integer.parseInt(customers.get(position).id));
//---- condithion 1
if(customers.get(position).status ==0){
showDialog(context,customers.get(position).user_id , Integer.parseInt(customers.get(position).id));
}else{
Toast.makeText(context,"تم الرد على هذا المستخدم مسبقا", Toast.LENGTH_SHORT).show();
}
}
};
adapter.setLoadMoreListener(new CustomerAdapter.OnLoadMoreListener() {
#Override
public void onLoadMore() {
recyclerView.post(new Runnable() {
#Override
public void run() {
int index = customers.size();
loadMore(index);
}
});
//Calling loadMore function in Runnable to fix the
// java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling error
}
});
recyclerView.setHasFixedSize(true);
// recyclerView.addItemDecoration(new VerticalLineDecorator(2));
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.setAdapter(adapter);
api = ServiceGenerator.createService(API.class);
load(0);
return rootView;
}
// load data first time
private void load(int index) {
Call<List<Customer>> call = api.getCustomer(index);
call.enqueue(new Callback<List<Customer>>() {
#Override
public void onResponse(Call<List<Customer>> call, final Response<List<Customer>> response) {
// Toast.makeText(MainActivity.this, "tost "+response.body().get(0).post_writer, Toast.LENGTH_LONG).show();
//Log.i("TRUE_TRUE_","Yes "+response.body().get(2).name);
if (response.isSuccessful()) {
//Log.i("TRUE_TRUE3","Yes"+response.body().toString());
//movies.addAll(response.body());
//adapter.notifyDataChanged();
getActivity().runOnUiThread(new Runnable(){
public void run() {
// No.1 ..............
// ShowDataScreen();
// Toast.makeText( MainActivity.this, "ShowDataScreen",Toast.LENGTH_SHORT).show();
//if(customers.get()){
customers.addAll(response.body());
adapter.notifyDataChanged();
initiUserlock(customers.size());
}
});// end of No.1 UI new thread
getActivity().runOnUiThread(new Runnable() {
public void run() {//No.2
// Toast.makeText( MainActivity.this, "This is correct way",Toast.LENGTH_SHORT).show();
}
});// end of No.2 UI new thread
// Toast.makeText(MainActivity.this, "tost "+response.body().get(0).post_writer, Toast.LENGTH_LONG).show();
} else {
Log.e(TAG, " Response Error " + String.valueOf(response.code()));
}
}
#Override
public void onFailure(Call<List<Customer>> call, Throwable t) {
Log.e(TAG, " Response Error " + t.getMessage());
}
});
}
// laod more data ...................................
private void loadMore(int index) {
// add loading progress view ....
//Toast.makeText(context, "loadMore", Toast.LENGTH_LONG).show();
customers.add(new Customer("load"));
// customers.get(index).user_id =2;
adapter.notifyItemInserted(customers.size() - 1);
Call<List<Customer>> call = api.getCustomer(index);
call.enqueue(new Callback<List<Customer>>() {
#Override
public void onResponse(Call<List<Customer>> call, Response<List<Customer>> response) {
if (response.isSuccessful()) {
//Toast.makeText(context, "it is Successful", Toast.LENGTH_LONG).show();
customers.remove(customers.size() - 1);
List<Customer> result = response.body();
// Log.i("Getresult{--: ", " "+result.get());
if(result.size()>0) {
customers.addAll(result);
//add loaded data
// How to delete every item = 3 from customers list
for (int i=0; i<customers.size(); i++) {
if(customers.get(i).user_id == 3){
// customers.remove(i);
}
}
} else {
//result size 0 means there is no more data available at server
adapter.setMoreDataAvailable(false);
//telling adapter to stop calling load more as no more server data available
Toast.makeText(context,"لايوجد بيانات اخرى", Toast.LENGTH_LONG).show();
}
adapter.notifyDataChanged();
//should call the custom method adapter.notifyDataChanged here to get the correct loading status
} else {
Log.e(TAG, " Load More Response Error000 " + String.valueOf(response.code()));
}
}
#Override
public void onFailure(Call<List<Customer>> call,Throwable t) {
Log.e(TAG, " Load More Response Error_11 " + t.getMessage());
}
});
}
As you already have the new list in the result list, you can solve it by using the result List and add it to the customers List
customers.clear();
for(Customer newCustomer: result){
if(newCustomer.user_id != 3){
customers.add(newCustomer);
}
}
Second option would be to iterate over the customers list using ListIterator
ListIterator<Customer> iter = customers.listIterator();
while(iter.hasNext()){
if(iter.next().user_id == 3){
iter.remove();
}
}
Or
customers.removeIf(customer -> customer.user_id == 3);
I am trying to learn the Android onLongclick context menu actions. When clicking an item on list it displays two action image one for calling and another for website url. But I am having null pointer exception. When toasting using the toast method it can display number and url. But this is not what i want to to. Its just for test. I want to dial the number when phone action is clicked and visit website when url action is clicked. I have commented toast for doing so. And tried to create perform call and performUrl() methods. I took idea from the example with toast so i tried to modify it but its simply not working so i commented the performCall() and performUrl() methods for now. Could anyone suggest how to make these things happen?
I have a department class which is a pure java class.
public class DepartmentActivity extends Activity {
//Department dept = new Department();
private ListView listView;
ArrayAdapter<Department> adapter;
//String list_item;
Object mActionMode;
private Department[] myDepartment = {
new Department("CS", "cs#yahoo.edu", "405.111.2222"),
new Department("Biology", "bio#yahoo.edu", "405.222.3333"),
new Department("Business", "business#yahoo.com", "405.333.4444"),
new Department("Music", "music#yahoo.com", "405.444.5555"),
new Department("Engineering", "engg#ucoll.com", "405.555.6666"),
new Department("Nursing", "nursing#yahoo.com", "213.555.6666")
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_department);
listView =(ListView) findViewById(R.id.list);
//adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.deptlist, deptList);
adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.deptlist, myDepartment);
listView.setAdapter(adapter);
//listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
//listener = new listView.OnItemLongClickListener(this);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//list_item = myDepartment.toString();
if (mActionMode != null){
return false;
}
mActionMode = DepartmentActivity.this.startActionMode(mActionModeCallback);
return true;
}
});
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
//mode.setTitle(list_item);
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
return true;
//return false;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.action_phone:
performCall();
mode.finish(); // Action picked, so close the CAB
return true;
case R.id.action_www:
//performUrl();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
};
/*
private void performCall() {
SparseBooleanArray selected = listView.getCheckedItemPositions();
String selectedNames ="";
for (int i = 0; i < selected.size(); i++) {
if (selected.valueAt(i)) {
int pos = selected.keyAt(i);
selectedNames += " " + myDepartment[pos].getPhone();
}
}
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:"+selectedNames));
startActivity(callIntent);
//Toast.makeText(DepartmentActivity.this, "Call: " + selectedNames,
// Toast.LENGTH_SHORT).show();
}
*/
/*
private void performUrl() {
SparseBooleanArray selected = listView.getCheckedItemPositions();
String selectedNames = "";
for (int i = 0; i < selected.size(); i++) {
if (selected.valueAt(i)) {
int pos = selected.keyAt(i);
selectedNames += " " + myDepartment[pos].getUrl();
}
}
//Toast.makeText(DepartmentActivity.this, "Url: " + selectedNames,
//Toast.LENGTH_SHORT).show();
}
*/
Stack trace
....PID: 3250
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.util.SparseBooleanArray.size()' on a null object reference
at esu.uco.rawal.p4rabina.DepartmentActivity.performCall(DepartmentActivity.java:108)
at esu.uco.rawal.p4rabina.DepartmentActivity.access$100(DepartmentActivity.java:18)
at esu.uco.rawal.p4rabina.DepartmentActivity$2.onActionItemClicked(DepartmentActivity.java:85)
at com.android.internal.policy.PhoneWindow$DecorView$ActionModeCallback2Wrapper.onActionItemClicked(PhoneWindow.java:3540)
at com.android.internal.app.WindowDecorActionBar$ActionModeImpl.onMenuItemSelected(WindowDecorActionBar.java:1093)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
at android.widget.ActionMenuView.invokeItem(ActionMenuView.java:616)
at com.android.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:141)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Thank You
Okay, I hope someone may be able to help. I have spent tonight trying figure this out, I just seem to understand it.
I have created a translation app using 4 Fragments & FragmentPagerAdapter, however it runs fine on the surface up to when I click on the 4th column and then the app crashes and closes.
Logcat is cut down... the top section shows first sign why it crashes, section shows fatal exception and dies. When scrolling across it shows different names than it states on the tab E.g - see below for log cat
- Numbers show for Numbers,
- Family show for Colors,
- Colors show for Phrases,
- Phrases show nothing.
NumbersFragment{...} not updated inline; expected state 3 found 2
.../com.example.android.miwok W/FragmentManager:moveToState: Fragment state for ColorsFragment{ccf160c #2 id=0x7f0d006b android:switcher:2131558507:2} not updated inline; expected state 3 found 2
...W/FragmentManager: moveToState: Fragment state for PhrasesFragments{...} not updated inline; expected state 3 found 2
...D/MediaPlayer: setSubtitleAnchor in MediaPlayer
...D/AudioManager: AudioManager dispatching onAudioFocusChange(-2) for android.media.AudioManager#d5174d4com.example.android.miwok.ColorsFragment...
...D/AndroidRuntime: Shutting down VM
...E/AndroidRuntime: FATAL EXCEPTION: mainProcess: com.example.android.miwok, PID: 28858
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.pause()' on a null object reference
at ...ColorsFragment$1.onAudioFocusChange(ColorsFragment.java:26)
at ...AudioManager$FocusEventHandlerDelegate$1.handleMessage(AudioManager.java:2147) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Please see my java code below
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set content of activity to layout file
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new CategoryFragmentPagerAdapter(getSupportFragmentManager(),
MainActivity.this));
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
}
}
x4 CategoryFragments.java are identical:
public class ColorsFragment extends Fragment {
private MediaPlayer mMediaPlayer;
private AudioManager mAudioManager; // <-- handles audiofocus when sound is played
AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener =
new AudioManager.OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
mMediaPlayer.pause(); // <-- Lose audio focus
mMediaPlayer.seekTo(0); // <-- & start again because its a short clip
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
mMediaPlayer.start(); // <-- Resume playing media
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
releaseMediaPlayer(); // if audiofocus is lost or app is closed
// stop playback and clean resource.
}
}
};
private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
releaseMediaPlayer();
}
};
public ColorsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.word_list, container, false);
// Create a list of words
final ArrayList<Word> words = new ArrayList<>();
words.add(new Word("red", "weṭeṭṭi", R.raw.color_red, R.drawable.color_red));
words.add(new Word("green", "chokokki", R.raw.color_green, R.drawable.color_green));
words.add(new Word("brown", "ṭakaakki", R.raw.color_brown, R.drawable.color_brown));
words.add(new Word("gray", "ṭopoppi", R.raw.color_gray, R.drawable.color_gray));
words.add(new Word("black", "kululli", R.raw.color_black, R.drawable.color_black));
words.add(new Word("white", "kelelli", R.raw.color_white, R.drawable.color_white));
words.add(new Word("dusty yellow", "ṭopiisә", R.raw.color_dusty_yellow, R.drawable.color_dusty_yellow));
words.add(new Word("mustard yellow", "chiwiiṭә", R.raw.color_mustard_yellow, R.drawable.color_mustard_yellow));
WordAdapter adapter = new WordAdapter(getActivity(), words, R.color.category_colors);
ListView listView = (ListView) rootView.findViewById(R.id.list);
listView.setAdapter(adapter);
// its important to request audio focus straight away in the program.
mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE); // <-- turns variable to an instance
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Word word = words.get(position); // <-- Gets the Word() object, at the given position.
releaseMediaPlayer(); // <-- Releases anything that maybe in the media player.
// Request audio focus for playback
int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
mMediaPlayer = MediaPlayer.create(getActivity(), word.getAudioResourceId());
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(mCompletionListener);
}
}
});
return rootView;
}
private void releaseMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
#Override
public void onStop() {
super.onStop();
releaseMediaPlayer();
}
}
CategoryFragmentPagerAdapter
public class CategoryFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 4;
private Context mContext;
public CategoryFragmentPagerAdapter(FragmentManager fm, Context context) {
super(fm);
mContext = context;
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new NumbersFragment();
} else if (position == 1) {
return new FamilyFragments();
} else if (position == 2) {
return new ColorsFragment();
} else {
return new PhrasesFragments();
}
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
if (position == 0) {
return mContext.getResources().getString(R.string.category_numbers);
} else if (position == 1) {
return mContext.getResources().getString(R.string.category_family);
} else if (position == 2) {
return mContext.getResources().getString(R.string.category_colors);
} else {
return mContext.getResources().getString(R.string.category_phrases);
}
}
}[![enter image description here][1]][1]
According crash log you need to secure access to the mMediaPlayer as it could be null:
AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener =
new AudioManager.OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
if (mMediaPlayer == null)
return;
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
mMediaPlayer.pause(); // <-- Lose audio focus
mMediaPlayer.seekTo(0); // <-- & start again because its a short clip
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
mMediaPlayer.start(); // <-- Resume playing media
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
releaseMediaPlayer(); // if audiofocus is lost or app is closed
// stop playback and clean resource.
}
}
};
I guess listener received AudioManager.AUDIOFOCUS_LOSS after which mMediaPlayer become null. And then it received next event crash happened