I have this activity
package com.padilla.jorge.proyecto_aplicaciones_moviles;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Calendar;
public class VerPerfil extends AppCompatActivity {
private String[] arraySpinner;
Intent i;
TextView Nombre_TextView;
TextView Email_TextView;
TextView Password_TextView;
TextView Puntos_TextView;
TextView getNombre;
TextView getEmail;
TextView getPassword;
TextView getPuntos;
ArrayList<TextView> textViewsVal;
ArrayList<TextView> textViewsName;
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference reference;
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ver_perfil);
Nombre_TextView=(TextView)findViewById(R.id.Nombre_textView);
Email_TextView=(TextView)findViewById(R.id.Email_TextView);
Password_TextView=(TextView)findViewById(R.id.Password_TextView);
Puntos_TextView=(TextView)findViewById(R.id.Puntos_TextView);
getNombre=(TextView)findViewById(R.id.Nombre_valor);
getEmail=(TextView)findViewById(R.id.Email_valor);
getPassword=(TextView)findViewById(R.id.Password_valor);
getPuntos=(TextView)findViewById(R.id.Puntos_valor);
textViewsName = new ArrayList<TextView>();
textViewsName.add(Nombre_TextView);
textViewsName.add(Email_TextView);
textViewsName.add(Password_TextView);
textViewsName.add(Puntos_TextView);
textViewsVal = new ArrayList<TextView>();
textViewsVal.add(getNombre);
textViewsVal.add(getEmail);
textViewsVal.add(getPassword);
textViewsVal.add(getPuntos);
Intent name_intent=this.getIntent();
final String name=name_intent.getExtras().getString("name");
reference = database.getReference(name).child("Perfil");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//rutina.setText(dataSnapshot.getKey());
int i = 0;
Log.d("number of childs",""+dataSnapshot.getChildrenCount());
for (DataSnapshot child : dataSnapshot.getChildren()) {
if (i < 10) {
textViewsName.get(i).setText(child.getKey());
textViewsVal.get(i).setText(child.getValue().toString());
Log.d("User key", child.getKey());
Log.d("User ref", child.getRef().toString());
Log.d("User val", child.getValue().toString());
i++;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
and i was wondering if there's a simple way to convert it to a fragment? Any help would be appreciated.
The reason i want to do this is because i want to implement a navigation drawer menu and i've seen that you have to use fragments (i know there's a way to do it with classes but it's way more complicated) and i already have this class so i would like to reuse it instead of creating a new fragment from scratch.
Let's try this:
Extend fragment and refactor MyActivityClass to MyFragmentClass
original: public class MyActivityClass extends AppCompatActivity
converted: public class MyFragmentClass extends Fragment
Create factory method and add all the values that you get from getIntent().getExtra() as parameters for the method
original: String name=getIntent.getExtras().getString("name");
converted:
This
public static MyFragmentClass newInstance(String name){
MyFragmentClass fragment = new MyActivity();
Bundle args = new Bundle();
args.putString(KEY_NAME, name);
fragment.setArguments(args);
return fragment;
}
and this,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
name = getArguments().getString(KEY_NAME);
}
}
override method onCreateView() and inflate your layout
original: setContentView(R.layout.activity_layout);
converted:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_layout, container, false);
return view;
}
place all the findViewById(...); statement in onCreateView() and rename to view.findViewById(...) and other code which does not need the activity to run.
override onActivityCreated() and place all the code that needs Activty in here.
remove code already converted to fragment
It's not the perfect answer but should help.
Try this:
Create fragment
Move that code and layout to fragment instead
Now you have a reusable fragment
Add the fragment in your activity or navigation drawer or wherever you like
Related
this is my first android project.
I am making a login and register page for a game i am making, and i'm trying to figure the login/register stuff. my project so far consists of MainActivity.java, LoginFragment and a RegisterFragment.
my question is after declaring the username, password, loginbtn variables how should my Intent intent declaration look like?
note aside, my mainActivity consists of a viewPager which just lets me slide through the login and register pages. but i will supply the code below
mainActivity.java
package com.example.my_app_2;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.app.Dialog;
import android.content.Intent;
import android.app.Activity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button btnSignIn, btnSignUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//create instance of SQLite Database
ViewPager viewPager = findViewById(R.id.viewPager);
AuthenticationPagerAdapter pagerAdapter = new AuthenticationPagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragmet(new LoginFragment());
pagerAdapter.addFragmet(new RegisterFragment());
viewPager.setAdapter(pagerAdapter);
}
static class AuthenticationPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> fragmentList = new ArrayList<>();
public AuthenticationPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
return fragmentList.get(i);
}
#Override
public int getCount() {
return fragmentList.size();
}
void addFragmet(Fragment fragment) {
fragmentList.add(fragment);
}
}
}
LoginFragment:
package com.example.my_app_2;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
/**
* A simple {#link Fragment} subclass.
*/
public class LoginFragment extends Fragment {
EditText username, password;
Button loginbtn;
public LoginFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_login, container,false);
username = v.findViewById(R.id.username);
password = v.findViewById(R.id.password);
loginbtn = v.findViewById(R.id.loginbtn);
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String usernameValue = username.getText().toString();
String passwordValue = password.getText().toString();
// i assume the Intent intent goes here, but i have no idea what arugments/parameters pass in the new Intent() part of it
}
});
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_login, container, false);
}
}
and same goes with the registerFragment
package com.example.my_app_2;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
/**
* A simple {#link Fragment} subclass.
*/
public class RegisterFragment extends Fragment {
EditText username, password, email;
Button signupbtn;
public RegisterFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_register, container,false);
username = v.findViewById(R.id.username);
password = v.findViewById(R.id.password);
email = v.findViewById(R.id.email);
signupbtn = v.findViewById(R.id.signupbtn);
signupbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String usernameValue = username.getText().toString();
String passwordValue = password.getText().toString();
String emailValue = email.getText().toString();
Intent intent = new Intent();
}
});
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_register, container, false);
}
}
what i have tried to do...
what i am trying to do is just take the username and password and store them in sharedPreferences.
thanks in advance, i apoligize for the silliness of the question but any help would be appreciated!
i have tried Intent intent = new Intent(this, RegisterFragment); // ??????
honestly im kinda clueless lol xd
(RegisterFragment.this); // ???????
I am making an app in which you keep track of your grades. Currently, I am working on a system for adding subjects. So, I want to display the subjects on a RecyclerView. So, I have an activity for adding the subject, which gets the name of the subject, stores it in a arraylist, sends the arraylist to the RecyclerView Adapter and displays the Subject name as an item.
The issue I am facing is that, I can't seem to transfer the value of the arraylist with an Intent. I get an error in the Adapter, specifically when I try to use a command called getIntent() .
Here is the code in RecyclerAdapter.java file:
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class recyclerAdapter extends RecyclerView.Adapter<recyclerAdapter.MyViewHolder> {
private ArrayList<String> subjectList;
public recyclerAdapter(ArrayList<String> subjectList){
this.subjectList = subjectList;
}
public class MyViewHolder extends RecyclerView.ViewHolder{
private TextView subjectName;
public MyViewHolder(final View view){
super(view);
subjectName = view.findViewById(R.id.txtSubjectName);
Intent addedSubject = getIntent(); //I get the error in this line, specifically getIntent()
subjectList = addedSubject.getStringArrayListExtra("Subject");
}
}
#NonNull
#Override
public recyclerAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View subjectView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_subjects, parent, false);
return new MyViewHolder(subjectView);
}
#Override
public void onBindViewHolder(#NonNull recyclerAdapter.MyViewHolder holder, int position) {
String subject = subjectList.get(position);
holder.subjectName.setText(subject);
}
#Override
public int getItemCount() {
return subjectList.size();
}
}
Here's the code in the activity in which you add the subject name:
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
public class addSubject extends AppCompatActivity {
private ArrayList<Subjects> subjectList;
private boolean subjectAdded = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getSupportActionBar().hide();
setContentView(R.layout.activity_add_subject);
subjectList = new ArrayList<>();
}
public void addSubject (View view){
EditText editSubjectName = findViewById(R.id.editSubjectName);
Intent backToMain = new Intent(this, MainActivity.class);
Intent toAdapter = new Intent(this, recyclerAdapter.class);
String subjectName = editSubjectName.getText().toString();
if (!subjectName.equals("")){
subjectList.add(new Subjects(subjectName));
toAdapter.putExtra("Subject", subjectList);
startActivity(backToMain);
}
else
Toast.makeText(getApplicationContext(),"Invalid values, try again",Toast.LENGTH_SHORT).show();
}
Why not reinitialize the recyclerView with a new set of subjectList.
`binding.rv.adapter=recyclerAdapter(//new subject list)
Since it is an Activity specific method it's not available inside the adapter.
However if your goal is to update data there are more elegant solutions to this like notifyDataSet() or using methods inside the adapter.
However if you have a complicated implementation this answer on Passing data from an activity back to recyclerview adapter might help.
Ps: Make your class names capital. it's a coding norm
I'm trying to pass images from a Realtime Database Recycler View to another activity.
First activity
package com.khumomashapa.notes.activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.khumomashapa.notes.R;
import com.khumomashapa.notes.adapter.RecyclerAdapter;
import com.khumomashapa.notes.Messages;
import com.khumomashapa.notes.interfaces.RecyclerTouchListener;
import java.util.ArrayList;
public class StoreActivity extends AppCompatActivity {
// Widget
RecyclerView recyclerView;
//Firebase
private DatabaseReference mref;
// Variable
private ArrayList<Messages> messagesList;
private RecyclerAdapter recyclerAdapter;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_store);
recyclerView = findViewById(R.id.products_view);
GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext()
,recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
Intent intent = new Intent(getBaseContext(), PreviewActivity.class);
intent.putExtra("images", position);
startActivity(intent);
Messages messages = messagesList.get(position);
Toast.makeText(StoreActivity.this, "You have selected: "+ messages.getTitle(), Toast.LENGTH_SHORT).show();
}
#Override
public void onLongClick(View view, int position) {
}
#Override
public void onButtonClicks(View view, int position) {
}
})
);
// Firebase
mref = FirebaseDatabase.getInstance().getReference();
// Arraylist
messagesList = new ArrayList<Messages>();
// Clear arraylist
ClearAll();
// Get data Method
GetDataFromFirebase();
}
private void GetDataFromFirebase(){
Query query = mref.child("Wallpapers");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ClearAll();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Messages messages = new Messages();
messages.setImage(snapshot.child("image").getValue().toString());
messages.setTitle(snapshot.child("title").getValue().toString());
messagesList.add(messages);
}
recyclerAdapter = new RecyclerAdapter(getApplicationContext(), messagesList);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void ClearAll(){
if(messagesList != null){
messagesList.clear();
if (recyclerAdapter !=null){
recyclerAdapter.notifyDataSetChanged();
}
}
messagesList = new ArrayList<Messages>();
}
}
This is the first activity layout
The activity I want the images to be displayed in.
package com.khumomashapa.notes.activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.khumomashapa.notes.R;
import com.squareup.picasso.Picasso;
public class PreviewActivity extends AppCompatActivity {
private ImageView preview;
Button purchaseBtn;
Button downloadBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preview);
preview = findViewById(R.id.ImagePreview);
purchaseBtn = findViewById(R.id.PurchaseBtn);
downloadBtn = findViewById(R.id.DownloadBtn);
String preview = getIntent().getStringExtra("images");
}
}
This is the second activities layout
As you can see there's no image showing up in the imageview.
This code does work. It does take the user to another activity, but it doesn't show the image that was clicked in the first activity and as you can see I have more than one image I want to show. The image that was clicked must be shown in the next activity.
So in short what I want to happen is:
Someone clicks an image e.g. Abduction, Blue Cinema etc.
Then the user is taken to another activity and is shown the image they clicked(Abduction or Blue Cinema etc).
Sorry if I sound redundant, but I've been stuck on this for awhile and the tutorials/posts I read before didn't help, because they don't use code that works with Firebase Realtime Database.
I want to build an app by which I can generate bussiness card. So I use navigaion drawer. For navigating menus I use fragment class for each of the menus and corresponding XML layout. In one of the layout I want to show my card view inside recyclerview.
MycardFragment.java
(This is the fragment class where I want show recyclerview)
package com.example.look.np.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.example.look.np.R;
import com.example.look.np.models.Template;
import com.example.look.np.utils.FirebaseMethod;
import com.example.look.np.utils.RecyclerviewAdapter;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class MyCardFragment extends Fragment {
private static final String TAG = "MyCardFragment";
private Context mContext;
private RecyclerView recyclerView;
FirebaseDatabase database;
DatabaseReference myRef ;
List<Template> listdata;
public MyCardFragment() {
// Required empty public constructor
}
//i tried this section but it gimes me error
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext=context;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mycards,container,false);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("template");
// Initialize Template Model Class
Template template = new Template();
// ...
// Lookup the Recycler view in fragment layout
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
// Attach the adapter to the recyclerview to populate items
RecyclerviewAdapter adapter = new RecyclerviewAdapter(template,inflater.getContext());//>>>This is the error i'm facig
// Set layout manager to position the items
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
listdata = new ArrayList<Template>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.child("template").getChildren()){
Template value = dataSnapshot1.getValue(Template.class);
Template fire = new Template();
String name = value.getP_name();
String desig = value.getP_designation();
String email = value.getP_email();
String phone = value.getP_phone();
String address = value.getC_address();
String c_name = value.getC_name();
fire.setP_name(name);
fire.setP_designation(desig);
fire.setP_email(email);
fire.setP_phone(phone);
fire.setC_name(c_name);
fire.setC_address(address);
listdata.add(fire);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Failed to read value
Log.w("Hello", "Failed to read value.", databaseError.toException());
}
});
return view;
}
#Override
public void onStart() {
super.onStart();
}
}
I aslo created an adapter for recycler view, when I want to set the adapter to the fragment class it shows error. It takes context and List. For context I add getActivity() bMycardFragment.java
(This is the fragment class where I want show recyclerview)
package com.example.look.np.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.example.look.np.R;
import com.example.look.np.models.Template;
import com.example.look.np.utils.FirebaseMethod;
import com.example.look.np.utils.RecyclerviewAdapter;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class MyCardFragment extends Fragment {
private static final String TAG = "MyCardFragment";
private Context mContext;
private RecyclerView recyclerView;
FirebaseDatabase database;
DatabaseReference myRef ;
List<Template> listdata;
public MyCardFragment() {
// Required empty public constructor
}
//i tried this section but it gimes me error
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext=context;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mycards,container,false);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("template");
// Initialize Template Model Class
Template template = new Template();
// ...
// Lookup the Recycler view in fragment layout
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
// Attach the adapter to the recyclerview to populate items
RecyclerviewAdapter adapter = new RecyclerviewAdapter(template,inflater.getContext());//>>>This is the error i'm facig
// Set layout manager to position the items
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
listdata = new ArrayList<Template>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.child("template").getChildren()){
Template value = dataSnapshot1.getValue(Template.class);
Template fire = new Template();
String name = value.getP_name();
String desig = value.getP_designation();
String email = value.getP_email();
String phone = value.getP_phone();
String address = value.getC_address();
String c_name = value.getC_name();
fire.setP_name(name);
fire.setP_designation(desig);
fire.setP_email(email);
fire.setP_phone(phone);
fire.setC_name(c_name);
fire.setC_address(address);
listdata.add(fire);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Failed to read value
Log.w("Hello", "Failed to read value.", databaseError.toException());
}
});
return view;
}
#Override
public void onStart() {
super.onStart();
}
}
MycardFragment.java
(This is the fragment class where I want show recyclerview)
package com.example.look.np.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.example.look.np.R;
import com.example.look.np.models.Template;
import com.example.look.np.utils.FirebaseMethod;
import com.example.look.np.utils.RecyclerviewAdapter;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class MyCardFragment extends Fragment {
private static final String TAG = "MyCardFragment";
private Context mContext;
private RecyclerView recyclerView;
FirebaseDatabase database;
DatabaseReference myRef ;
List<Template> listdata;
public MyCardFragment() {
// Required empty public constructor
}
//i tried this section but it gimes me error
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext=context;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mycards,container,false);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("template");
// Initialize Template Model Class
Template template = new Template();
// ...
// Lookup the Recycler view in fragment layout
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
// Attach the adapter to the recyclerview to populate items
RecyclerviewAdapter adapter = new RecyclerviewAdapter(template,inflater.getContext());//>>>This is the error i'm facig
// Set layout manager to position the items
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
listdata = new ArrayList<Template>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.child("template").getChildren()){
Template value = dataSnapshot1.getValue(Template.class);
Template fire = new Template();
String name = value.getP_name();
String desig = value.getP_designation();
String email = value.getP_email();
String phone = value.getP_phone();
String address = value.getC_address();
String c_name = value.getC_name();
fire.setP_name(name);
fire.setP_designation(desig);
fire.setP_email(email);
fire.setP_phone(phone);
fire.setC_name(c_name);
fire.setC_address(address);
listdata.add(fire);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Failed to read value
Log.w("Hello", "Failed to read value.", databaseError.toException());
}
});
return view;
}
#Override
public void onStart() {
super.onStart();
}
}
I have an adapter class which takes context and List of items. Now I want to set my adapter in a fragment by passing context (getActivity() and List but it shows me error
I tried getActivity() but it show me error
i also tried this
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext=context;
}
//This is adapter class for my Recyclerview
RecyclerAdater.java
package com.example.look.np.utils;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.look.np.R;
import com.example.look.np.models.Template;
import java.util.List;
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyHolder>{
// ... constructor and member variables
// Usually involves inflating a layout from XML and returning the holder
List<Template> listdata;
Context context;
public RecyclerviewAdapter(List<Template> listdata, Context context) {
this.listdata = listdata;
this.context = context;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Inflate the custom layout
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview,parent,false);
// Return a new holder instance
MyHolder myHolder = new MyHolder(view);
return myHolder;
}
public void onBindViewHolder(MyHolder holder, int position) {
Template data = listdata.get(position);
holder.pname.setText(data.getP_name());
holder.pdesignation.setText(data.getP_designation());
holder.pemail.setText(data.getP_email());
holder.pphone.setText(data.getP_phone());
holder.cname.setText(data.getC_name());
holder.caddress.setText(data.getC_address());
}
#Override
public int getItemCount() {
//return listdata.size();
int arr = 0;
try{
if(listdata.size()==0){
arr = 0;
}
else{
arr=listdata.size();
}
}catch (Exception e){
e.printStackTrace();
}
return arr;
}
class MyHolder extends RecyclerView.ViewHolder{
// Your holder should contain a member variable
// for any view that will be set as you render a row
TextView pname,caddress,pemail,pdesignation,pphone,cname;
// We also create a constructor that accepts the entire item row
// and does the view lookups to find each subview
public MyHolder(View itemView) {
// Stores the itemView in a public final member variable that can be used
// to access the context from any ViewHolder instance.
super(itemView);
pname = (TextView) itemView.findViewById(R.id.txt_personName);
caddress = (TextView) itemView.findViewById(R.id.txt_address);
pemail = (TextView) itemView.findViewById(R.id.txt_email);
pdesignation = (TextView) itemView.findViewById(R.id.txt_designation);
pphone = (TextView) itemView.findViewById(R.id.txt_phone);
cname = (TextView) itemView.findViewById(R.id.txt_companyName);
}
}
}
Point to be noted, don't forget to set layoutManager to recyclerview and to set adapter.
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL
recyclerview.setLayoutManager(layoutManager);
recyclerview.setHasFixedSize(true);
recyclerviewAdapter adapter = new recyclerviewAdapterAdapter(listdata,getActivity());
recyclerview.setAdapter(adapter);
Another thing to notice in your code is:
There is network call (Which run in background) in oncreateView(). Before it gives result, the return view; is getting called.
This means the view is not updated while on background job is going.
This can be resolved by calling separate method like setRecyclerView() from onCreateView() method. After getting result from background operation you can set your recyclerview as mentioned above.
Don't forget to call the adapter.notifydatasetchanged() method.
I have made this app where in one particular activity i have a all the items listed in a list view. when you click the list item it goes to another activity where similar thing is happening. after that i was the clicked list items to be converted into a strings and transported into a 3rd activity where i can display those.
when i try to display them this shows in the text view where the clicked text item should have appeared:
this is code for the first activity:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.internal.Objects;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class TicketCategory extends AppCompatActivity {
public static String Category;
public String getCategory() {
return Category;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ticket_category);
populateTicketCategoryList();
final ListView listView = (ListView) findViewById(R.id.lvTicketCategory);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i == 0) {
Category = listView.getItemAtPosition(i).toString();
Intent intent = new Intent(TicketCategory.this, Subcategory.class);
startActivity(intent);
}
}
});
}
private void populateTicketCategoryList()
{
ArrayList<CompTicketCategory> arrayOfTicket = CompTicketCategory.getTicket();
CompTicketCategoryAdapter adapter = new CompTicketCategoryAdapter(this, arrayOfTicket);
ListView listView = (ListView) findViewById(R.id.lvTicketCategory);
listView.setAdapter(adapter);
}
}
the code for the second activity is:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class Subcategory extends AppCompatActivity {
public String Category;
public static String Subcat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subcategory);
populateSubcategoryList();
final ListView listView = (ListView) findViewById(R.id.lvSubcategory);
ArrayAdapter arrayAdapter = new ArrayAdapter<String>(Subcategory.this, android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Subcat = listView.getItemAtPosition(i).toString();
Intent intent = new Intent(Subcategory.this, SubmitTicket.class);
startActivity(intent);
}
});
and this is the code for the activity where both of the clicked items should be displayed:
public class SubmitTicket extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_submit_ticket);
Spinner spinner = (Spinner) findViewById(R.id.spinner_priority);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.priority_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final Button butt = findViewById(R.id.submit);
butt.setOnClickListener(new View.OnClickListener()
{
public void onClick (View view){
Toast.makeText(getApplicationContext(), "The ticket has been submitted", Toast.LENGTH_SHORT).show();
}
});
TextView textView = (TextView)findViewById(R.id.Category_submit_report);
textView.setText(TicketCategory.Category);
TextView tv = (TextView)findViewById(R.id.Subcategory_submit_report);
tv.setText(Subcategory.Subcat);
}
Please help me. i would appreciate any output. thanks!
UPDATE:
after trying
CompTicketCategory model = listView.getItemAtPosition(i);
Category=model.Category; // your Category variable
Category=model.getCategory();
this error is shown;
screenshot
You can use Intent Extra Feature.
In the First Activity,
Intent intent = new Intent(Subcategory.this, SubmitTicket.class);
switch1.putExtra("deviceID", listView.getItemAtPosition(i).toString(););
startActivity(intent);
Then Next activity recall them,
Intent intent = getIntent();
String data = intent.getStringExtra("data");
Try this in your TicketCategory actvity
Use this:
CompSubcategory model = listView.getItemAtPosition(i);
Category=model.Category; // your Category variable
Category=model.getCategory(); // or use getter setter method
Instead of this:
Category = listView.getItemAtPosition(i).toString();