Pass EditText value to ListView from two different activities - android-studio

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();
}
});
}

Related

How to get my TextView clickable to display the alert diaglog box?

I have the following code but the word "reset password" is not clickable. Even after I add some attributes to my xml, I still can't get it to be clicked. I thought that we should be using a button instead of a textview for clicking on? I have linked the variables to my xml file and set the relevant TextView for it.
public class LoginActivity extends AppCompatActivity {
private EditText email;
private EditText password;
private TextView reset_password;
private Button login;
private Button register;
private FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
login = findViewById(R.id.login);
register = findViewById(R.id.register);
reset_password = findViewById(R.id.reset_password);
auth = FirebaseAuth.getInstance();
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt_email = email.getText().toString();
String txt_password = password.getText().toString();
loginUser(txt_email, txt_password);
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
}
});
}
private void loginUser(String email, String password) {
auth.signInWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(LoginActivity.this, "Login Successful", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
});
reset_password.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final EditText resetMail = new EditText(v.getContext());
AlertDialog.Builder passwordResetDialog = new AlertDialog.Builder(v.getContext());
passwordResetDialog.setTitle("Reset Password ?");
passwordResetDialog.setMessage("Enter Your Email To Received Reset Link");
passwordResetDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// extract the email and send reset link
String mail = resetMail.getText().toString().trim();
auth.sendPasswordResetEmail(mail).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(LoginActivity.this, "Reset Link Sent To Your Email", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, "Error! Reset Link is Not Sent" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
passwordResetDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// close the dialog
}
});
passwordResetDialog.create().show();
}
});
}
}
This is my xml code:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Forgot Password"
android:layout_below="#id/password"
android:id="#+id/reset_password"/>

setLayout not inflating correct xml layout?

been alright so far. I try to use docs or find my issues.
However my mainActivity has 4 buttons. These buttons depending on which view is clicked passes the R.id.button. I pass this value into an intent which Activity2 uses bundle to get id integer. I then setContentView using this.
However im having issues getting correct view to inflate now, it seems like its loading an old layout. My aim is to inflate 3 separate layout on Activity2 depending which button was clicked.
I know my other other button does inflate another activity and get proper xml layout.
Why are my other 3 buttons not inflating on Activity2 properly?
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button pizza;
Button hamburger;
Button icecream;
Button history;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pizza = findViewById(R.id.buttonPizza);
hamburger = findViewById(R.id.buttonBurger);
icecream = findViewById(R.id.buttonIceCream);
history = findViewById(R.id.buttonHistroy);
pizza.setOnClickListener(this);
hamburger.setOnClickListener(this);
icecream.setOnClickListener(this);
history.setOnClickListener(this);
}
#Override
public void onClick(View v){
int idView = v.getId();
switch(v.getId()) {
case R.id.buttonBurger : startOrderActivity(R.layout.burger_layout);
makeToast(idView);
break;
case R.id.buttonPizza : startOrderActivity(R.layout.pizza_layout);
makeToast(idView);
break;
case R.id.buttonIceCream : startOrderActivity(R.layout.icecream_layout);
makeToast(idView);
break;
case R.id.buttonHistroy : startOrderActivity(R.layout.history_layout);
makeToast(idView);
break;
}
}
private void startOrderActivity(int id){
if(id != R.layout.history_layout) {
Intent intentOrder = new Intent(this, MakeOrderActivity.class);
intentOrder.putExtra("layout", id);
startActivity(intentOrder);
}
else {
Intent intentOrder = new Intent(this, OrderHistoryActivity.class);
intentOrder.putExtra("layout", id);
startActivity(intentOrder);
}
}
public void makeToast(int id){
String txt = String.valueOf(id);
Toast newToast = Toast.makeText(getApplicationContext(),txt,Toast.LENGTH_LONG);
newToast.show();
}
}
public class MakeOrderActivity extends AppCompatActivity {
Button placeOrderButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle data = getIntent().getExtras();
int layoutNum = data.getInt("layout");
setContentView(layoutNum);
placeOrderButton = findViewById(R.id.placeOrder);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.order, menu);
return true;
}
public void onCheckboxClicked(View view){
}
}
Answer is to create a View which is created by getInflator.
https://stackoverflow.com/a/17070408/8443090

Tracking selected tab and changing a textview accordingly

I'm working on my 1st android project, which uses a tab layout. I want to keep track of the active tab and change a textview present in the appbar (main activity).
Here is my main activity, tab manager, and a fragment
MAIN ACTIVITY
private static final String TAG = "MainActivity";
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(mViewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.Tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.tab_rooms_24dp);
tabLayout.getTabAt(1).setIcon(R.drawable.tab_feed_24dp);
tabLayout.getTabAt(2).setIcon(R.drawable.tab_profile_24dp);
tabLayout.getTabAt(0).getIcon().setColorFilter(getResources().getColor(R.color.Accent), PorterDuff.Mode.SRC_IN);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
tab.getIcon().setColorFilter(getResources().getColor(R.color.Accent),PorterDuff.Mode.SRC_IN);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
tab.getIcon().clearColorFilter();
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setupViewPager(ViewPager viewPager){
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new Tab1Fragment(), "");
adapter.addFragment(new Tab2Fragment(), "");
adapter.addFragment(new Tab3Fragment(), "");
viewPager.setAdapter(adapter);
}
TAB MANAGER
private final List<Fragment> mFragmentList =new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public void addFragment(Fragment fragment, String title){
mFragmentList.add(fragment);
mFragmentTitleList.add(title );
}
public SectionsPageAdapter(FragmentManager fm) {
super(fm);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
FRAGMENT
private static final String TAG = "Tab3Fragment";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab1,container,false);
return view;
}
I tried creating a variable in an abstract class then extending it into all three of these scripts which would be a simple solution but fragments dont seem to work well with extending, not to mention that probably isnt the most efficient method.
So I'm thinking the best method would be to simply handle it from the SectionsPageManager script?
Use addOnPageChangeListener on you pager.
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position == 1) {
setTitle("Tab 1");
} else if (position == 2)
{
setTitle("Tab 2");
}
else
{
setTitle("Home");
}
}
So I got it worked out and figured I'd come post the answer for anyone who may need it.
Not that the above answer sets the app title, not a TextView withing the appbar as stated in the question.
private static final String TAG = "MainActivity";
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager mViewPager;
private TextView activeTab;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activeTab = (TextView)findViewById(R.id.PageTitle);
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(mViewPager);
}
private void setupViewPager(ViewPager viewPager)
{
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new Tab1Fragment(), "");
adapter.addFragment(new Tab2Fragment(), "");
adapter.addFragment(new Tab3Fragment(), "");
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }
#Override
public void onPageSelected(int position)
{
switch (position){
case 0: activeTab.setText("text");
break;
case 1: activeTab.setText("better text");
break;
case 2: activeTab.setText("best text");
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}

How to implement onActivityResult within RecyclerView Fragment

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.

How to send data in ListView dynamicaly in android.?

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/

Resources