I create custom layout which i want to use inside broadcast receiver, but getLayoutInflater() not work inside receiver
inside onreceiver method i call startAlaram(context,intent)
private void startAlaram(final Context context, Intent intent) {
LayoutInflater inflater = LayoutInflater.from(context);
final View view = inflater.inflate(R.layout.custom_layout_notification, null);
AlertDialog.Builder builder=new AlertDialog.Builder(context,);
builder.setTitle("Get Reminder");
builder.setMessage("Alert ALert");
builder.setIcon(R.mipmap.ic_launcher_round);
builder.setView(view);
final AlertDialog dialog=builder.create();
TextView not_txt_title,not_txt_desc,not_txt_callfor,not_txt_name;
ImageView img1;
not_txt_title = view.findViewById( R.id.not_txt_title );
not_txt_desc = view.findViewById( R.id.not_txt_desc );
not_txt_callfor = view.findViewById( R.id.not_txt_callfor );
not_txt_name = view.findViewById( R.id.not_txt_name );
img1 = view.findViewById( R.id.img1);
not_txt_title.setText(rTitle);
not_txt_desc.setText(rDesc);
not_txt_callfor.setText(rCallFor);
not_txt_name.setText(rName);
dialog.show();
}
You can implement a transparent activity with AlertDialog.
Create a void for your AlertDialog.
private void alert() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//... your alert stuff
}
Show your AlertDialog in your Receiver
#Override
public void onReceive(Context context, Intent intent) {
alert();
}
This is very Simple.
private void showDialog(){
LayoutInflater factory = LayoutInflater.from(this);
final View deleteDialogView = factory.inflate(R.layout.mylayout, null);
final AlertDialog deleteDialog = new AlertDialog.Builder(this).create();
deleteDialog.setView(deleteDialogView);
deleteDialogView.findViewById(R.id.yes).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//your business logic
deleteDialog.dismiss();
}
});
deleteDialogView.findViewById(R.id.no).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
deleteDialog.dismiss();
}
});
deleteDialog.show();
}
* you have to register/unregister your broadcast.
registerReceiver(mReceiver, new IntentFilter("com.mybroadcast"));
unregisterReceiver(mReceiver);
Your Broadcast code is like this.
Broadcast mReceiver = new Broadcast(){
#Override
public void onReceive(Context context, Intent intent) {
showDialog()
}
}
Related
appreciate if you can help me here.
I am creating a To Do List, where the ListView is in the MainToDoList Activity with a "Add a new Task" button that takes the user to the second activity.
In the second activity, there is a Edit Text field where user can input the title of the task. Two buttons are "Save" and "Cancel"
My question is, how to pass the edit text value after pressing the save button to display it into the listview in the first activity.
First Activity:
public class Todolistactivity extends AppCompatActivity {
private Button btn;
private ListView list;
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.todolistactivity);
btn = findViewById(R.id.addTask);
list = findViewById(R.id.task_list);
}
private void addTask() {
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(Todolistactivity.this, EditToDo.class));
}
});
}
Second Activity:
public class EditToDo extends Todolistactivity {
private static final String TAG = "EditToDo";
private Button save;
private Button cancel;
private EditText title;
#Override
protected void onCreate (Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.activity_taskedit);
save = findViewById(R.id.saveTask);
cancel = findViewById(R.id.cancelTask);
title = findViewById(R.id.taskTitle);
saveButton();
cancelButton();
}
private void saveButton(){
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent backToDo = new Intent
(getBaseContext(),Todolistactivity.class);
String titleEntered = title.getText().toString();
backToDo.putExtra("task", titleEntered);
startActivity(backToDo);
}
});
}
Use startActivityForResult
in your Todolistactivity class
private void addTask() {
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivityForResult(new Intent(Todolistactivity.this, EditToDo.class), 100); // 100 is request code.
}
});
}
//...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if(resultCode == Activity.RESULT_OK){
String result = data.getStringExtra("task");
}
else if (resultCode == Activity.RESULT_CANCELED) {
//...
}
}
}
In Your EditToDo class
private void saveButton(){
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String titleEntered = title.getText().toString();
Intent intent = new Intent();
intent.putExtra("task", titleEntered);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
}
Here I'm using Custom Adapter by implementing listAdapter to Support buttons in the list items. When i click the Delete button it deletes currect row. But i can't able to refresh this listView.
File Structure is MainActivity -> FragmentClass-> this Custom class for the listAdpater.
public class Category_ListView_Custom_Adapter extends BaseAdapter implements ListAdapter{
private Realm realm;
private ArrayList<String> list = new ArrayList<>();
private Context context;
public Category_ListView_Custom_Adapter(ArrayList<String> list, Context context){
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
View view1 = view;
realm = Realm.getDefaultInstance();
if(view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.category_listview_row, null);
}
TextView listItemText = (TextView) view.findViewById(R.id.item);
listItemText.setText(list.get(i));
ImageView edit = (ImageView) view.findViewById(R.id.image);
ImageView delete = (ImageView) view.findViewById(R.id.delete);
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// list.remove(i);
/// Toast.makeText(view.getContext(), "hey "+list.get(i).toString(), Toast.LENGTH_SHORT).show();
// notifyDataSetChanged();
Intent intent = new Intent(context, AddCategory.class);
intent.putExtra("category","expense");
intent.putExtra("subcategory", list.get(i));
context.startActivity(intent);
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
RealmResults<Category> categorylist = realm.where(Category.class).equalTo("Id",i+1).and().equalTo("Subcategory",list.get(i)).findAll();
for (Category category : categorylist) {
realm.beginTransaction();
categorylist.deleteFirstFromRealm();
realm.commitTransaction();
try {
context.notifyAll();
}catch (Exception e){
Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
}
// Expense.call_resume
}
}
});
return view;
}
}
Please Help me. Thank you.
You are .removing from a wrong view. Try to make root List<> static and do Class.list.get(i).remove or something like that.
Also, try to hide a view inside your get view.
I`v been trying for a while to destroy activity when the home button is pressed or when the app is in background and I manage to do something with this code
#Override
protected void onPause() {
this.finish();
super.onPause();
}
and when the app runs it does not crash but after a while playing in the activity the app just goes background and crashes.
This is the activity that I`m talking about:
public class Playing extends AppCompatActivity implements View.OnClickListener {
final static long INTERVAL=1154;//1 second
final static long TIMEOUT=7000;
int progressValue = 0;
CountDownTimer mcountDown;
List<Question> questionPlay = new ArrayList<>();
DbHelper db;
int index=0 , score =0,thisQuestion=0,totalQuestion,CorrectAnswer;
String mode = "";
ProgressBar progressBar;
ImageView imageView;
Button btnA, btnB, btnC,btnD;
TextView txtScore,txtQuestion;
#Override
protected void onPause() {
this.finish();
super.onPause();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playing);
Bundle extra = getIntent().getExtras();
if(extra!=null)
mode =extra.getString("MODE");
db = new DbHelper(this);
txtScore = (TextView)findViewById(R.id.txtScore);
txtQuestion =(TextView)findViewById(R.id.txtQuestion);
progressBar=(ProgressBar) findViewById(R.id.progreessBar);
btnA = (Button) findViewById(R.id.btnAnswerA);
btnB =(Button)findViewById(R.id.btnAnswerB);
btnC = (Button)findViewById(R.id.btnAnswerC);
btnD = (Button)findViewById(R.id.btnAnswerD);
imageView = (ImageView)findViewById(R.id.question_bike);
btnA.setOnClickListener(this);
btnB.setOnClickListener(this);
btnC.setOnClickListener(this);
btnD.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
questionPlay = db.getQuestionMode(mode);
totalQuestion = questionPlay.size();
mcountDown = new CountDownTimer(TIMEOUT, INTERVAL) {
#Override
public void onTick(long millisUntilFinished) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
mcountDown.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
private void showQuestion(int index) {
if (index < totalQuestion){
thisQuestion++;
txtQuestion.setText(String.format("%d %d",thisQuestion,totalQuestion));
progressBar.setProgress(0);
progressValue = 0;
int ImageID = this.getResources().getIdentifier(questionPlay.get(index).getImage().toLowerCase(),"drawable",getPackageName());
imageView.setBackgroundResource(ImageID);
btnA.setText(questionPlay.get(index).getAnswerA());
btnB.setText(questionPlay.get(index).getAnswerB());
btnC.setText(questionPlay.get(index).getAnswerC());
btnD.setText(questionPlay.get(index).getAnswerD());
mcountDown.start();
}
else {
Intent intent = new Intent(this,Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL",totalQuestion);
dataSend.putInt("CORRECT",CorrectAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
#Override
public void onClick(View v) {
mcountDown.cancel();
if (index < totalQuestion){
Button clickedButton = (Button)v;
if(clickedButton.getText().equals(questionPlay.get(index).getCorrectAnswer())){
score+=1;
CorrectAnswer++;
showQuestion(++index);
}
else showQuestion(++index);
txtScore.setText(String.format("S:%d",score));
}
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Playing.this ,MainActivity.class) ;
startActivity(intent) ;
finish() ;
}
}
I`v tried and with this code
#Override
protected void onDestroy(){
super.onDestroy;
finish();
}
but then the second activity does not start and the app crashes again.
So what to do?
I am trying to have a button within a Tab which is part of an activity for uploading images, when clicking the button inside one of the 2 Tabs presented in the activity ( Tab 1 pics, Tab 2 Vid ) the user could choose an image from the device.
My problem is implemneting the onClick Listener and onActivityResult which is not being used when placed after onClick, plus the #Override is being underlined as an error.
I guess i am not implementing the onClick the right way and not sure how to activate onActivityResult the proper way, i would appreciate any guidance;
MainActivty;
public class upload extends AppCompatActivity {
public String UserID;
private static final int REQUEST_SIGNUP = 0;
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload);
Firebase.setAndroidContext(this);
// Adding Toolbar to Main screen
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Setting ViewPager for each Tabs
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
// Set Tabs inside Toolbar
TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new UploadPictures(), "Pictures");
adapter.addFragment(new UploadVideos(), "Videos");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public Adapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
And here is the Fragment Code;
public class UploadPictures extends android.support.v4.app.Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final RecyclerView recyclerView = (RecyclerView) inflater.inflate(
R.layout.recycler_view, container, false);
ContentAdapter adapter = new ContentAdapter(recyclerView.getContext());
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return recyclerView;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView picture;
public EditText tagEditText;
public Button tagCurLoc, choosePic, uploadContent;
public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.pictue_upload, parent, false));
picture = (ImageView) itemView.findViewById(R.id.imgToUpload);
tagEditText = (EditText) itemView.findViewById(R.id.tagEditText);
tagCurLoc = (Button) itemView.findViewById(R.id.tagCurLoc);
choosePic = (Button) itemView.findViewById(R.id.choosePic);
choosePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
onActivityResult(requestCode, resultCode, data);
Toast.makeText(getActivity().getApplicationContext(), "Canceled ", Toast.LENGTH_SHORT).show();
} else {
if (requestCode == RESULT_LOAD_IMAGE) {
Uri selectedImgPath = data.getData();
picture.setImageURI(selectedImgPath);
RealFilePath = Uri.parse(String.valueOf(selectedImgPath));
Toast.makeText(getActivity().getApplicationContext(), " " + RealFilePath, Toast.LENGTH_SHORT).show();
}
}
}
});
uploadContent = (Button) itemView.findViewById(R.id.uploadContent);
}
}
/**
* Adapter to display recycler view.
*/
public class ContentAdapter extends RecyclerView.Adapter<ViewHolder> {
// Set numbers of List in RecyclerView.
private Context mContext;
public ContentAdapter(Context context) {
this.mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return LENGTH;
}
}
Not sure if the onClick listener for the button should be implemented in the Adapter or the View holder, and from there the issue of onActivityResult cant be used ?
Weel, solved after some more reading and few try outs.
The onClick listener should be implemented at the ViewHolder class followed by
#Override
onActivityResult.
within the onClickListener onActivityResult invoked by;
startActivityForResult(intent, RESULT_LOAD_IMAGE);
and within onActivityResult;
onActivityResult(requestCode, resultCode, data);
Considering all of this taking place in an activity extending Fragment.
My question is how do i send data written in EditText of dialogue box by clicking button and display it on LIstView of Main Activity. ?
public class TaskDetailsActivity extends Activity implements OnClickListener{
String[] timepass= new String[100];
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.taskdetails);
//timepass[0] = "sidd";
/*ListView tasklist= (ListView)findViewById(R.id.listview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.insideaddtask, R.id.tp, timepass);
tasklist.setAdapter(adapter);*/
}
public void addnewtask(View view)
{
showDialog(1);
}
#Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog=null;
switch (id)
{
case 1: dialog = new Dialog(TaskDetailsActivity.this);
dialog.setContentView(R.layout.addtask);
Button task_add_ok = (Button)findViewById(R.id.btn_ok);
task_add_ok.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
EditText writetask = (EditText)findViewById(R.id.txt_writetask);
String data = writetask.getText().toString();
timepass[0] = data;
}
});
break;
default:
break;
}
return dialog;
}
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
}
}
you can use any adapter for this arrayadapter of type string...
and use the button's onclick method to populate the listview...
below link provides a good example...
http://android.amberfog.com/?p=296
www.androidhive.info/2011/10/android-listview-tutorial/