I want startActivity(LoginActivity) when after 3rd fragment.
In position 3rd fragment, I slide from right to left to start the activity.
I found some question but:
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if(position == tutorialViewPager.getAdapter().getCount() - 1){
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
}
In that case, when move 2nd fragment to 3rd fragment with slide, 3rd fragment(last fragment) was appeared a little bit and change Activity.
I want to change Activity when I slide last fragment(not from 2nd fragment to 3rd fragment, just slide 3rd fragment).
How I can warp Fragment to specific Activity when slide last fragment?
Please help me.
public class TutorialActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {
int MAX_PAGE = 3;
Fragment cur_fragment = new Fragment();
ViewPager tutorialViewPager;
private int selectedPageIndex = -1;
private boolean exitWhenScrollNextPage = false;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tutorial_page);
tutorialViewPager = (ViewPager) findViewById(R.id.tutorialViewPager);
tutorialViewPager.setAdapter(new adapter(getSupportFragmentManager()));
tutorialViewPager.addOnPageChangeListener(this);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if(position == tutorialViewPager.getAdapter().getCount() - 1){
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
private class adapter extends FragmentPagerAdapter{
public adapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(position<0 || MAX_PAGE <= position){
return null;
}
switch (position){
case 0:
cur_fragment = new TutorialFragmentA();
break;
case 1:
cur_fragment = new TutorialFragmentB();
break;
case 2:
cur_fragment = new TutorialFragmentC();
break;
}
return cur_fragment;
}
#Override
public int getCount() {
return MAX_PAGE;
}
}
}
You have to modify the implementation of the methods of ViewPager.OnPageChangeListener. Here is what i used and managed to solve this issue.
I put here your transition to (LoginActivity).
mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
boolean onLastPageChanged = false;
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
int lastFrag = mQuestionCollectionPagerAdapter.getCount() -1;
if (onLastPageChanged && position == lastFrag) {
//next
Log.e(TAG, "Transition Happened");
}
}
#Override
public void onPageScrollStateChanged (int state) {
int lastFrag = mQuestionCollectionPagerAdapter.getCount() -1;
int currentFragment = mViewPager.getCurrentItem();
if (currentFragment == lastFrag /*&& lastPos==lastIdx*/ && state == 1) {
onLastPageChanged = true;
Log.e(TAG, "page scroll state >>>>>>");
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
} else {
onLastPageChanged = false;
}
}
});
Related
I know how to add items to RecyclerView and show them, but let's say I add some dynamic items to the RecyclerView like this image
Here After click save button, it creates three rows in the RecyclerView like below image, which I don't want it creates three rows.
Instead I want to create one row, and when I clicked in that row then shows the three items like this image.
AddChecklist class
public class AddChecklist extends AppCompatActivity {
Button btnAddItem;
public LinearLayout linearLayout;
DbHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_checklist);
dbHelper = new DbHelper(this);
btnAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addView();
}
});
}
public void addView(){
View checklistView = getLayoutInflater().inflate(R.layout.checklist_view, null, false);
EditText etChecklistItem = checklistView.findViewById(R.id.et_checklist_item);
CheckBox checkBox = checklistView.findViewById(R.id.check_box);
linearLayout.addView(checklistView);
ImageView imgDelete = checklistView.findViewById(R.id.img_delete);
imgDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
removeView(checklistView);
}
});
}
public void removeView(View view){
linearLayout.removeView(view);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
DbHelper dbHelper = new DbHelper(getApplicationContext());
switch (item.getItemId()) {
case R.id.btn_save:
ChecklistHelper checklistHelper = new ChecklistHelper();
for (int i = 0; i < linearLayout.getChildCount(); i++) {
View v = linearLayout.getChildAt(i);
EditText etChecklistItem = v.findViewById(R.id.et_checklist_item);
CheckBox checkBox = v.findViewById(R.id.check_box);
if (checkBox.isChecked()) {
checklistHelper.setStatus("1");
}
else
checklistHelper.setStatus("0");
dbHelper.insertChecklist(checklistHelper.getStatus(), etChecklistItem.getText().toString(), DateTime.date(), DateTime.time(), System.currentTimeMillis());
}
finish();
break;
}
return true;
}
}
Adapter class
public class ChecklistItems extends AppCompatActivity {
Toolbar toolbar;
RecyclerView recyclerView;
String content;
String status;
boolean isEditChecklist = false;
private ChecklistAdapter checklistAdapter;
DbHelper dbHelper;
List<ChecklistHelper> checks;
int id;
ChecklistHelper checklistHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checklist_items);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
checklistHelper = new ChecklistHelper();
dbHelper = new DbHelper(this);
checks = dbHelper.getChecklists();
checklistAdapter = new ChecklistAdapter(checks);
recyclerView.setAdapter(checklistAdapter);
}
public class ChecklistAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private boolean isEnableDelete = false;
List<ChecklistHelper> checkList;
public ChecklistAdapter(List<ChecklistHelper> checkList) {
this.checkList = checkList;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.checklist_layout_child, parent, false);
return new ChecklistChildViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
ChecklistChildViewHolder checklistChildViewHolder = (ChecklistChildViewHolder) holder;
checklistChildViewHolder.updateVisibility(isEnableDelete);
checklistChildViewHolder.checkBox.setText(checkList.get(position).getContent());
checklistChildViewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
String txt = checklistChildViewHolder.checkBox.getText().toString();
if (b)
checklistChildViewHolder.checkBox.setText(lineThrough(txt));
else
checklistChildViewHolder.checkBox.setText(txt);
}
});
checklistChildViewHolder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dbHelper.deleteChecklist(id);
finish();
}
});
}
#Override
public int getItemCount() {
return checkList.size();
}
public void updateItems(boolean isEnableDelete){
this.isEnableDelete = isEnableDelete;
notifyDataSetChanged();
}
public class ChecklistChildViewHolder extends RecyclerView.ViewHolder {
CheckBox checkBox;
ImageView delete, edit;
ChecklistChildViewHolder(#NonNull View itemView) {
super(itemView);
checkBox = itemView.findViewById(R.id.checkbox_child);
delete = itemView.findViewById(R.id.delete_child);
edit = itemView.findViewById(R.id.edit_child);
delete.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
public void updateVisibility(boolean isEnableDelete){
if (isEnableDelete) {
delete.setVisibility(View.VISIBLE);
edit.setVisibility(View.VISIBLE);
}
else {
delete.setVisibility(View.INVISIBLE);
edit.setVisibility(View.INVISIBLE);
}
}
}
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
DbHelper dbHelper = new DbHelper(this);
// long id = getIntent().getIntExtra("id", 0);
switch (item.getItemId()) {
case R.id.edit:
isEditChecklist = true;
checklistAdapter.updateItems(true);
invalidateOptionsMenu();
break;
case R.id.save:
Toast.makeText(getApplicationContext(), "saved ", Toast.LENGTH_SHORT).show();
checklistAdapter.updateItems(false);
isEditChecklist = false;
finish();
break;
case R.id.delete:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete Checklist");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Continue ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dbHelper.deleteChecklist(id);
// checklistAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "checklist deleted", Toast.LENGTH_SHORT).show();
finish();
}
});
builder.setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
}).create().show();
break;
}
return true;
}
}
I want to retrieve image for recycler view in fragment
code of MovieActivity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
Intent intent = new Intent(this, LoadingActivity.class);
startActivity(intent);
setupViewFragment();
}
setupToolbar();
setupBottomNavigation();
}
private void setupViewFragment() {
// show discover movies fragment by default
DiscoverMoviesFragment discoverMoviesFragment = DiscoverMoviesFragment.newInstance();
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), discoverMoviesFragment, R.id.fragment_container);
}
private void setupBottomNavigation() {
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_home:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), HomeFragment.newInstance(),
R.id.fragment_container);
//startActivity(new Intent(getApplicationContext()
//,HomeActivity.class));
return true;
case R.id.action_discover:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), DiscoverMoviesFragment.newInstance(),
R.id.fragment_container);
return true;
case R.id.action_favorites:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), FavoritesFragment.newInstance(),
R.id.fragment_container);
return true;
}
return false;
}
});
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
}
`
code for HomeFragment :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
Intent intent = new Intent(this, LoadingActivity.class);
startActivity(intent);
setupViewFragment();
}
setupToolbar();
setupBottomNavigation();
}
private void setupViewFragment() {
// show discover movies fragment by default
DiscoverMoviesFragment discoverMoviesFragment = DiscoverMoviesFragment.newInstance();
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), discoverMoviesFragment, R.id.fragment_container);
}
private void setupBottomNavigation() {
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_home:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), HomeFragment.newInstance(),
R.id.fragment_container);
//startActivity(new Intent(getApplicationContext()
//,HomeActivity.class));
return true;
case R.id.action_discover:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), DiscoverMoviesFragment.newInstance(),
R.id.fragment_container);
return true;
case R.id.action_favorites:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), FavoritesFragment.newInstance(),
R.id.fragment_container);
return true;
}
return false;
}
});
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
}
code for HomeAdapter :
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ImageViewHolder> {
private Context mContext;
private List<Upload> mUploads;
private OnItemClickListener mListener;
public HomeAdapter(Context context, List<Upload> uploads) {
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Picasso.get()
.load(uploadCurrent.getImageUrl())
.placeholder(R.mipmap.ic_launcher)
.centerInside()
.fit()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_view_name);
imageView = itemView.findViewById(R.id.image_view_upload);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select Action");
MenuItem doWhatever = menu.add(Menu.NONE, 1, 1, "Do whatever");
MenuItem delete = menu.add(Menu.NONE, 2, 2, "Delete");
doWhatever.setOnMenuItemClickListener(this);
delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
switch (item.getItemId()) {
case 1:
mListener.onWhatEverClick(position);
return true;
case 2:
mListener.onDeleteClick(position);
return true;
}
}
}
return false;
}
}
public interface OnItemClickListener {
void onItemClick(int position);
void onWhatEverClick(int position);
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
}
this is the error :
`C:\Users\User\Desktop\PopularMovies\app\src\main\java\com\ajdi\yassin\popularmovies\ui\movieslist\home\HomeFragment.java:65: error: incompatible types: HomeFragment cannot be converted to Context
mAdapter = new HomeAdapter(HomeFragment.this, mUploads);`
Please use getApplicationContext() ,because HomeFragment.this is consider as an Activity and in your HomeAdapter constructor you have passed Context.
Replace:
mAdapter = new HomeAdapter(HomeFragment.this, mUploads);
To:
mAdapter = new HomeAdapter(getApplicationContext(), mUploads);
I want to return the data from second activity to first activity using intent when click the OnAddClicked button in second activity, but what I done was not working. The data that I return to first activity is null and I have no idea about this. Can anyone help me to solve this problem?
First Activity:
public class CartView extends AppCompatActivity {
ActivityCartViewBinding binding;
public CartView.MyClickHandler handler;
GridView view_listView;
String Default_curr;
String itemgroup;
String itemtype;
String uprice;
String quantity;
ACDatabase db;
List<AC_Class.Item> s_item = new ArrayList<>();
AC_Class.InvoiceDetails invoiceDetails;
AC_Class.Item item;
String substring = "";
EditText searchEditText;
Button All;
Button Type;
Button Group;
ArrayAdapter<String> adapter;
int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_cart_view);
// Action Bar
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Catalog");
actionBar.setDisplayHomeAsUpEnabled(true);
searchEditText = (EditText) findViewById(R.id.searchField);
UIUtil.hideKeyboard(this);
UIUtil.showKeyboard(this, searchEditText);
db = new ACDatabase(this);
invoiceDetails = new AC_Class.InvoiceDetails();
item = new AC_Class.Item();
handler = new MyClickHandler(this);
binding.setHandler(handler);
All = (Button) findViewById(R.id.button1);
Type = (Button) findViewById(R.id.button2);
Group = (Button) findViewById(R.id.button3);
view_listView = (GridView) findViewById(R.id.GridView);
All.setVisibility(View.GONE);
Type.setVisibility(View.GONE);
Group.setVisibility(View.GONE);
getData("");
searchEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {}
#Override
public void afterTextChanged(Editable s) {
getData(s.toString().trim());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.ctlg_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
/*if (id == android.R.id.home)
{
onBackPressed();
return true;
}*/
if (id == R.id.cart)
{
Intent new_intent = new Intent(CartView.this, CartList.class);
new_intent.putExtra("invoiceDetail", invoiceDetails);
startActivityForResult(new_intent,3);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
getData("");
}
public void getData(String substring) {
Cursor data = db.getItemLike(substring, 0);
if (data.getCount() > 0){
s_item.clear();
while (data.moveToNext()) {
try {
AC_Class.Item item = new AC_Class.Item(data.getString(0), data.getString(1), data.getString(2), data.getString(3), data.getString(4), data.getString(5), data.getString(6), data.getString(7), data.getString(8), data.getFloat(9), data.getFloat(10), data.getFloat(11), data.getFloat(12), data.getFloat(13), data.getFloat(14), data.getString(15), data.getString(16), data.getFloat(17), data.getString(18),data.getFloat(19),data.getFloat(20));
s_item.add(item);
} catch (Exception e) { Log.i("custDebug", "error reading image: "+e.getMessage()); }
}
CartViewListAdapter arrayAdapter = new CartViewListAdapter(this, s_item);
view_listView.setAdapter(arrayAdapter);
Cursor dcurren = db.getReg("6");
if(dcurren.moveToFirst()){
Default_curr = dcurren.getString(0);
}
view_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String itemcode = ((AC_Class.Item)parent.getItemAtPosition(position)).getItemCode();
String uom = ((AC_Class.Item)parent.getItemAtPosition(position)).getUOM();
AC_Class.Item sa =((AC_Class.Item) parent.getItemAtPosition(position));
//Intent item_intent = new Intent();
Intent item_intent = new Intent(CartView.this, ItemDetail.class);
item_intent.putExtra("ItemKey",itemcode);
item_intent.putExtra("ItemUOMKey",uom);
item_intent.putExtra("Items",sa);
//setResult(4, item_intent);
startActivity(item_intent);
//finish();
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
if (resultCode == 1) {
itemtype = data.getStringExtra("TypeKey");
if (itemtype != null) {
getTypedata();
}
}
break;
case 2:
if (resultCode == 1) {
itemgroup = data.getStringExtra("GroupKey");
if(itemgroup != null){
getGroupdata();
}
}
break;
case 3:
if (resultCode == 1) {
AC_Class.Item i = data.getParcelableExtra("Item");
uprice = data.getStringExtra("Price");
quantity = data.getStringExtra("Quantity");
if (i != null) {
invoiceDetails.setItemCode(i.getItemCode());
invoiceDetails.setItemDescription(i.getDescription());
invoiceDetails.setUPrice(Double.valueOf(i.getPrice()));
invoiceDetails.setUOM(i.getUOM());
//invoiceDetails.setUPrice(Double.valueOf(uprice));
invoiceDetails.setQuantity(Double.valueOf(quantity));
}
}
break;
}
}
}
SecondActivity:
public class ItemDetail extends AppCompatActivity {
ActivityItemDetailBinding binding;
AC_Class.Item items;
AC_Class.ItemUOM itemuom;
AC_Class.Cart cart;
AC_Class.InvoiceDetails invoiceDetails;
ACDatabase db;
String Item;
String ItemUOM;
String Default_curr;
Intent pintent;
EditText etQty;
String default_loc;
List<AC_Class.Item> c_item = new ArrayList<>();
MyClickHandler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_item_detail);
itemuom = new AC_Class.ItemUOM();
items = new AC_Class.Item();
invoiceDetails = new AC_Class.InvoiceDetails();
cart = new AC_Class.Cart();
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
db = new ACDatabase(this);
pintent = getIntent();
//substring = pintent.getStringExtra("substring");
Item = pintent.getStringExtra("ItemKey");
ItemUOM = pintent.getStringExtra("ItemUOMKey");
handler = new MyClickHandler(this);
binding.setHandler(handler);
Cursor loc = db.getReg("7");
if(loc.moveToFirst()){
default_loc = loc.getString(0);
}
items = pintent.getParcelableExtra("Items");
binding.setItem(items);
binding.setInvoicedetail(invoiceDetails);
binding.quantity.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) {
etQty = (EditText)findViewById(R.id.quantity);
String qty = etQty.getText().toString();
if(qty.length() > 0)
{
invoiceDetails.setQuantity(Double.valueOf(qty));
//Calculation();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
onBackPressed();
return true;
}
}
return super.onOptionsItemSelected(item);
}
public class MyClickHandler {
Context context;
public MyClickHandler(Context context) {
this.context = context;
}
public void OnAddClicked(View view) {
//Intent new_intent = new Intent(context, CartList.class);
Intent new_intent = new Intent(context,CartView.class);
new_intent.putExtra("Item", items);
new_intent.putExtra("Quantity",invoiceDetails.getQuantity());
new_intent.putExtra("Price",invoiceDetails.getUPrice());
setResult(1, new_intent);
finish();
}
}
}
OnAddClicked your are finishing the activity when it goes to next activity previous activity goes to end....so remove the finish();
First thing first, to get result from other activity, you need to Use startActivityForResult method instead of startActivity.
Intent item_intent = new Intent(CartView.this, ItemDetail.class);
item_intent.putExtra("ItemKey",itemcode);
item_intent.putExtra("ItemUOMKey",uom);
item_intent.putExtra("Items",sa);
//startActivity(item_intent);
startActivityForResult(item_intent,REQUST_CODE);
and for setting result
Intent new_intent = new Intent();
new_intent.putExtra("Item", items);
new_intent.putExtra("Quantity",invoiceDetails.getQuantity());
new_intent.putExtra("Price",invoiceDetails.getUPrice());
setResult(Activity.RESULT_OK, new_intent);
finish();
and to receive result use below code.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(REQUST_CODE==requestCode && resultCode==Activity.RESULT_OK){
// do logical stuff.
}
}
I have two Edittexts in MainActivity: etFrom and etTo.
When clicked etFrom goes to ListFrom activity and etTo to ListTo activity.ListFrom and ListTo activities contain Listview and after choosing an item it comes back to Main activity and displays results in edittexts. I use MainActivity.putExtra("To",v); and etTo.setText(getIntent().getStringExtra("To")); to get data from an activity.
After clicking on first edittext, choosing an item from Listview and coming back to Main Activity, when I do the same for second edittext the first edittext becomes empty. And the same when I do first one, second one becomes empty.First Second
ListTo Code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_to);
etSearchTo=(EditText) findViewById(R.id.etSearchTo);
listViewTo=(ListView) findViewById(R.id.listViewTo);
initList();
listViewTo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String v="";
Intent intent=new Intent(ListTo.this,SearchRide.class);
switch (position) {
case 0:
v = items[0];
break;
case 1:
v = items[1];
break;
case 2:
v = items[2];
break;
case 3:
v = items[3];
break;
case 4:
v = items[4];
break;
case 5:
v = items[5];
break;
}
intent.putExtra("To",v);
startActivity(intent);
}
});
ListFrom Code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_from);
listView=(ListView) findViewById(R.id.listviewFrom);
editText=(EditText) findViewById(R.id.etsearchFrom);
initList();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String v="";
Intent intent=new Intent(ListFrom.this,SearchRide.class);
switch (position) {
case 0:
v = items[0];
break;
case 1:
v = items[1];
break;
case 2:
v = items[2];
break;
case 3:
v = items[3];
break;
case 4:
v = items[4];
break;
case 5:
v = items[5];
break;
}
intent.putExtra("From",v);
startActivity(intent);
}
});
SearchRide as Main Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_ride);
etDate=(EditText) findViewById(R.id.etDate);
TextView tFrom=(TextView) findViewById(R.id.tFrom);
TextView tTo=(TextView) findViewById(R.id.tTo);
etFrom=(EditText) findViewById(R.id.etFrom);
etTo=(EditText) findViewById(R.id.etTo);
Button bSearch=(Button) findViewById(R.id.bSearch);
ImageView iplussign=(ImageView) findViewById(R.id.iplussign);
ImageView iminussign=(ImageView) findViewById(R.id.iminussign);
final TextView tNumber=(TextView) findViewById(R.id.tNumber);
etTo.setText(getIntent().getStringExtra("To"));
tNumber.setText(String.valueOf(p));
iplussign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(p<=9) {
p++;
tNumber.setText(String.valueOf(p));
}
}
});
iminussign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(p>=2) {
p--;
tNumber.setText(String.valueOf(p));
}
}
});
etFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ListFrom=new Intent(SearchRide.this,ListFrom.class);
startActivity(ListFrom);
}
});
etFrom.setText(getIntent().getStringExtra("From"));
etTo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ToList =new Intent(SearchRide.this,ListTo.class);
startActivity(ToList);
}
});
etTo.setText(getIntent().getStringExtra("To"));
etDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog dialog= new DatePickerDialog(SearchRide.this,R.style.MyDatePickerStyle,listener,calendar.get(Calendar.DAY_OF_MONTH),calendar.get(Calendar.MONTH),calendar.get(Calendar.YEAR));
dialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
dialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
use startActivityForResult() to start ListFrom and ListTo Activities and the receive the result from these activities in OnActivityResult() method.
SearchRide as Main Activity code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_ride);
etDate=(EditText) findViewById(R.id.etDate);
TextView tFrom=(TextView) findViewById(R.id.tFrom);
TextView tTo=(TextView) findViewById(R.id.tTo);
etFrom=(EditText) findViewById(R.id.etFrom);
etTo=(EditText) findViewById(R.id.etTo);
Button bSearch=(Button) findViewById(R.id.bSearch);
ImageView iplussign=(ImageView) findViewById(R.id.iplussign);
ImageView iminussign=(ImageView) findViewById(R.id.iminussign);
final TextView tNumber=(TextView) findViewById(R.id.tNumber);
tNumber.setText(String.valueOf(p));
iplussign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(p<=9) {
p++;
tNumber.setText(String.valueOf(p));
}
}
});
iminussign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(p>=2) {
p--;
tNumber.setText(String.valueOf(p));
}
}
});
etFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ListFrom = new Intent(SearchRide.this,ListFrom.class);
startActivityForResult(ListFrom,0);
}
});
etTo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ToList = new Intent(SearchRide.this,ListTo.class);
startActivityForResult(ToList,1);
}
});
etDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatePickerDialog dialog= new DatePickerDialog(SearchRide.this,R.style.MyDatePickerStyle,listener,calendar.get(Calendar.DAY_OF_MONTH),calendar.get(Calendar.MONTH),calendar.get(Calendar.YEAR));
dialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
dialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if(resultCode == Activity.RESULT_OK){
etFrom.setText(data.getStringExtra("From"));
}
} else if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
etTo.setText(data.getStringExtra("To"));
}
}}
ListFrom code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_from);
listView=(ListView) findViewById(R.id.listviewFrom);
editText=(EditText) findViewById(R.id.etsearchFrom);
initList();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String v="";
switch (position) {
case 0:
v = items[0];
break;
case 1:
v = items[1];
break;
case 2:
v = items[2];
break;
case 3:
v = items[3];
break;
case 4:
v = items[4];
break;
case 5:
v = items[5];
break;
}
Intent intent = new Intent();
intent.putExtra("From",v);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
ListTo code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_to);
etSearchTo=(EditText) findViewById(R.id.etSearchTo);
listViewTo=(ListView) findViewById(R.id.listViewTo);
initList();
listViewTo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String v="";
switch (position) {
case 0:
v = items[0];
break;
case 1:
v = items[1];
break;
case 2:
v = items[2];
break;
case 3:
v = items[3];
break;
case 4:
v = items[4];
break;
case 5:
v = items[5];
break;
}
Intent intent = new Intent();
intent.putExtra("To",v);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
Here is what you can do. Put both from and to values as extra when starting an activity and return them both as result. This way you will be able to remember it. I am assuming you just do not want to use static variables.
// in ListTo activity
intent.putExtra("To",v);
intent.putExtra("From", getIntent().getStringExtra("From"));
// in ListFrom activity
intent.putExtra("From",v);
intent.putExtra("To", getIntent().getStringExtra("To"));
// in Main activity
etTo.setText(getIntent().getStringExtra("To"));
etFrom.setText(getIntent().getStringExtra("From"));
// when starting ListFrom activity
Intent ListFrom=new Intent(SearchRide.this,ListFrom.class);
intent.putExtra("From", getIntent().getStringExtra("From"));
intent.putExtra("To", getIntent().getStringExtra("To"));
startActivity(ListFrom);
// when starting ListTo activity
Intent ToList =new Intent(SearchRide.this,ListTo.class);
intent.putExtra("From", getIntent().getStringExtra("From"));
intent.putExtra("To", getIntent().getStringExtra("To"));
startActivity(ToList);
PS: I have not tested the above code. You can experience null pointer errors, but it should give you the general idea.
I don't use anything related to threads, but the emulator keeps saying:
12-15 14:19:22.807 20983-21204/edu.fontys.stayconnected E/AbstractTracker: Can't create handler inside thread that has not called Looper.prepare()
It there a way to debug some more, so to see why this error happens?
MainActivity:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
final OptionFragmentAdapter adapter = new OptionFragmentAdapter(getSupportFragmentManager());
if (viewPager != null) {
SlidingTabLayout slidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tab_layout);
slidingTabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.colorAccent);
}
});
slidingTabLayout.setDistributeEvenly(true);
viewPager.setAdapter(adapter);
slidingTabLayout.setViewPager(viewPager);
}
if (!NotificationManagerCompat.getEnabledListenerPackages(this).contains(getPackageName())) {
new AlertDialog.Builder(this)
.setTitle(getString(R.string.dialog_notification_title))
.setMessage(R.string.dialog_notification_message)
.setPositiveButton(R.string.dialog_notification_settings, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS));
}
})
.setNegativeButton(R.string.dialog_notification_close_app, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.show();
}
}
}
OptionFragmentAdapter:
public class OptionFragmentAdapter extends FragmentStatePagerAdapter {
private static final String TAG = "OptionFragmentAdapter";
private String[] titles = new String[] { "Lamps", "Apps", "Profile" };
public OptionFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Log.d(TAG, String.format("Current position: %d", position));
Fragment fragment = null;
if (position == 0) {
fragment = new LampsFragment();
} else if (position == 1) {
fragment = new AppsFragment();
} else if (position == 2) {
fragment = new ProfileFragment();
} else {
Log.w(TAG, "There is no fragment found for this position");
}
return fragment;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
#Override
public int getCount() {
return titles.length;
}
}
The slidingTabLayout is from google: https://github.com/google/iosched/blob/master/android/src/main/java/com/google/samples/apps/iosched/ui/widget/SlidingTabLayout.java