Activity not receiving callback from fragment - android

I have a Fragment that interfaces OnWeekViewClickListener as such:
public interface OnWeekViewClickListener {
// TODO: Update argument type and name
public void onWeekViewClick();
}
I assign the listener during the onAttach method as such:
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = activity;
try {
mListener = (OnWeekViewClickListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
yet my Activity that implements OnWeekViewClickListener never receives a call back? Nor any errors?
Here is that activity:
public class RoomDetailsActivity extends FragmentActivity implements RoomAmenityHorizontalViewer.OnFragmentInteractionListener, DayScheduleViewer.OnWeekViewClickListener {
private RoomAmenityHorizontalViewer amenityFrag = RoomAmenityHorizontalViewer.newInstance();
private DayScheduleViewer dayFrag = DayScheduleViewer.newInstance();
private FrameLayout dayViewFrame;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(getWindow().FEATURE_NO_TITLE);
setContentView(R.layout.detail_view_info);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.room_amenity_spinner_view, amenityFrag, "amenityFrag");
transaction.replace(R.id.room_dayview_layout, dayFrag, "dayFrag");
transaction.commit();
ImageButton backButton = (ImageButton) findViewById(R.id.roomDetailsBackBtn);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myBackIntent = new Intent(getBaseContext(), ProximityActivity.class);
startActivity(myBackIntent);
}
});
RoundedImageView pinOverlay = (RoundedImageView) findViewById(R.id.imageView4);
ImageView roomImage = (ImageView) findViewById(R.id.roomImageView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_room_details, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onWeekViewClick() {
Log.v("Fragment Interaction", "Fragment item touched!");
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
Here the fragment is calling the listener:
myWeekView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mListener.onWeekViewClick();
}
});

Related

When back button is pressed the APP exit. Why?

In my App when i press back button from the following activity doesn't return to main activity(fragment) but the App close.
public class ListaSmartphone extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lista_smartphone);
Button buttonSP = (Button)findViewById(R.id.buttonXIAOMI);
buttonSP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent openListaSP = new Intent(ListaSmartphone.this, ElencoXiaomi.class);
startActivity(openListaSP);
}
});
Button buttonTB = (Button)findViewById(R.id.buttonMEIZU);
buttonTB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent openListaTB = new Intent(ListaSmartphone.this, ElencoMeizu.class);
startActivity(openListaTB);
}
});
}
}
THIS IS THE MAIN ACTIVITY CODE
public class MainActivity extends AppCompatActivity {
FragmentPagerAdapter adapterViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager vpPager = (ViewPager) findViewById(R.id.vpPager);
adapterViewPager = new MyPagerAdapter(getSupportFragmentManager());
vpPager.setAdapter(adapterViewPager);
vpPager.setPageTransformer(true, new RotateUpTransformer());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public static class MyPagerAdapter extends FragmentPagerAdapter {
private static int NUM_ITEMS = 4;
private static final String[] TAB_TITLES = new String[]{"WOW STORE", "PRODOTTI", "SERVIZI", "INFO"};
public MyPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Returns total number of pages
// Returns the fragment to display for that page
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FragmentWithZeroImage.newInstance("", R.drawable.wowstorelogo);
case 1:
return FragmentWithOneImage.newInstance("", R.drawable.prodotti);
case 2:
return FragmentWithTwoImages.newInstance("", R.drawable.riparazioni);
case 3:
return FragmentWithThreeImages.newInstance("", R.drawable.info);
default:
return null;
}
}
#Override
public int getCount(){
return TAB_TITLES.length;
}
#Override
public CharSequence getPageTitle(int position){
return TAB_TITLES[position];
}
}
}
The Application works fine, no error but on a devices whe back button is pressed the App exits and doesn't back to MainActivity.
I use Main Activity with four fragments.
While Passing Intent you might have used finish(); after startActivity()
use this code :
#Override
public void onBackPressed() {
this.startActivity(new Intent(ListaSmartphone.this,MainActivity.class));
// super.onBackPressed();
}
and open the fragment in onCreate function of MainActivity
If you want to go back to the MainActivity on back button press then use this code
#Override
public void onBackPressed() {
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}

