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
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;
}
}
building an Android App using Room DB. I've uninstalled the app various times but always seem to get the same entry as i re-install it.
I can't seem to reach the onCreate part of the RoomDatabase.Callback as I'm trying to add some dummy entries and log some info to the logs.
public class MainActivity extends AppCompatActivity {
private ContactsAdapter contactsAdapter;
private ArrayList<Contact> contactArrayList = new ArrayList<>();
private RecyclerView recyclerView;
private ContactsAppDatabase contactsAppDatabase;
private static final String TAG="MainActivityTag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(" Contacts Manager ");
recyclerView = findViewById(R.id.recycler_view_contacts);
contactsAppDatabase= Room.databaseBuilder(getApplicationContext(),ContactsAppDatabase.class,"ContactDB")
.addCallback(callback)
.build();
new GetAllContactsAsyncTask().execute();
contactsAdapter = new ContactsAdapter(this, contactArrayList, MainActivity.this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(contactsAdapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addAndEditContacts(false, null, -1);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void addAndEditContacts(final boolean isUpdate, final Contact contact, final int position) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
View view = layoutInflaterAndroid.inflate(R.layout.layout_add_contact, null);
AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilderUserInput.setView(view);
TextView contactTitle = view.findViewById(R.id.new_contact_title);
final EditText newContact = view.findViewById(R.id.name);
final EditText contactEmail = view.findViewById(R.id.email);
contactTitle.setText(!isUpdate ? "Add New Contact" : "Edit Contact");
if (isUpdate && contact != null) {
newContact.setText(contact.getName());
contactEmail.setText(contact.getEmail());
}
alertDialogBuilderUserInput
.setCancelable(false)
.setPositiveButton(isUpdate ? "Update" : "Save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
}
})
.setNegativeButton("Delete",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
if (isUpdate) {
deleteContact(contact, position);
} else {
dialogBox.cancel();
}
}
});
final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
alertDialog.show();
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(newContact.getText().toString())) {
Toast.makeText(MainActivity.this, "Enter contact name!", Toast.LENGTH_SHORT).show();
return;
} else {
alertDialog.dismiss();
}
if (isUpdate && contact != null) {
updateContact(newContact.getText().toString(), contactEmail.getText().toString(), position);
} else {
createContact(newContact.getText().toString(), contactEmail.getText().toString());
}
}
});
}
private void deleteContact(Contact contact, int position) {
contactArrayList.remove(position);
new DeleteContactAsyncTask().execute(contact);
}
private void updateContact(String name, String email, int position) {
Contact contact = contactArrayList.get(position);
contact.setName(name);
contact.setEmail(email);
new UpdateContactAsyncTask().execute(contact);
contactArrayList.set(position, contact);
}
private void createContact(String name, String email) {
new CreateContactAsyncTask().execute(new Contact(0,name,email));
}
private class GetAllContactsAsyncTask extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... voids) {
contactArrayList.addAll(contactsAppDatabase.getContactDAO().getContacts());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
contactsAdapter.notifyDataSetChanged();
}
}
private class CreateContactAsyncTask extends AsyncTask<Contact,Void,Void>{
#Override
protected Void doInBackground(Contact... contacts) {
long id = contactsAppDatabase.getContactDAO().addContact(contacts[0]);
Contact contact = contactsAppDatabase.getContactDAO().getContact(id);
if (contact != null) {
contactArrayList.add(0, contact);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
contactsAdapter.notifyDataSetChanged();
}
}
private class UpdateContactAsyncTask extends AsyncTask<Contact,Void,Void>{
#Override
protected Void doInBackground(Contact... contacts) {
contactsAppDatabase.getContactDAO().updateContact(contacts[0]);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
contactsAdapter.notifyDataSetChanged();
}
}
private class DeleteContactAsyncTask extends AsyncTask<Contact,Void,Void>{
#Override
protected Void doInBackground(Contact... contacts) {
contactsAppDatabase.getContactDAO().deleteContact(contacts[0]);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
contactsAdapter.notifyDataSetChanged();
}
}
RoomDatabase.Callback callback = new RoomDatabase.Callback() {
#Override
public void onCreate(#NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
//Toast.makeText(getApplicationContext()," On Create Called ",Toast.LENGTH_LONG).show();
Log.i(TAG, " on create invoked ");
createContact("name 1","email 1");
createContact("name 2","email 2");
createContact("name 3","email 3");
}
#Override
public void onOpen(#NonNull SupportSQLiteDatabase db) {
super.onOpen(db);
// Toast.makeText(getApplicationContext()," On Create Called ",Toast.LENGTH_LONG).show();
Log.i(TAG, " on open invoked ");
}
};
}
I've added write/ read external storage in the manifest unsure if thats important.
Things is onOpen gets invoked from within the callback so it seems a little weird.
github repo
when I install the app onanother device it works fine. obviously on the other (the first) device I still get the error even after deleting and reinstalling the app.
Please help.
I have a problem every time i open an activity (blueToothSearch.java) the following error occurs in my logcat.
12-04 18:57:52.317 5354-5354/com.example.admin.paniccenter E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.admin.paniccenter, PID: 5354
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.admin.paniccenter/com.example.admin.paniccenter.blueToothSearch}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at org.altbeacon.beacon.BeaconManager.<init>(BeaconManager.java:323)
at org.altbeacon.beacon.BeaconManager.getInstanceForApplication(BeaconManager.java:315)
at com.example.admin.paniccenter.blueToothSearch.<init>(blueToothSearch.java:65)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Below is my blueToothSearch activity which i want to use to display a list of beacons in my region.
public class blueToothSearch extends AppCompatActivity implements BeaconConsumer {
private static final String TAG = "blueToothSearch";
private ViewPagerAdapter viewadapter;
private ViewPager myViewPager;
private TabLayout tabLayout;
public Toolbar toolbar;
//public static Handler UIHandler;
private static final int REQUEST_ENABLE_BT = 1234;
//public static final String EXTRAS_TARGET_ACTIVITY = "extrasTargetActivity";
//private static final String JAALEE_BEACON_PROXIMITY_UUID = "EBEFD083-70A2-47C8-9837-E7B5634DF524";//Jaalee BEACON Default UUID
// private static final Region ALL_BEACONS_REGION = new Region("rid", null, null, null);
//public static final String EXTRAS_BEACON = "extrasBeacon";
public BeaconManager beaconManager = BeaconManager.getInstanceForApplication(getBaseContext());
private ArrayList<Beacon> arrayL = new ArrayList<Beacon>();
private BeaconServiceUtility beaconUtill = null;
private BeaconAdapter adapterr;
public ListView list;
private LayoutInflater inflater;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
viewadapter = new ViewPagerAdapter(getSupportFragmentManager());
toolbar = (Toolbar)findViewById(R.id.toolbar);
toolbar.setTitle("Bluetooth Devices");
//Set up the View Pager with the View page adapter
myViewPager = (ViewPager)findViewById(R.id.viewpager);
tabLayout = (TabLayout)findViewById(R.id.tabs);
tabLayout.setupWithViewPager(myViewPager);
//tabLayout.setVisibility(View.GONE);
final FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setImageResource(R.drawable.ic_popup_sync_24);
setupViewPager(myViewPager);
setSupportActionBar(toolbar);
//viewPager.setAdapter(adapter);
myViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position){
case 0: fab.show();
break;
case 1: fab.hide();
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
//getSupportActionBar().setDisplayShowHomeEnabled(true);
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
drawer.closeDrawer(Gravity.LEFT);
}
});
adapterr = new BeaconAdapter();
list = findViewById(R.id.beaconlist);
list.setAdapter(adapterr);
//list.setOnItemClickListener(createOnItemClickListener());
inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private void setupViewPager(ViewPager viewPager){
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new blueToothSearch.bluetooth(), "Available Devices");
adapter.addFragment(new bluetoothProperties(), "Device Properties");
viewPager.setAdapter(adapter);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_ENABLE_BT){
if (resultCode == Activity.RESULT_OK){
connectToService();
}else {
Toast.makeText(this, "Bluetooth not enabled", Toast.LENGTH_LONG).show();
getSupportActionBar().setSubtitle("Bluetooth not enabled");
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void connectToService(){
try {
beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
}catch (RemoteException e){
e.printStackTrace();
}
try {
beaconManager.startMonitoringBeaconsInRegion(new Region("myMonitoringUniqueId", null, null, null));
}catch (RemoteException e){
e.printStackTrace();
}
}
/**
private AdapterView.OnItemClickListener createOnItemClickListener(){
return new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
if (getIntent().getStringExtra(EXTRAS_TARGET_ACTIVITY) != null){
try {
Class<?> clazz = Class.forName(getIntent().getStringExtra(EXTRAS_TARGET_ACTIVITY));
Intent intent = new Intent(blueToothSearch.this, clazz );
Beacon temp = adapterr.getItem(pos);
intent.putExtra(EXTRAS_BEACON, temp);
if(getIntent().getStringExtra(EXTRAS_TARGET_ACTIVITY).contains("com.example.admin.paniccenter.CharacteristicsDemoActivity"))
{
startActivity(intent);
// if (temp.getProximityUUID().equalsIgnoreCase(JAALEE_BEACON_PROXIMITY_UUID)) {
// startActivity(intent);
// }
// else
// {
// ListBeaconsActivity.this.runOnUiThread(new Runnable()
//{
// public void run()
// {
//Toast.makeText(ListBeaconsActivity.this, "Current Beacon is in Non-Connectable mode", Toast.LENGTH_LONG).show();
// }
// });
// }
}
else
{
startActivity(intent);
}
}catch (ClassNotFoundException e){
Log.e(TAG, "Finding class by name failed", e);
}
}
}
};
}
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.scan_menu, menu);
MenuItem refreshItem = menu.findItem(R.id.refresh);
refreshItem.setActionView(R.layout.actionbar_indeterminate_progress);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onStart() {
super.onStart();
beaconUtill.onStart(beaconManager, this);
}
#Override
public void onStop() {
beaconUtill.onStop(beaconManager, this);
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onBeaconServiceConnect() {
getSupportActionBar().setSubtitle("Scanning...");
Toast.makeText(this, "Scanning for devices", Toast.LENGTH_LONG).show();
beaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
arrayL.clear();
arrayL.addAll((ArrayList<Beacon>) beacons);
adapterr.notifyDataSetChanged();
}
});
beaconManager.setMonitorNotifier(new MonitorNotifier() {
#Override
public void didEnterRegion(Region region) {
Log.e("BeaconDetactorService", "didEnterRegion");
}
#Override
public void didExitRegion(Region region) {
Log.e("BeaconDetactorService", "didExitRegion");
}
#Override
public void didDetermineStateForRegion(int i, Region region) {
Log.e("BeaconDetactorService", "didDetermineStateForRegion");
}
});
connectToService();
}
public static class bluetooth extends Fragment {
private static final String TAG = "bluetooth";
private int position;
private TextView textv;
private ViewPagerAdapter viewadapter;
private ViewPager myViewPager;
private TabLayout tabLayout;
private FragmentActivity myContext;
#Override
public void onAttach(Context context) {
super.onAttach(context);
//hideAction = (HideActionBar)getContext();
myContext = (FragmentActivity)getContext();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//position = getArguments().getInt("pos");
//toolbar.getMenu().clear();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//return inflater.inflate(R.layout.fragment_bluetooth_search, container, false);
View view = inflater.inflate(R.layout.fragment_bluetooth_search, container, false);
//TextView text = (TextView)getActivity().findViewById(R.id.view);
//text.setText("i am the real text ");
//hideAction.customBlueToothToolbar();
//FloatingActionButton fl = (FloatingActionButton)getActivity().findViewById(R.id.fab);
//fl.setImageResource(R.drawable.ic_popup_sync_24);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
public class BeaconAdapter extends BaseAdapter {
private ArrayList<Beacon> beacons;
#Override
public int getCount() {
return arrayL.size();
}
#Override
public Beacon getItem(int arg0) {
return arrayL.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
try {
ViewHolder holder;
if (convertView != null) {
holder = (ViewHolder) convertView.getTag();
} else {
holder = new ViewHolder(convertView = inflater.inflate(R.layout.tupple_monitoring, null));
}
if (beacons.get(position).getParserIdentifier() != null)
holder.beacon_uuid.setText("UUID: " + arrayL.get(position).getParserIdentifier());
holder.beacon_major.setText("Major: " + arrayL.get(position).getBeaconTypeCode());
holder.beacon_minor.setText(", Minor: " + arrayL.get(position).getBluetoothName());
holder.beacon_proximity.setText("Proximity: " + arrayL.get(position).getDistance());
holder.beacon_rssi.setText(", Rssi: " + arrayL.get(position).getRssi());
holder.beacon_txpower.setText(", TxPower: " + arrayL.get(position).getTxPower());
holder.beacon_range.setText("" + arrayL.get(position).getExtraDataFields());
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
private class ViewHolder {
private TextView beacon_uuid;
private TextView beacon_major;
private TextView beacon_minor;
private TextView beacon_proximity;
private TextView beacon_rssi;
private TextView beacon_txpower;
private TextView beacon_range;
public ViewHolder(View view) {
beacon_uuid = (TextView) view.findViewById(R.id.BEACON_uuid);
beacon_major = (TextView) view.findViewById(R.id.BEACON_major);
beacon_minor = (TextView) view.findViewById(R.id.BEACON_minor);
beacon_proximity = (TextView) view.findViewById(R.id.BEACON_proximity);
beacon_rssi = (TextView) view.findViewById(R.id.BEACON_rssi);
beacon_txpower = (TextView) view.findViewById(R.id.BEACON_txpower);
beacon_range = (TextView) view.findViewById(R.id.BEACON_range);
view.setTag(this);
}
}
}
I am using a BeaconManager class to range and scan my beacons, the library is from package org.altbeacon.beacon
I am having four tab in my View pager I have search in google but I can,t found any solution when Swipe my view pager it work fine like 1-2-3-4 but when I try to swipe reverse 4-3-2-1 than my data get lost or you can say my adapter get lost.My View Pager is inside Activity.My Data is lost when I go to next page and back then back my data is lost.
My Main Activity is:
public class MainActivity extends AppCompatActivity {
public static int notificationCountCart = 0;
Toolbar toolbar;
ActionBar actionBar;
static ViewPager viewPager;
static TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
if (toolbar != null)
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
if (actionBar != null) {
TextView textView = new TextView(this);
textView.setText("Shopping");
textView.setTextSize(20);
textView.setTypeface(null, Typeface.BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(getResources().getColor(R.color.white));
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(textView);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(new IconDrawable(this, FontAwesomeIcons.fa_angle_left).colorRes(R.color.white).actionBarSize());
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
viewPager = (ViewPager) findViewById(R.id.viewpagerrr);
tabLayout = (TabLayout) findViewById(R.id.tabs);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
}
#Override
protected void onResume() {
super.onResume();
invalidateOptionsMenu();
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#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 onPrepareOptionsMenu(Menu menu) {
// Get the notifications MenuItem and
// its LayerDrawable (layer-list)
MenuItem item = menu.findItem(R.id.action_cart);
NotificationCountSetClass.setAddToCart(MainActivity.this, item, notificationCountCart);
// force the ActionBar to relayout its MenuItems.
// onCreateOptionsMenu(Menu) will be called again.
invalidateOptionsMenu();
return super.onPrepareOptionsMenu(menu);
}
#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_search) {
startActivity(new Intent(MainActivity.this, SearchResultActivity.class));
return true;
} else if (id == R.id.action_cart) {
/* NotificationCountSetClass.setAddToCart(MainActivity.this, item, notificationCount);
invalidateOptionsMenu();*/
startActivity(new Intent(MainActivity.this, CartListActivity.class));
/* notificationCount=0;//clear notification count
invalidateOptionsMenu();*/
return true;
} else if (id == android.R.id.home) {
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
// startActivity(new Intent(MainActivity.this, EmptyActivity.class));
}
return super.onOptionsItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
ImageListFragment fragment = new ImageListFragment();
SpeakerFragment speakerFragment = new SpeakerFragment();
adapter.addFragment(fragment, getString(R.string.item_2));
adapter.addFragment(speakerFragment, getString(R.string.item_4));
adapter.addFragment(new HeadPhone(), getString(R.string.item_3));
adapter.addFragment(new Offer(), getString(R.string.item_1));
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
My Fragment is
public class ImageListFragment extends Fragment {
String category_Name, Category_ID, Product_ID, Product_Name,
Product_Image, Product_Price, Product_Sale, Cart;
public static final String STRING_IMAGE_URI = "ImageUri";
public static final String STRING_IMAGE_POSITION = "ImagePosition";
private static MainActivity mActivity;
ArrayList<SingleItemModel> singleItemModels;
RecyclerView recyclerView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getCategoryone();
Fresco.initialize(getContext());
mActivity = (MainActivity) getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
recyclerView = (RecyclerView) inflater.inflate(R.layout.layout_recylerview_list, container, false);
return recyclerView;
}
public static class SimpleStringRecyclerViewAdapter
extends RecyclerView.Adapter<ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder> {
// private String[] mValues;
private ArrayList<SingleItemModel> mValues;
private RecyclerView mRecyclerView;
public static class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final SimpleDraweeView mImageView;
public final LinearLayout mLayoutItem;
public final ImageView mImageViewWishlist;
TextView iTemName, itemDescription, itemPrice;
public ViewHolder(View view) {
super(view);
mView = view;
mImageView = (SimpleDraweeView) view.findViewById(R.id.image1);
mLayoutItem = (LinearLayout) view.findViewById(R.id.layout_item);
mImageViewWishlist = (ImageView) view.findViewById(R.id.ic_wishlist);
iTemName = (TextView) view.findViewById(R.id.itemName);
itemDescription = (TextView) view.findViewById(R.id.itemDescription);
itemPrice = (TextView) view.findViewById(R.id.itemPrice);
}
}
public SimpleStringRecyclerViewAdapter(RecyclerView recyclerView, ArrayList<SingleItemModel> items) {
mValues = items;
mRecyclerView = recyclerView;
}
#Override
public ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder(view);
}
#Override
public void onViewRecycled(ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder holder) {
if (holder.mImageView.getController() != null) {
holder.mImageView.getController().onDetach();
}
if (holder.mImageView.getTopLevelDrawable() != null) {
holder.mImageView.getTopLevelDrawable().setCallback(null);
//
}
}
#Override
public void onBindViewHolder(final ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder holder, final int position) {
SingleItemModel singleItemModel = mValues.get(position);
holder.iTemName.setText(singleItemModel.getCategory_Name());
final Uri uri = Uri.parse(singleItemModel.getProduct_Image());
holder.mImageView.setImageURI(uri);
holder.itemPrice.setText(singleItemModel.getProduct_Price());
holder.itemDescription.setText(singleItemModel.getProduct_Sale());
}
#Override
public int getItemCount() {
return mValues.size();
}
}
public void getCategoryone() {
final RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://proaudiobrands.com/app/feature.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("shabina shopping response", response);
try {
singleItemModels = new ArrayList<>();
JSONObject mainObj = new JSONObject(response);
Log.d("shabina ", response);
JSONArray Feature_product = mainObj.getJSONArray("Feature_product");
for (int i = 0; i < Feature_product.length(); i++) {
JSONObject Feature_Product = Feature_product.getJSONObject(i);
String Category_Namee = Feature_Product.getString("Category_Namee");
String Category_IDs = Feature_Product.getString("Category_IDs");
JSONArray Product_List = Feature_Product.getJSONArray("Product_List");
for (int j = 0; j < Product_List.length(); j++) {
JSONObject Category_Name = Product_List.getJSONObject(j);
if (Category_Name.getString("Category_Name").equals("Microphones")) {
category_Name = Category_Name.getString("Category_Name");
Category_ID = Category_Name.getString("Category_ID");
Product_ID = Category_Name.getString("Product_ID");
Product_Name = Category_Name.getString("Product_Name");
Product_Image = Category_Name.getString("Product_Image");
Product_Price = Category_Name.getString("Product_Price");
Product_Sale = Category_Name.getString("Product_Sale");
Cart = Category_Name.getString("Cart");
Log.e("sushil Category_Name", category_Name + " " + Category_ID + " " + Product_ID + " " + Product_Name + " " + Product_Image + " " + Product_Price + " " + Product_Sale + " " + Cart);
SingleItemModel singleItemModel1 = new SingleItemModel(category_Name, Category_ID, Product_ID, Product_Name, Product_Image, Product_Price, Product_Sale, Cart);
singleItemModels.add(singleItemModel1);
}
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(new ImageListFragment.SimpleStringRecyclerViewAdapter(recyclerView, singleItemModels));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("method", "feature");
params.put("userId", "PRO1");
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
90000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
}
}
Replace your MainActivity with below
public class MainActivity extends AppCompatActivity {
public static int notificationCountCart = 0;
Toolbar toolbar;
ActionBar actionBar;
static ViewPager viewPager;
static TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
if (toolbar != null)
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
if (actionBar != null) {
TextView textView = new TextView(this);
textView.setText("Shopping");
textView.setTextSize(20);
textView.setTypeface(null, Typeface.BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(getResources().getColor(R.color.white));
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(textView);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(new IconDrawable(this, FontAwesomeIcons.fa_angle_left).colorRes(R.color.white).actionBarSize());
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
viewPager = (ViewPager) findViewById(R.id.viewpagerrr);
viewPager.setOffscreenPageLimit(4);
tabLayout = (TabLayout) findViewById(R.id.tabs);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
}
#Override
protected void onResume() {
super.onResume();
invalidateOptionsMenu();
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#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 onPrepareOptionsMenu(Menu menu) {
// Get the notifications MenuItem and
// its LayerDrawable (layer-list)
MenuItem item = menu.findItem(R.id.action_cart);
NotificationCountSetClass.setAddToCart(MainActivity.this, item, notificationCountCart);
// force the ActionBar to relayout its MenuItems.
// onCreateOptionsMenu(Menu) will be called again.
invalidateOptionsMenu();
return super.onPrepareOptionsMenu(menu);
}
#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_search) {
startActivity(new Intent(MainActivity.this, SearchResultActivity.class));
return true;
} else if (id == R.id.action_cart) {
/* NotificationCountSetClass.setAddToCart(MainActivity.this, item, notificationCount);
invalidateOptionsMenu();*/
startActivity(new Intent(MainActivity.this, CartListActivity.class));
/* notificationCount=0;//clear notification count
invalidateOptionsMenu();*/
return true;
} else if (id == android.R.id.home) {
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
// startActivity(new Intent(MainActivity.this, EmptyActivity.class));
}
return super.onOptionsItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
ImageListFragment fragment = new ImageListFragment();
SpeakerFragment speakerFragment = new SpeakerFragment();
adapter.addFragment(fragment, getString(R.string.item_2));
adapter.addFragment(speakerFragment, getString(R.string.item_4));
adapter.addFragment(new HeadPhone(), getString(R.string.item_3));
adapter.addFragment(new Offer(), getString(R.string.item_1));
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
Hello need help with a class trying to figure out how to create a first and last button in a fragment that will jump to the first item in a ViewPager and the last item in a ViewPager I'm a bit lost with how to implement. Here is the fragment.
public class CrimeFragment extends Fragment {
private static final String ARG_CRIME_ID = "crime_id";
private static final String DIALOG_DATE = "DialogDate";
private static final int REQUEST_DATE = 0;
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
private CheckBox mSolvedCheckBox;
private Spinner mSpinner;
private Button mFirstButton;
private Button mLastButton;
public static CrimeFragment newInstance(UUID crimeId) {
Bundle args = new Bundle();
args.putSerializable(ARG_CRIME_ID, crimeId);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == REQUEST_DATE) {
Date date =
(Date) data.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDate();
}
}
private void updateDate() {
mDateButton.setText(mCrime.getDate().toString());
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID crimeId = (UUID) getArguments().getSerializable(ARG_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, container, false);
mTitleField = (EditText)v.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.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) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
mDateButton = (Button) v.findViewById(R.id.crime_date);
updateDate();
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
DatePickerFragment dialog = DatePickerFragment.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(manager, DIALOG_DATE);
}
});
mSpinner = (Spinner) v.findViewById(R.id.crime_severity);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
R.array.severity_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
mCrime.setSeverity((String) mSpinner.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});
mSolvedCheckBox = (CheckBox) v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
mCrime.setSolved(isChecked);
}
});
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return v;
}
}
Here is the Activity with the ViewPager.
public class CrimePagerActivity extends FragmentActivity{
private static final String EXTRA_CRIME_ID = "com.martin.android.criminalintent.crime_id";
private ViewPager mViewPager;
private List<Crime> mCrimes;
public static Intent newIntent(Context packageContext, UUID crimeId) {
Intent intent = new Intent(packageContext, CrimePagerActivity.class);
intent.putExtra(EXTRA_CRIME_ID, crimeId);
return intent;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime_pager);
UUID crimeId = (UUID) getIntent().getSerializableExtra(EXTRA_CRIME_ID);
mViewPager = (ViewPager) findViewById(R.id.activity_crime_pager_view_pager);
mCrimes = CrimeLab.get(this).getCrimes();
FragmentManager fragmentManager = getSupportFragmentManager();
mViewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
#Override
public Fragment getItem(int position) {
Crime crime = mCrimes.get(position);
return CrimeFragment.newInstance(crime.getId());
}
#Override
public int getCount() {
return mCrimes.size();
}
});
for (int i = 0; i < mCrimes.size(); i++) {
if (mCrimes.get(i).getId().equals(crimeId)) {
mViewPager.setCurrentItem(i);
break;
}
}
}
}
For the First button Im pretty sure I just need to set item to 0? For last button I need to set item to size - 1 just not sure how to do that.
In your CrimePagerActivity, write two method's to jump to the ViewPager first page and last page.
CrimePagerActivity.java:
public void jumpToFirstPage() {
mViewPager.setCurrentItem(0);
}
public void jumpToLastPage() {
mViewPager.setCurrentItem(mCrimes.size() - 1);
}
Call those method's from mFirstButton and mLastButton click listener method:
CrimeFragment.java:
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((CrimePagerActivity)getActivity()).jumpToFirstPage();
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((CrimePagerActivity)getActivity()).jumpToLastPage();
}
});
Hope this will work perfectly.
Ok this was a answer that I was given by the teacher incase anyone is interested.
mFirstButton = (Button) v.findViewById(R.id.first_crime_button);
mFirstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewPager pager = (ViewPager) getActivity().findViewById(R.id.activity_crime_pager_view_pager);
pager.setCurrentItem(0);
}
});
mLastButton = (Button) v.findViewById(R.id.last_crime_button);
mLastButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewPager pager = (ViewPager) getActivity().findViewById(R.id.activity_crime_pager_view_pager);
pager.setCurrentItem(CrimeLab.get(getActivity()).getCrimes().size()-1);
}
});
Create two button and on click set
viewPager.setCurrentItem(0); // for top
and
viewPager.setCurrentItem(mCrimes.size()); // for last