How to pass data from ListView in activity to fragment To view the location on the map, look on my method addMarker() in FragmentTwoClass?
.....................................................................................................
FavoritesActivity:
public class Favorites extends AppCompatActivity {
private ArrayList<MapModel> mMapList; // ArrayList of MovieModel
private MapCustomAdapterFavorites mAdapter; // CustomAdapter of MainActivity
private GetMapsAsyncTaskFavorites mGetMapsAsyncTaskFavorites; // AsyncTask for AddMovie to add movie to MainActivity
private ListView mListView; // ListView of MainActivity
private MapDBHelperFavorites mMapDBHelper; // The SQLiteHelper of the app
private SwipeRefreshLayout swipeRefreshLayout; // SwipeRe freshLayout of MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorite);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("LocationProject");
mListView = findViewById(R.id.listFavorites); // ID of the ListView of MainActivity
swipeRefreshLayout = findViewById(R.id.swipe_container); // ID of the SwipeRefreshLayout of MainActivity
mMapDBHelper = new MapDBHelperFavorites(this); // Put the SQLiteHelper in MainActivity
mMapList = mMapDBHelper.getAllMaps(); // Put the getAllMovies of SQLiteHelper in the ArrayList of MainActivity
mAdapter = new MapCustomAdapterFavorites(this, mMapList); // Comparing the ArrayList of MainActivity to the CustomAdapter
registerForContextMenu(mListView);
// Put AsyncTask in the ListView of MainActivity to execute the SQLiteHelper
mGetMapsAsyncTaskFavorites = new GetMapsAsyncTaskFavorites(mListView);
mGetMapsAsyncTaskFavorites.execute(mMapDBHelper);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentTwo fragObj = new FragmentTwo();
Bundle bundle = new Bundle();
bundle.putSerializable(getString(R.string.map_edit_favorites), (mMapList.get(position)));
fragObj.setArguments(bundle);
}
});
swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorOrange)); // Colors of the SwipeRefreshLayout of MainActivity
// Refresh the MovieDBHelper of app in ListView of MainActivity
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mGetMapsAsyncTaskFavorites = new GetMapsAsyncTaskFavorites(mListView);
mGetMapsAsyncTaskFavorites.execute(mMapDBHelper);
// Vibration for 0.1 second
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
vibrator.vibrate(100);
}
finish();
startActivity(getIntent()); // Refresh activity
Toast toast = Toast.makeText(Favorites.this, "The list are refreshed!", Toast.LENGTH_SHORT);
View view = toast.getView();
view.getBackground().setColorFilter(getResources().getColor(R.color.colorLightBlue), PorterDuff.Mode.SRC_IN);
TextView text = view.findViewById(android.R.id.message);
text.setTextColor(getResources().getColor(R.color.colorBrown));
toast.show(); // Toast
swipeRefreshLayout.setRefreshing(false);
}
});
}
// Sets off the menu of activity_menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.favorites_menu, menu);
return super.onCreateOptionsMenu(menu);
}
// Sets off the menu of list_menu
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.favorites_list_menu, menu);
}
// Options in the activity_menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.mute: // Mute all the sound in app
AudioManager managerYes = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
managerYes.setStreamMute(AudioManager.STREAM_MUSIC, true);
Toast toastMute = Toast.makeText(this, "The sound are mute!", Toast.LENGTH_SHORT);
View viewMute = toastMute.getView();
viewMute.getBackground().setColorFilter(getResources().getColor(R.color.colorLightBlue), PorterDuff.Mode.SRC_IN);
TextView textMute = viewMute.findViewById(android.R.id.message);
textMute.setTextColor(getResources().getColor(R.color.colorBrown));
toastMute.show(); // Toast
break;
case R.id.unMute: // Allow all the sound in app
AudioManager managerNo = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
managerNo.setStreamMute(AudioManager.STREAM_MUSIC, false);
Toast toastUnMute = Toast.makeText(this, "The sound are on!", Toast.LENGTH_SHORT);
View viewUnMute = toastUnMute.getView();
viewUnMute.getBackground().setColorFilter(getResources().getColor(R.color.colorLightBlue), PorterDuff.Mode.SRC_IN);
TextView textUnMute = viewUnMute.findViewById(android.R.id.message);
textUnMute.setTextColor(getResources().getColor(R.color.colorBrown));
toastUnMute.show(); // Toast
break;
case R.id.intentMainActivity:
Intent intentBackMainActivity = new Intent(this, MainActivity.class);
startActivity(intentBackMainActivity);
break;
case R.id.deleteAllDataFavorites: // Delete all data of the app for delete all the data of the app
Intent intentDeleteAllData = new Intent(this, DeleteAllDataFavorites.class);
startActivity(intentDeleteAllData);
break;
}
return super.onOptionsItemSelected(item);
}
// Options in the list_menu
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int listPosition = info.position;
switch (item.getItemId()) {
case R.id.edit: // Edit the movies on MainActivity
Intent intent = new Intent(Favorites.this, EditMap.class);
intent.putExtra(getString(R.string.map_id), mMapList.get(listPosition).getId());
intent.putExtra(getString(R.string.map_edit), mMapList.get(listPosition));
startActivity(intent);
break;
case R.id.shareIntent:
String name = mMapList.get(listPosition).getName();
String address = mMapList.get(listPosition).getVicinity();
double lat = mMapList.get(listPosition).getLat();
double lng = mMapList.get(listPosition).getLng();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Name: " + name + "\nAddress: " + address + "\nLatitude: " + lat + "\nLongitude: " + lng);
sendIntent.setType("text/plain");
startActivity(sendIntent);
break;
case R.id.delete: // Delete item(movie) on MainActivity
mGetMapsAsyncTaskFavorites.deleteMovie(listPosition);
mMapDBHelper.deleteMap(mMapList.get(listPosition));
Intent intentDeleteData = new Intent(Favorites.this, DeleteMap.class);
startActivity(intentDeleteData);
break;
}
return super.onContextItemSelected(item);
}
FragmentTwoClass:
public class FragmentTwo extends Fragment implements OnMapReadyCallback {
private GoogleMap mGoogleMap;
private MapView mMapView;
private View mView;
private MapModel mapModel;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_two_layout, container, false);
mapModel = (MapModel) getArguments().getSerializable(getString(R.string.map_edit_favorites)); // GetSerializable for the texts
return mView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMapView = view.findViewById(R.id.map);
if (mMapView != null) {
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(getContext());
mGoogleMap = googleMap;
addMarker();
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(true);
}
public void addMarker() {
MarkerOptions marker = new MarkerOptions().position(new LatLng(mapModel.getLat(), mapModel.getLng())).title("Elior home");
mGoogleMap.addMarker(marker);
mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
return true;
}
});
}
Related
I'm trying to send a value from TextView to RecyclerView (in an another Activity).
MainActivity.class
There is i want to use a method onClickYes for send each of word to my recyclerView in an another activity.
public class MainActivity extends AppCompatActivity {
TextView display, progress;
private List<String> worldList;
private ArrayList<RecyclerItems> recyclerItems;
private WordDataBase wordDatabaseForYes;
int counter = 1;
int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = findViewById(R.id.dispalay);
progress = findViewById(R.id.progress);
recyclerItems = new ArrayList<>();
worldList = new ArrayList<>();
worldList.add("cat");//i want to display this word firstly
worldList.add("dog");//it after click
worldList.add("monkey");//after it
worldList.add("bird");//after it
worldList.add("fish");//etc
worldList.add("home");//etc
worldList.add("car");//etc
}
public void onClickYes(View view) {
if (i >= worldList.size()) return;
display.setText(worldList.get(i));
progress.setText(counter + "");
//заполняем наш recyclerView
//Intent intent = new Intent(MainActivity.this, YesActivity.class);
//intent.putExtra("word", user + ", вам передали: " + gift);
//startActivity(intent);
i++;
counter++;
}
public void onClickNo(View view) {
Toast.makeText(this, "Size is " + worldList.size(), Toast.LENGTH_SHORT).show();
//recyclerItems.add(new RecyclerItems(worldList.get(i)));
i = 0;
counter = 0;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.yes:
recyclerItems.add(new RecyclerItems(worldList.get(i)));
intent = new Intent(MainActivity.this, YesActivity.class);
startActivity(intent);
break;
case R.id.no:
intent = new Intent(MainActivity.this, NoActivity.class);
startActivity(intent);
break;
case R.id.about:
Toast.makeText(this, "By SaturnPRO", Toast.LENGTH_SHORT).show();
//openDialogAbout
break;
}
return true;
}
}
My Second Activity
public class YesActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
ArrayList<RecyclerItems> yesWordList;
private WordDataBase wordDatabaseForYes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
yesWordList = new ArrayList<>();
recyclerView = findViewById(R.id.rvYes);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerViewAdapter(yesWordList);
layoutManager = new LinearLayoutManager(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(layoutManager);
}
}
Also i have an Adapter but i couldn't show it here.
How can i do it? enter code here Please help.
Send the word in intent extras:
case R.id.yes:
recyclerItems.add(new RecyclerItems(worldList.get(i)));
intent = new Intent(MainActivity.this, YesActivity.class);
intent.putExtra("key", worldList.get(i));
startActivity(intent);
break;
In your second activity:
String name = intent.getStringExtra("key");
You can make the wordList a static member. Then you can access it in your adapter.
I'm using the firebaseRecyclerAdaper on a fragment and i want to open an item from de populated list from firebase and send the data to a new fragment. Can u guys tell me please how can i start the FragmentDetail from the onCLickListener on FragmentAllPosts and pass the PostModel parameter to it?
Main Activity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "TAG" ;
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference , postsRef;
private StorageReference profileImgRef;
private CircleImageView circleImageViewMain;
private TextView nameEdtTxt, emailEdtTxt;
Fragment fragment= null;
private RecyclerView recyclerView;
private FloatingActionButton fab;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
progressDialog= new ProgressDialog(this);
progressDialog.setMessage("Please wait!");
progressDialog.setCanceledOnTouchOutside(false);
//Initialize Firebase modules
firebaseAuth=FirebaseAuth.getInstance();
databaseReference= FirebaseDatabase.getInstance().getReference().child("users");
postsRef= FirebaseDatabase.getInstance().getReference().child("posts");
profileImgRef= FirebaseStorage.getInstance().getReference();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
circleImageViewMain = (CircleImageView) header.findViewById(R.id.circleImageHeader);
nameEdtTxt = (TextView) header.findViewById(R.id.txtName);
emailEdtTxt =(TextView)header.findViewById(R.id.txtEmail);
if (firebaseAuth.getCurrentUser()!=null){
LoadUserData(CheckUserDataBase());
}
ViewPager vp_pages= (ViewPager) findViewById(R.id.vp_pages);
PagerAdapter pagerAdapter=new FragmentAdapter(getSupportFragmentManager());
vp_pages.setAdapter(pagerAdapter);
TabLayout tbl_pages= (TabLayout) findViewById(R.id.tabs);
tbl_pages.setupWithViewPager(vp_pages);
tbl_pages.setTabTextColors(ColorStateList.valueOf(Color.parseColor("#FFFFFF")));
tbl_pages.setHorizontalScrollBarEnabled(true);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fragment= new AddPostFrag();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction= fragmentManager.beginTransaction();
transaction.add(R.id.add_post_container, fragment).commit();
fab.hide();
}
});
}
class FragmentAdapter extends FragmentPagerAdapter {
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new FragmentAllPosts();
case 1:
return new FragmentLosts();
case 2:
return new FragmentFounds();
}
return null;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
//
//Your tab titles
//
case 0:return "All";
case 1:return "Losts";
case 2: return "Founds";
default:return null;
}
}
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser user= firebaseAuth.getCurrentUser();
if (user == null){
SendUserToLogin();
} else {
CheckUserDataBase();
}
}
public static class PostsViewHolder extends RecyclerView.ViewHolder {
CircleImageView circleImageView;
ImageView imageView;
TextView authorNdate, location, description;
public PostsViewHolder(#NonNull View itemView) {
super(itemView);
circleImageView= itemView.findViewById(R.id.circleImageView_cv);
imageView= itemView.findViewById(R.id.imageView_cv);
authorNdate= itemView.findViewById(R.id.author_date_cv);
location = itemView.findViewById(R.id.location_cv);
description = itemView.findViewById(R.id.description_cv);
}
}
private void UpdateHome() {
}
private void LoadUserData(final String uid) {
try {
final File localFile =File.createTempFile("profile","png");
StorageReference filepath=profileImgRef.child(uid).child("profileImg/profile.png");
filepath.getFile(localFile)
.addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Picasso.get()
.load(localFile)
.placeholder(R.drawable.ic_account)
.into(circleImageViewMain);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this,
"Profile photo not found, please update your profile!",
Toast.LENGTH_SHORT).show();
SendUserToSetup();
}
});
} catch (IOException e) {
e.printStackTrace();
}
databaseReference.child(uid).child("userInfo").addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("name")){
String name = dataSnapshot.child("name").getValue().toString();
nameEdtTxt.setText(name);
String email = dataSnapshot.child("email").getValue().toString();
emailEdtTxt.setText(email);
} else {
Toast.makeText(MainActivity.this,
"Profile name does not exists, please update your profile",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);
}
#Override
protected void onStop() {
super.onStop();
}
private String CheckUserDataBase() {
final String userID =firebaseAuth.getCurrentUser().getUid();
databaseReference.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.child(userID).hasChild("userInfo")){
SendUserToSetup();
} else {
UpdateHome();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);
return userID;
}
private void SendUserToSetup() {
Intent i = new Intent(this,SetupActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
private void SendUserToLogin() {
Intent i = new Intent(this,LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (getSupportFragmentManager().getBackStackEntryCount() >0)
{
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
} else
{
super.onBackPressed();
}
fab.show();
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
switch (id){
case R.id.nav_home:
super.onResume();
if (fragment!=null){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction= fragmentManager.beginTransaction();
transaction.remove(fragment).commit();
fab.show();
}
break;
case R.id.nav_profile:
super.onPause();
break;
case R.id.nav_my_posts:
super.onPause();
break;
case R.id.nav_messeges:
super.onPause();
break;
case R.id.nav_settings:
super.onPause();
break;
case R.id.nav_logout:
SendUserToLogin();
firebaseAuth.signOut();
break;
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Fragment with the FirebaseRecyclerAdapter
public class FragmentAllPosts extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private DatabaseReference postsRef;
private Context context= getContext();
Fragment mFragment;
Bundle mBundle;
public FragmentAllPosts() {
// Required empty public constructor
}
public static FragmentAllPosts newInstance(String param1, String param2) {
FragmentAllPosts fragment = new FragmentAllPosts();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
private RecyclerView recyclerAllPosts;
private ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
progressDialog= new ProgressDialog(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_all_posts,container,false);
postsRef= FirebaseDatabase.getInstance().getReference().child("posts");
recyclerAllPosts= v.findViewById(R.id.recycler_all_posts);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerAllPosts.setLayoutManager(linearLayoutManager);
return v;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context=context;
}
#Override
public void onStart() {
super.onStart();
progressDialog.show();
FirebaseRecyclerOptions<PostsModel> options=
new FirebaseRecyclerOptions.Builder<PostsModel>()
.setQuery(postsRef,PostsModel.class)
.setLifecycleOwner(this)
.build();
FirebaseRecyclerAdapter<PostsModel,PostsViewHolder> adapter=
new FirebaseRecyclerAdapter<PostsModel, PostsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final PostsViewHolder holder, int position, #NonNull final PostsModel model) {
String processedTime= CalculateTime(model.getData());
Picasso.get().load(Uri.parse(model.getUserImg())).into(holder.circleImageView);
Picasso.get().load(Uri.parse(model.getImageUri())).into(holder.imageView);
holder.authorNdate.setText(model.getAuthor()+" updated "+processedTime);
holder.location.setText(model.getLocation());
holder.description.setText(model.getDescription());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment frag= new FragmentDetail();
getFragmentManager().beginTransaction().replace(R.id.add_post_container,frag)
.addToBackStack(null).commit();
}
});
}
#NonNull
#Override
public PostsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view= LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.card_view,viewGroup,false );
PostsViewHolder viewHolder= new PostsViewHolder(view);
return viewHolder;
}
};
recyclerAllPosts.setAdapter(adapter);
progressDialog.dismiss();
adapter.startListening();
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
public String CalculateTime(String inputTime){
String timeOut;
Calendar currentTime= Calendar.getInstance();
SimpleDateFormat dateFormat= new SimpleDateFormat(getString(R.string.date_format));
dateFormat.format(currentTime.getTime());
SimpleDateFormat postFormat= new SimpleDateFormat(getString(R.string.date_format));
Calendar postTime = Calendar.getInstance();
try {
Date datePost=postFormat.parse(inputTime);
postTime.setTime(datePost);
} catch (ParseException e) {
e.printStackTrace();
}
long timeCurrent= currentTime.getTimeInMillis();
long timePost = postTime.getTimeInMillis();
long diff= timeCurrent- timePost;
long minutes= diff/(60*1000);
long hours = diff/(60 * 60 * 1000);
long days = diff/(24 * 60 * 60 * 1000);
if (minutes<59 && minutes>1){
timeOut=Long.toString(minutes)+" mins ago";
} else if (minutes<1){
timeOut=" just now";
}else if (hours<24 && minutes>59){
timeOut=Long.toString(hours)+" hour(s) ago";
}else {
timeOut=Long.toString(days)+" day(s) ago";
}
return timeOut;
}
static class PostsViewHolder extends RecyclerView.ViewHolder {
CircleImageView circleImageView;
ImageView imageView;
TextView authorNdate, location, description;
public PostsViewHolder(#NonNull View itemView) {
super(itemView);
itemView.setTag(this);
circleImageView= itemView.findViewById(R.id.circleImageView_cv);
imageView= itemView.findViewById(R.id.imageView_cv);
authorNdate= itemView.findViewById(R.id.author_date_cv);
location = itemView.findViewById(R.id.location_cv);
description = itemView.findViewById(R.id.description_cv);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Detail Fragment:
public class FragmentDetail extends Fragment {
public FragmentDetail() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_detail, container, false);
}
}
I'd suggest a read on the documentation. Passing data between two activities should be done via interfaces.
As suggested by the official site
I am currently facing 2 problems, the spinner state is not saving and when I am on the InformationActivity the spinner is reset. I have used the information on other posts but it doesnt seem to help.
At the moment I cant use finish(); in my onBackPressed(); on InformationActivity because it goes back to the ScannerView as I am Implementing the ZXing library. How could I save the Spinner state and also stop the program from crashing onBackPressed when I am on HomeActivity.
Thanks.
HomeActivity:
public class HomeActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
private FirebaseAuth firebaseAuth;
private Button buttonLogout;
private ZXingScannerView scannerView;
private final int permission_code = 1;
String [] selectedProfile;
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
firebaseAuth = FirebaseAuth.getInstance();
if(firebaseAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(this, MainActivity.class));
}
FirebaseUser user = firebaseAuth.getCurrentUser();
if (savedInstanceState != null) {
spinner.setSelection(savedInstanceState.getInt("yourSpinner", 0));
// do this for each of your text views
}
else {
//android spinner to select profile
spinner = (Spinner) findViewById(R.id.spinnerProfiles);
adapter = ArrayAdapter.createFromResource(this, R.array.restrictions, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
}
//opens camera when button is pressed
public void scanBarcode(View view) {
//check if user given app camera permissions
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, permission_code);
}
//opens camera
scannerView = new ZXingScannerView(this);
scannerView.setResultHandler(new ZXingScannerResultHandler());
//stops camera and scannerview
setContentView(scannerView);
scannerView.startCamera();
}
//selects an item from the spinner and passes it to InformationActivity
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(getBaseContext(), item + " Selected", Toast.LENGTH_SHORT).show();
switch (position){
case 0:
selectedProfile = getResources().getStringArray(R.array.Wheat);
break;
case 1:
selectedProfile = getResources().getStringArray(R.array.Crustaceans);
break;
case 2:
selectedProfile = getResources().getStringArray(R.array.Eggs);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
//stops camera and outputs barcode result to a Toast
class ZXingScannerResultHandler implements ZXingScannerView.ResultHandler {
#Override
public void handleResult(Result result) {
String resultBarcode = result.getText();
Intent intent = new Intent(getApplicationContext(), InformationActivity.class);
intent.putExtra("BarcodeString", resultBarcode.toString());
intent.putExtra("ProfileArray", selectedProfile);
startActivity(intent);
scannerView.stopCamera();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == permission_code) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_LONG).show();
}
}
//go back to home after permissions accepted
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(intent);
scannerView.stopCamera();
}
//goes back to homepage when back button is pressed
#Override
public void onBackPressed() {
setContentView(R.layout.activity_home);
scannerView.stopCamera();
}
//stops the camera on pause
#Override
public void onPause(){
super.onPause();
scannerView.stopCamera();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("yourSpinner", spinner.getSelectedItemPosition());
}
}
InformationActivity:
public class InformationActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information);
TextView barcodeView = (TextView) findViewById(R.id.tvBarcode);
barcodeView.setText(getIntent().getExtras().getString("BarcodeString"));
TextView profileView = (TextView) findViewById(R.id.tvProfile);
String[] selectedProfile = getIntent().getStringArrayExtra("ProfileArray");
profileView.setText(selectedProfile[0]);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(intent);
}
}
To Save Spinner posotion in sharedpreference :
int userChoice = spinner.getSelectedItemPosition();
SharedPreferences sharedPref = getSharedPreferences("FileName",0);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putInt("userChoiceSpinner",usersChoice);
prefEditor.commit();
Get Data from sharedpreferences :
SharedPreferences sharedPref = getSharedPreferences("FileName",MODE_PRIVATE);
int spinnerValue = sharedPref.getInt("userChoiceSpinner",-1);
if(spinnerValue != -1) {
// set the selected value of the spinner
spinner.setSelection(spinnerValue);
}
Also look into this :
One Another Example to save : https://stackoverflow.com/a/29527936/8448886
SharedPreference Tutorial :https://www.journaldev.com/9412/android-shared-preferences-example-tutorial
when you select any item from spinner at that time get that selected item and store that position and after when you come back to activity load spinner first, compare that item with array items and get position of that item then set that position to spinner i think this way you get exact selection of that item into spinner.
I want to add an image from device to the app.
I will use solution of David Manpearl at this openImageIntent.
My code looks fine but when I run the app and select the image in the app, but the problem is the onActivityResult when I finish selecting the image. Please see my code and advise me on what I'm doing wrong. Thank for any suggestion.
Update Info: This Fragment is parent of another Fragment it's name "EventFragment" because I have use FragmentTabHost in EventFragment to display EventAdd class fragment and I have MainActivity it's a ActionBarActivity this is a main of activity when application started. When I click EventFragment menu from MainActivity it will go to EventFragment and EventAdd it's here in FragmentTabHost . Let's see the code:
MainActivity:
public class MainActivity extends ActionBarActivity implements
NavigationDrawerFragment.NavigationDrawerCallbacks {
public static String Username;
/**
* Fragment managing the behaviors, interactions and presentation of the
* navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in
* {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent myIntent = getIntent();
Username = myIntent.getStringExtra("username");
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.container,
PlaceholderFragment.newInstance(position + 1)).commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_sectionMain);
break;
case 2:
mTitle = getString(R.string.title_section1);
break;
case 3:
mTitle = getString(R.string.title_section2);
break;
case 4:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(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();
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 {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static Fragment newInstance(int sectionNumber) {
Fragment fragment = null;
switch(sectionNumber) {
default:
case 1:
fragment = new PlaceholderFragment();
break;
case 2:
fragment = new EventFragment();
break;
case 3:
//Fragment fragment = new MyFragment2();
break;
case 4:
//Fragment fragment = new MyFragment2();
break;
}
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(getArguments().getInt(
ARG_SECTION_NUMBER));
}
}
}
EventFragment:
public class EventFragment extends Fragment{
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
mTabHost = null;
}
private FragmentTabHost mTabHost;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
mTabHost = new FragmentTabHost(getActivity());
mTabHost.setup(getActivity(), getChildFragmentManager(), R.layout.fragment_event);
mTabHost.addTab(mTabHost.newTabSpec("Tab1").setIndicator("รายการแจ้งเหตุ"),
EventListView.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Tab2").setIndicator("แจ้งเรื่องร้องเรียน"),EventAdd.class,null);
return mTabHost;
}
public EventFragment() {
// TODO Auto-generated constructor stub
}
}
EventAdd Class Fragment:
public class EventAdd extends Fragment {
private ArrayList<HashMap<String, String>> EventTypeList = null;
private Spinner spinnerET;
private List<String> spinnerETArray;
private static final int SELECT_PICTURE_REQUEST_CODE = 0;
private ImageView imageView;
private Bitmap photo;
private Uri outputFileUri;
private Button clearbtn;
private Button AEbtn;
private EditText name;
private EditText detail;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
final View rootView = inflater.inflate(R.layout.fragment_event_add, container, false);
SetGet sl = new SetGet();
EventTypeList = sl.getArrayListET();
spinnerET=(Spinner) rootView.findViewById(R.id.spinnerType);
name = (EditText) rootView.findViewById(R.id.EditTextName);
detail = (EditText) rootView.findViewById(R.id.editTextdetail);
spinnerETArray = new ArrayList<String>();
imageView = (ImageView)rootView.findViewById(R.id.imageView1);
Button photoButton = (Button) rootView.findViewById(R.id.cam_btn);
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openImageIntent();
}
});
spinnerETArray.add("==เลือกประเภท==");
for (HashMap<String, String> map : EventTypeList){
for (Entry<String, String> mapEntry : map.entrySet())
{
if(mapEntry.getKey() == "event_type_name"){
spinnerETArray.add(mapEntry.getValue());
}
}
}
Log.d("spinnerETArray:",spinnerETArray.toString());
ArrayAdapter<String> adapter =new ArrayAdapter<String>(this.getContext(),android.R.layout.simple_spinner_item, spinnerETArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerET.setAdapter(adapter);
clearbtn = (Button) rootView.findViewById(R.id.Clearbtn);
clearbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clearInput();
}
});
AEbtn = (Button) rootView.findViewById(R.id.AEbtn);
AEbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent Mapint = new Intent(getActivity(), MapMarkPointActivity.class);
Mapint.putExtra("name", name.getText().toString());
Mapint.putExtra("detail", detail.getText().toString());
Mapint.putExtra("photo", photo);
String text = spinnerET.getSelectedItem().toString();
Integer typeId = null;
String CurrentText = "";
for (HashMap<String, String> map : EventTypeList){
for (Entry<String, String> mapEntry : map.entrySet())
{
if(mapEntry.getKey() == "event_type_name"){
CurrentText = mapEntry.getValue();
}else if(mapEntry.getKey() == "event_type_id" && CurrentText == text){
String id = mapEntry.getValue();
typeId = Integer.parseInt(id);
}
}
}
Mapint.putExtra("typeId", typeId);
startActivity(Mapint);
}
});
return rootView;
}
protected void clearInput() {
name.setText("");
detail.setText("");
spinnerET.setSelection(0);
photo = null;
imageView.setImageResource(R.drawable.ic_launcher);
}
private void openImageIntent(){
// Determine Uri of camera image to save.
final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "MyDir" + File.separator);
root.mkdirs();
final String fname = "img_"+ System.currentTimeMillis() + ".jpg";
final File sdImageMainDirectory = new File(root, fname);
outputFileUri = Uri.fromFile(sdImageMainDirectory);
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getContext().getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for(ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
try{
Log.d("startActivityForResult:","startActivityForResult");
getParentFragment().startActivityForResult(chooserIntent, SELECT_PICTURE_REQUEST_CODE);
}catch(Exception e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
Log.d("onActivityResult:","onActivityResult");
if (resultCode == Activity.RESULT_OK) {
Log.d("OK:","ok");
if (requestCode == SELECT_PICTURE_REQUEST_CODE) {
final boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
} else {
selectedImageUri = data == null ? null : data.getData();
}
Log.d("รูป:",selectedImageUri.toString());
try {
photo = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImageUri);
Log.d("รูป:",photo.toString());
imageView.setImageBitmap(photo);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}else{
Log.d("Error:",data.toString());
}
}
public EventAdd() {
super();
// TODO Auto-generated constructor stub
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
In your host activity (MainActivity.java) you need to do:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
}
I am having a issue, as my app is crashing instead of opening the fragments. I have a ListActivity, that takes you to another activity; and in that other activity, there are two fragments. The ListActivity is expecting a result from one of the fragments.
My code was working prior to adding the fragments! However the fragments are no longer showing up and the app closes...does anyone possibly know what my issue could be? And any advice on how to take this issue? I sincerely appreciate all and any help, thank you! My code is below.
The ListActivity.java:
public class LyricList extends ListActivity {
private static final int ACTIVITY_CREATE=0;
private static final int ACTIVITY_EDIT=1;
private static final int INSERT_ID = Menu.FIRST;
private static final int DELETE_ID = Menu.FIRST + 1;
private LyricsDbAdapter mDbHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lyriclist);
mDbHelper = new LyricsDbAdapter(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
}
private void fillData() {
Cursor lyricsCursor = mDbHelper.fetchAllLyrics();
startManagingCursor(lyricsCursor);
String[] from = new String[]{LyricsDbAdapter.KEY_TITLE};
int[] to = new int[]{R.id.text1};
SimpleCursorAdapter lyrics =
new SimpleCursorAdapter(this, R.layout.lyrics_row, lyricsCursor, from, to);
setListAdapter(lyrics);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_ID, 0, R.string.menu_insert);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case INSERT_ID:
createLyric();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
mDbHelper.deleteLyric(info.id);
fillData();
return true;
}
return super.onContextItemSelected(item);
}
private void createLyric() {
Intent i = new Intent(this, NextActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, NextActivity.class);
i.putExtra(LyricsDbAdapter.KEY_ROWID, id);
startActivityForResult(i, ACTIVITY_EDIT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}
}
The other activity class that should be opening via the listActivity:
public class NextActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab one = actionBar.newTab().setText("Lyric Editor");
Tab two = actionBar.newTab().setText("Loops");
one.setTabListener(new MyTabListener(new LyricEditorFragment()));
two.setTabListener(new MyTabListener(new LoopsFragment()));
actionBar.addTab(one);
actionBar.addTab(two);
}
public class MyTabListener implements TabListener{
Fragment fragment;
public MyTabListener(Fragment f){
fragment = f;
}
#Override
public void onTabReselected(Tab arg0, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab arg0, FragmentTransaction ft) {
// TODO Auto-generated method stub
ft.replace(R.id.frame1, fragment);
}
#Override
public void onTabUnselected(Tab arg0, FragmentTransaction ft) {
// TODO Auto-generated method stub
ft.remove(fragment);
}
}
}
Not sure if you want to see the fragment class, but here is this just incase:
public class LyricEditorFragment extends Fragment {
private EditText mTitleText;
private EditText mBodyText;
private Long mRowId;
private LyricsDbAdapter mDbHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new LyricsDbAdapter(getActivity());
mDbHelper.open();
mTitleText = (EditText) getView().findViewById(R.id.title);
mBodyText = (EditText) getView().findViewById(R.id.body);
Button confirmButton = (Button) getView().findViewById(R.id.confirm);
mRowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(LyricsDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getActivity().getIntent().getExtras();
mRowId = extras != null ? extras.getLong(LyricsDbAdapter.KEY_ROWID)
: null;
}
populateFields();
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
getActivity().setResult(Activity.RESULT_OK);
getActivity().finish();
}
});
}
private void populateFields() {
if (mRowId != null) {
Cursor lyric = mDbHelper.fetchLyric(mRowId);
getActivity().startManagingCursor(lyric);
mTitleText.setText(lyric.getString(
lyric.getColumnIndexOrThrow(LyricsDbAdapter.KEY_TITLE)));
mBodyText.setText(lyric.getString(
lyric.getColumnIndexOrThrow(LyricsDbAdapter.KEY_BODY)));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(LyricsDbAdapter.KEY_ROWID, mRowId);
}
#Override
public void onPause() {
super.onPause();
saveState();
}
#Override
public void onResume() {
super.onResume();
populateFields();
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
if (mRowId == null) {
long id = mDbHelper.createLyric(title, body);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateLyric(mRowId, title, body);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
//return super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.activity_lyriceditor, container, false);
return view;
}
}
The problem is that you are getting a View from the activity which will return null.. you need to create/inflate the view from the onCreateView..
click here and follow the steps on how to create and use a view from fragment..
Click Here