Actionbar buttons not working

I am new to android development.I have made an app where the MainActivity consists of a Gridview with images and ActivityTwo is the fullscreen view of the selected image.I am trying to add a back button on the actionbar.The icon is visible but it is not clickable.Also i tried to add other menu items which are also visible but nothing happens on touching them.I have also tried adding onClickListener to the menu items as suggested in some posts but it didn't seem to work.
Below is the ActivityTwo code.
public class ActivityTwo extends ActionBarActivity implements OnClickListener {
protected int currentPosition;
Button share,back;
ImageView imageView;
ViewPager viewPager;
private Toolbar toolbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
toolbar= (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
share = (Button)findViewById(R.id.button1);
share.setOnClickListener(this);
back=(Button)findViewById(R.id.button2);
back.setOnClickListener(this);
// get intent data
Intent i = getIntent();
// Selected image id
final int position = i.getExtras().getInt("position");
viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
currentPosition = arg0;
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if
(id==R.id.home)
{
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}
public class ImagePagerAdapter extends PagerAdapter {
Integer[] icons = MainActivity.mThumbIds;
#Override
public int getCount() {
return icons.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = ActivityTwo.this;
imageView = new ImageView(context);
//ImageView imageView = (ImageView)findViewById(R.id.imageView);
// int padding = context.getResources().getDimensionPixelSize(
// R.dimen.padding_large);
imageView.setPadding(5, 5, 5, 5);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageResource(icons[position]);
imageView.setTag(position);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==share){
ImageView Imgv = (ImageView)viewPager.findViewWithTag(viewPager.getCurrentItem());
Drawable mDrawable = Imgv.getDrawable();
Bitmap mBitmap = ((BitmapDrawable)mDrawable).getBitmap();
String path = Images.Media.insertImage(getContentResolver(),
mBitmap, "Image Description", null);
Uri uri = Uri.parse(path);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share Image")); }
if(v==back)
{
finish();
}
}
}
Try to add this code to your toolbar for navigating back
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
For another item in your toolbar
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Toast.makeText(context, "setting", Toast.LENGTH_SHORT).show();
break;
case R.id.action_share:
Toast.makeText(context, "share", Toast.LENGTH_SHORT).show();
break;
}
}
Hope this help
To make your app icon "clickable" as a back button, your Activities must follow a parent-child hierarchy.
Example:
Activity A is your main Activity.
Pressing something (say a ListView item or GridView item) will start Activity B.
In this way Activity A is what's called a parent Activity to Activity B.
You define this in XML in your manifest like so:
<activity
android:name="com.example.android.ActivityA"
android:label="#string/title_activity_a" />
<activity
android:name="com.example.android.ActivityB"
android:label="#string/title_activity_b"
android:parentActivityName="com.example.android.ActivityA">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.android.ActivityA" />
</activity>
This will make the app icon appear with a back arrow ( < ) to the left of it.
We then must handle the click event.
We so this from within our onOptionsItemSelected method in Activity B like so:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// Create an intent to start Activity A.
Intent intent = new Intent(ActivityB.this, ActivityA.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
android.R.id.home is the ID of the click event we are listening for.
Sometimes you may wish to simulate a back button press instead of starting Activity A fresh with an intent. You could achieve that like so:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// Simulate back button press.
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}

Cannot signin to QuickBlox in Android

I am new to QuickBlox. After going through the tutorial I have done the following to signup a new user into QuickBlox. The problem is that I am getting the following errors:
1. {"errors":["Token is required"]}
2. STATUS : 201
I referred to the following question Register user to QuickBlox Users from android but it didn't help.
My Codes:
public class MainActivity extends ActionBarActivity implements OnClickListener {
Button sign_up;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QBSettings.getInstance().fastConfigInit("XxxXX", "XXXXXX",
"XXXXXX");
sign_up = (Button) findViewById(R.id.sign_up);
sign_up.setOnClickListener(MainActivity.this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.sign_up:
QBAuth.createSession(new QBEntityCallback<QBSession>() {
#Override
public void onError(List<String> arg0) {
// TODO Auto-generated method stub
}
#Override
public void onSuccess() {
// TODO Auto-generated method stub
final QBUser user = new QBUser("user1", "123456789");
user.setExternalId("45345");
user.setFullName("User1");
user.setPhone("123456789");
QBUsers.signUp(user, new QBEntityCallbackImpl<QBUser>() {
#Override
public void onSuccess(QBUser user, Bundle args) {
}
#Override
public void onError(List<String> errors) {
}
});
}
#Override
public void onSuccess(QBSession arg0, Bundle arg1) {
// TODO Auto-generated method stub
}
});
break;
default:
break;
}
}
}
Where did you get this error? It's not clear from your code example
Also the right way to create a user is inside this callback:
#Override
public void onSuccess(QBSession arg0, Bundle arg1)
not this
#Override
public void onSuccess()

FriendPickerFragment Facebook Android SDK not showing anything

i don't know what's wrong with my code. As long as i know my code is right, but i still got java.lang.null.pointer in
friendPickerFragment.loadData(false);
i already defined friendPickerFragment like this but still, i got error
friendPickerFragment = (FriendPickerFragment) fragmentManager.findFragmentById(R.id.friend_picker_fragment);
Here is my whole code and i think it's the same as facebook sdk sample friendpicker
public class PickFriends extends FragmentActivity {
FriendPickerFragment friendPickerFragment;
public static void populateParameters(Intent intent, String userId, boolean multiSelect, boolean showTitleBar){
intent.putExtra(FriendPickerFragment.USER_ID_BUNDLE_KEY,userId);
intent.putExtra(FriendPickerFragment.MULTI_SELECT_BUNDLE_KEY, multiSelect);
intent.putExtra(FriendPickerFragment.SHOW_TITLE_BAR_BUNDLE_KEY,showTitleBar);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pick_friends);
FragmentManager fragmentManager = getSupportFragmentManager();
if(savedInstanceState == null){
final Bundle args = getIntent().getExtras();
friendPickerFragment = new FriendPickerFragment(args);
fragmentManager.beginTransaction()
.add(R.id.friend_picker_fragment, friendPickerFragment);
//friendPickerFragment = (FriendPickerFragment) fragmentManager.findFragmentById(R.id.friend_picker_fragment);
} else {
friendPickerFragment = (FriendPickerFragment) fragmentManager.findFragmentById(R.id.friend_picker_fragment);
}
friendPickerFragment.setOnErrorListener(new PickerFragment.OnErrorListener() {
#Override
public void onError(PickerFragment<?> fragment, FacebookException error) {
PickFriends.this.onError(error);
}
});
friendPickerFragment.setOnDoneButtonClickedListener(new PickerFragment.OnDoneButtonClickedListener() {
#Override
public void onDoneButtonClicked(PickerFragment<?> fragment) {
SelectFriend application = (SelectFriend) getApplication();
application.setSelectedUsers(friendPickerFragment.getSelection());
setResult(RESULT_OK,null);
finish();
}
});
}
private void onError(Exception error){
String text = "Error Exception";
Toast toast = Toast.makeText(this,text,Toast.LENGTH_SHORT);
toast.show();
}
#Override
protected void onStart(){
super.onStart();
friendPickerFragment.loadData(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_pick_friends, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Please help me. Thank you

android fragment onorientationchange issue

I created a simple project that Button in Activity click to Show Toast from Fragment.Works fine when just click Button, but after orientation changed and clicking Button occurs error.
public class MainActivity extends Activity {
PlaceholderFragment pf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pf = new PlaceholderFragment();
Button b = (Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
pf.showToast();
}
});
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, pf)
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Log.i("TAG", "onCreateView");
return rootView;
}
public void showToast(){
Toast.makeText(getActivity(), "Show Toast from PlaceholderFragment", Toast.LENGTH_SHORT).show();
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
Log.i("TAG", "onAttach");
}
#Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
Log.i("TAG", "onDetach");
}
}
}
I found out Fragment was calling onAttach and onDetach after orientating. How can i fix this problem?
When the device Orientation changes, the activity in which the fragment sits is by default destroyed and created again. You can avoid these changes by adjusting the android:configChanges in the manifest file. This code should work:
android:configChanges="keyboardHidden|orientation"

Categories

Resources