firebase recycle view is not showing - android

I'm trying to read a list form a fire base in a recycle viewer, but it's not showing it to me.
this addfood.java - it's the class which i will show the blog flow in it:
package com.example.median1.sora;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.MenuView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.firebase.client.Firebase;
import com.firebase.client.core.Context;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
import org.w3c.dom.Text;
public class addfood extends AppCompatActivity {
private RecyclerView mBlogList;
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addfood);
mDatabase=FirebaseDatabase.getInstance().getReference("Blog");
mBlogList=(RecyclerView)findViewById(R.id.blog_list);
mBlogList.setHasFixedSize(true);
mBlogList.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Blog1,BlogViewHolder> firebaseRecyclerAdapter1=new FirebaseRecyclerAdapter<Blog1, BlogViewHolder>(
Blog1.class,
R.layout.blog_row,
BlogViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(BlogViewHolder viewHolder, Blog1 model, int position) {
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
}
};
mBlogList.setAdapter(firebaseRecyclerAdapter1);
}
public static class BlogViewHolder extends RecyclerView.ViewHolder{
View mView;
public BlogViewHolder(View itemView) {
super(itemView);
mView=itemView;
}
public void setTitle(String title){
TextView post_title=(TextView)mView.findViewById(R.id.post_title1);
post_title.setText(title);
}
public void setDesc(String desc){
TextView post_desc=(TextView)mView.findViewById(R.id.post_desc1);
post_desc.setText(desc);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.action_add){
Intent u=new Intent(addfood.this,potedfood.class);
startActivity(u);
}
return super.onOptionsItemSelected(item);
}
}
this is blog1.java this is the:
package com.example.median1.sora;
/**
* Created by median1 on 9/23/2017.
*/
public class Blog1 {
private String title;
private String desc;
private String image;
public Blog1(){
}
public Blog1(String title, String desc, String image) {
this.title = title;
this.desc = desc;
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
addfood.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.median1.sora.addfood">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/blog_list"></android.support.v7.widget.RecyclerView>
</android.support.constraint.ConstraintLayout>
blog_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/post_image1"
android:src="#mipmap/add_btn"
android:scaleType="centerCrop"
android:adjustViewBounds="true"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/post_title1"
android:hint="name"
android:padding="10dp"
android:textSize="16dp"
android:textStyle="bold"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/post_desc1"
android:hint="price"
android:padding="10dp"
android:textSize="16dp"
android:textStyle="bold"/>
</LinearLayout>
</LinearLayout>

i had this same issue but then i saw this solution it turns out the adapter needs to start listening and it has to be made global
To solve this, first make your adapter variable global:
private FirebaseRecyclerAdapter<UserInformation, EmployeeViewHolder> adapter;
Then you need to add the following lines of code in your onStart() and onStop() methods:
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
if(adapter != null) {
adapter.stopListening();
}
}
Because the adapter uses a listener to check for database changes, in order to make it work, you need to start listening first. And when you close the application, you need to stop listening.

Related

firebase recycler view crashing on scrolling down

Hii I am trying to read data from firebase database and storage to Firebase recycler everything is working fine till I am scrolling the Recycler view down then app is crashing here is my code
MODEL CLASS
package com.example.ace.park;
public class model {
public String name,num,type,sno;
public model(String name, String num, String type, String sno) {
this.name = name;
this.num = num;
this.type = type;
this.sno = sno;
}
public model() {
}
}
Here is JAVA CLASS
package com.example.ace.park;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class dis extends AppCompatActivity {
NavigationView navigationView;
TextView textView;
Intent intent;
FirebaseRecyclerAdapter<model, displayAdapter> adapter;
FirebaseRecyclerOptions<model> options;
RecyclerView recyclerView;
DatabaseReference mDatabase,query;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dis);
recyclerView = findViewById(R.id.myRecView);
mDatabase = FirebaseDatabase.getInstance().getReference().child("parkings");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
query = FirebaseDatabase.getInstance().getReference().child("parkings");
options = new FirebaseRecyclerOptions.Builder<model>()
.setQuery(query, model.class)
.build();
adapter = new FirebaseRecyclerAdapter<model, displayAdapter>(
options) {
#Override
public displayAdapter onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler, parent, false);
return new displayAdapter(v);
}
#Override
protected void onBindViewHolder(displayAdapter holder, final int position, final model current) {
holder.setName(current.name);
holder.setTotal(current.num);
holder.setType(current.type);
holder.setImage(getApplicationContext(),current.sno,current.sno);
holder.mview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(dis.this, ""+position, Toast.LENGTH_SHORT).show();
}
});
}
};
//Populate Item into Adapter
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
Here is Adapter
package com.example.ace.park;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FileDownloadTask;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import java.io.File;
import java.io.IOException;
public class displayAdapter extends RecyclerView.ViewHolder {
public View mview;
public displayAdapter(View itemView) {
super(itemView);
mview = itemView;
}
public void setName(String name){
TextView recName = mview.findViewById(R.id.recyclerName);
recName.setText(name);
}
public void setTotal(String title){
TextView t = mview.findViewById(R.id.recyclerTotal);
t.setText(title);
}
public void setType(String type){
TextView t = mview.findViewById(R.id.recyclerType);
t.setText(type);
}
public void setImage(Context ctx, String image,String user){
final ImageView iv = mview.findViewById(R.id.recyclerImg);
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageReference = storage.getReference().child("Parkings"+"/"+image);
try {
final File localFile = File.createTempFile("images", "jpg");
storageReference.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Bitmap bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath());
iv.setImageBitmap(bitmap);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
} catch (IOException e ) {
Toast.makeText(ctx, "Error in Adapter", Toast.LENGTH_SHORT).show();
}
}
}
This is recycler layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
app:cardCornerRadius="10dp"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerName"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:textColor="#212020"
android:textSize="30sp"
android:text="#string/name_of_place"
/>
<ImageView
android:layout_width="300dp"
android:layout_marginTop="30dp"
android:layout_height="230dp"
android:scaleType="centerCrop"
android:paddingLeft="10dp"
android:layout_gravity="center"
android:paddingRight="10dp"
android:id="#+id/recyclerImg"
android:contentDescription="#string/img"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:textColor="#615f5f"
android:textSize="18sp"
android:id="#+id/recyclerTotal"
android:text="#string/tsp"
/>
<TextView
android:layout_width="match_parent"
android:layout_marginTop="5dp"
android:text="#string/type"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:id="#+id/recyclerType"
android:layout_height="25dp"
android:textSize="18sp"
android:layout_marginBottom="5dp"
/>
</LinearLayout>
</android.support.v7.widget.CardView>
Logcat is giving his error
11-21 20:37:32.885 9681-9681/com.example.ace.park E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ace.park, PID: 9681
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Long to type com.example.ace.park.model
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database##16.0.5:423)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database##16.0.5:214)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database##16.0.5:79)
at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database##16.0.5:212)
at com.firebase.ui.database.ClassSnapshotParser.parseSnapshot(ClassSnapshotParser.java:29)
at com.firebase.ui.database.ClassSnapshotParser.parseSnapshot(ClassSnapshotParser.java:15)
at com.firebase.ui.common.BaseCachingSnapshotParser.parseSnapshot(BaseCachingSnapshotParser.java:35)
at com.firebase.ui.common.BaseObservableSnapshotArray.get(BaseObservableSnapshotArray.java:52)
at com.firebase.ui.database.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:106)
at com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:122)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6673)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6714)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5647)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5913)
at android.support.v7.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:285)
at android.support.v7.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:342)
at android.support.v7.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:358)
at android.support.v7.widget.GapWorker.prefetch(GapWorker.java:365)
at android.support.v7.widget.GapWorker.run(GapWorker.java:396)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
this is image of database structure

How to restrict the duplicate entries in the Firebase Database

In my app my user is entering the category and that category is stored in the FirebseDB. After storing the value in the DB the user can view the inserted value in the Spinner.
At this point all works fine.
I want user to enter only unique value .so , if user wants to enter the value which is already there he should get a Toast.
Following is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.lenovo.baicactivitytest.MainActivity">
<Spinner
android:id="#+id/sp"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<Button
android:id="#+id/add_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="70dp"
android:text="Add" />
</RelativeLayout>
Following is my inputdialogue.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize"
android:orientation="vertical"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="50dp">
<android.support.design.widget.TextInputLayout
android:id="#+id/nameLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/nameEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:hint= "Name" />
</android.support.design.widget.TextInputLayout>
<Button android:id="#+id/saveBtn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save"
android:clickable="true"
android:background="#color/colorAccent"
android:layout_marginTop="40dp"
android:textColor="#android:color/white"/>
</LinearLayout>
</LinearLayout>
Spacecraft.java
package com.example.lenovo.baicactivitytest;
/**
* Created by LENOVO on 29-12-2017.
*/
public class Spacecraft {
String name;
public Spacecraft() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
FirebaseHelper
package com.example.lenovo.baicactivitytest;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseException;
import com.google.firebase.database.DatabaseReference;
import java.util.ArrayList;
/**
* Created by LENOVO on 29-12-2017.
*/
public class FirebaseHelper {
DatabaseReference db;
Boolean saved = null;
public FirebaseHelper(DatabaseReference db) {
this.db = db;
}
//SAVE
public Boolean save(Spacecraft spacecraft)
{
if(spacecraft==null)
{
saved=false;
}else
{
try
{
db.child("Spacecraft").push().setValue(spacecraft);
saved=true;
}catch (DatabaseException e)
{
e.printStackTrace();
saved=false;
}
}
return saved;
}
//READ
public ArrayList<String> retrieve()
{
final ArrayList<String> spacecrafts=new ArrayList<>();
db.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot,spacecrafts);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetchData(dataSnapshot,spacecrafts);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return spacecrafts;
}
private void fetchData(DataSnapshot snapshot,ArrayList<String> spacecrafts)
{
spacecrafts.clear();
for (DataSnapshot ds:snapshot.getChildren())
{
String name=ds.getValue(Spacecraft.class).getName();
spacecrafts.add(name);
}
}
}
MainActivity.java
package com.example.lenovo.baicactivitytest;
import android.app.Dialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity extends AppCompatActivity {
DatabaseReference db;
FirebaseHelper helper;
private Button madd_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner sp =(Spinner) findViewById(R.id.sp);
//SETUP FB
db= FirebaseDatabase.getInstance().getReference();
helper = new FirebaseHelper(db);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,helper.retrieve());
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
madd_btn = (Button) findViewById(R.id.add_btn);
madd_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
displayInputDialog();
}
});
}
//DISPLAY INPUT DILAOG
private void displayInputDialog()
{
Dialog d=new Dialog(this);
d.setTitle("Firebase database");
d.setContentView(R.layout.inputdialog);
final EditText nameTxt= (EditText) d.findViewById(R.id.nameEditText);
Button saveBtn = (Button) d.findViewById(R.id.saveBtn);
//SAVE
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//GET DATA
String name=nameTxt.getText().toString();
//set data
Spacecraft s = new Spacecraft();
s.setName(name);
//SAVE
if(name != null && name.length()>0)
{
if(helper.save(s))
{
nameTxt.setText("");
}
}else
{
Toast.makeText(MainActivity.this, "Name Cannot Be Empty", Toast.LENGTH_SHORT).show();
}
}
});
d.show();
}
}
Can do this:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Category");
ref.orderByChild("categoryname").equalTo(name).addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot){
if(dataSnapshot.exist()) {
Toast.makeText(MainActivity.this, "Name already exists", Toast.LENGTH_SHORT).show();
}
}
Can do the above, it will search in the Category node in the db, and if it exists then it will give you the Toast message.

How to pass data between fragments of a FragmentTabHost?

I'm trying to learn android and am having an issue with this project. I have set up a fragment tab host with four fragments. What I would like to do is have the first three fragments be interactive with the user and when they tab over to the 4th tab, it will display all the information they put in on the first three. I figured I can pass the info overriding on onPause() as the trigger as I don't want to use a button press. Right now, I'm just trying to get the EditText to work to make sure I'm doing everything right. I'm not sure if I'm using the fragment transaction correctly, or the way I'm trying to collect the edit text field. Later on I hope to pass the information via a bundle. Any help would be appreciated.
Main:
package valdes.fragmenttabsmenu;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
import android.app.FragmentTransaction;
public class MainActivity extends FragmentActivity implements WelcomeFragment.WelcomeListener {
private FragmentTabHost mTabHost;
private String firstName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
mTabHost.addTab(mTabHost.newTabSpec("Home").setIndicator("Home", null), WelcomeFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Demographics").setIndicator("Demographics", null), DemographicsFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Questions").setIndicator("Questions", null), QuestionsFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Overview").setIndicator("Overview", null), OverviewFragment.class, null);
}
#Override
public void getFristName(String first_Name){
firstName = first_Name;
OverviewFragment fragment = new OverviewFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
fragment.setFirstName(firstName);
ft.addToBackStack(null);
ft.commit();
}
}
Fragment 1 - getting info
package valdes.fragmenttabsmenu;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class WelcomeFragment extends Fragment {
public WelcomeFragment() {
// Required empty public constructor
}
interface WelcomeListener{
public void getFristName(String firstName);
}
private WelcomeListener listener;
private String firstName;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_welcome, container, false);
EditText editText = (EditText) view.findViewById(R.id.first_name);
firstName = editText.getText().toString();
return view;
}
#Override
public void onAttach(Context context){
super.onAttach(context);
this.listener = (WelcomeListener)context;
}
#Override
public void onPause(){
super.onPause();
if(listener != null){
listener.getFristName(firstName);
}
}
}
Fragment 1 XML
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="#dimen/activity_horizontal_margin">
<TextView
android:id="#+id/welcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:textSize="25sp"
android:text="#string/welcome_message"/>
<EditText
android:id="#+id/first_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/first_name"/>
<EditText
android:id="#+id/last_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/last_name"/>
<Spinner
android:id="#+id/birthday"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="#array/months"/>
</LinearLayout>
Fragment 2 - getting info
package valdes.fragmenttabsmenu;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class OverviewFragment extends Fragment {
private String firstName;
private String lastName;
public OverviewFragment() {
// 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_overview, container, false);
}
#Override
public void onStart(){
super.onStart();
View view = getView();
if(view != null){
TextView name = (TextView) view.findViewById(R.id.OV_name);
name.setText(firstName);
}
}
public void setFirstName(String firstName){this.firstName = firstName;}
}
Fragment 2 XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="valdes.fragmenttabsmenu.OverviewFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:textSize="25sp"
android:layout_weight="1"
android:text="#string/overview"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_horizontal"
android:textSize="40sp"
android:text="Responses go here"/>
<TextView
android:id="#+id/OV_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="TEST"/>
<Button
android:id="#+id/submit_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/submit"/>
</LinearLayout>
Create a Listner for get/set data between fragments and implement it on activity like this
InteractionLister.java
public interface InteractionLister {
void setData(String data);
String getData();
}
MainActivity.java
public class TabActivity extends Activity implements InteractionLister{
private String mData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void setData(String data) {
this.mData = data;
}
#Override
public String getData() {
return mData;
}
}
TabFragment1.java
public class TabFragment1 extends Fragment {
InteractionLister interactionLister;
private static final String TAG = TabFragment1.class.getSimpleName();
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
Log.w(TAG,"Data from other fragment " + interactionLister.getData());
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
interactionLister = (InteractionLister) activity;
}
}

xml layout loads but my activity doesn't respond to button clicks

I'm new at this but I already made a small app that worked the same way.
I can't see what I'm doing wrong because the code looks quiet the same as my previous app.
When I run it or debug my app it shows my layout on my emulator so it does load the page that has to be loaded but that's all it does, it doesn't listen to button clicks. I also gives me no errors.
Here's my XML code for fragment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment">
<TextView
android:text="Eventaris"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="100px"
android:textStyle="bold"
android:id="#+id/lblEventaris"
/>
<LinearLayout
android:layout_width="500px"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:orientation="vertical"
android:id="#+id/login">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Gebruikersnaam"
android:id="#+id/txtGebruikersnaam"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Wachtwoord"
android:inputType="textPassword"
android:layout_below="#id/txtGebruikersnaam"
android:id="#+id/txtWachtwoord"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Inloggen"
android:id="#+id/btnInloggen"
android:layout_below="#id/txtWachtwoord"/>
</LinearLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:layout_below="#id/login">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="nog geen account?"
android:gravity="center"
android:id="#+id/lblRegistratie"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Registeren"
android:id="#+id/btnRegistreren"
android:layout_below="#id/lblRegistratie"/>
</RelativeLayout>
</RelativeLayout>
Here's my fragmennt activity MainFragment.Java
package com.example.arno.eventaris;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import java.sql.SQLException;
/**
* Created by Arno on 28/04/2015.
*/
public class MainFragment extends Fragment {
private OnMainFragmentInteractionListener mListener;
private View view;
public MainFragment()
{
//required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view=inflater.inflate(R.layout.fragment_main, container, false);
Button btnInloggen = (Button) view.findViewById(R.id.btnInloggen);
btnInloggen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
inloggen();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
Button btnRegistreren = (Button) view.findViewById(R.id.btnRegistreren);
btnRegistreren.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
navigeerRegistratie();
}
});
return view;
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try{
mListener = (OnMainFragmentInteractionListener) activity;
}
catch (ClassCastException e)
{
throw new ClassCastException(activity.toString() + "must implement OnFragmentInteractionListener");
}
}
public void inloggen() throws SQLException {
EditText gebr=(EditText) view.findViewById(R.id.txtGebruikersnaam);
EditText wachtw=(EditText) view.findViewById(R.id.txtWachtwoord);
String gebruiker = gebr.getText().toString();
String wachtwoord = wachtw.getText().toString();
mListener.login(gebruiker, wachtwoord);
}
public void navigeerRegistratie()
{
mListener.navigeerRegistratie();
}
#Override
public void onDetach()
{
super.onDetach();
mListener = null;
}
public interface OnMainFragmentInteractionListener {
//Todo: Update argument type and name
public void login(String gebruiker, String wachtwoord) throws SQLException;
public void navigeerRegistratie();
}
}
Here is my Main Activity MainActivity.java
package com.example.arno.eventaris;
import android.app.DialogFragment;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.example.arno.eventaris.Database.DBAdapter;
import java.sql.SQLException;
public class MainActivity extends ActionBarActivity implements MainFragment.OnMainFragmentInteractionListener,RegistratieFragment.OnRegistratieFragmentInteractionListener{
private Cursor gebruikerCursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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);
}
#Override
public void login(String gebruiker, String wachtwoord) throws SQLException {
DBAdapter db = new DBAdapter(this);
db.open();
gebruikerCursor = db.getGebruiker(gebruiker);
if(gebruikerCursor.moveToFirst()) {
gebruikerCursor.moveToFirst();
String wwControle = gebruikerCursor.getString(gebruikerCursor.getColumnIndex("wachtwoord"));
if (wachtwoord.equals(wwControle)) {
HomeFragment fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putString("gebruikersnaam", gebruiker);
fragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
} else {
DialogFragment errorlogin = new ErrorLogin();
errorlogin.show(getFragmentManager(), "Wachtwoord incorrect!");
}
}
else
{
DialogFragment errorlogin = new ErrorLogin();
errorlogin.show(getFragmentManager(), "Gebruikersnaam incorrect!");
}
db.close();
}
#Override
public void navigeerRegistratie() {
getFragmentManager().beginTransaction().replace(R.id.container, new RegistratieFragment()).commit();
}
#Override
public void registreren(String gebruiker, String voornaam, String naam, String email, String wachtwoord, String herhaalWachtwoord) {
if(wachtwoord.equals(herhaalWachtwoord)) {
DBAdapter db = new DBAdapter(this);
db.open();
long id = db.insertGebruiker(gebruiker, voornaam, naam, email, wachtwoord);
getFragmentManager().beginTransaction().replace(R.id.container, new MainFragment()).commit();
}
else
{
DialogFragment errorregistratie = new ErrorRegistratie();
errorregistratie.show(getFragmentManager(), "Wachtwoorden komen niet overeen!");
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
And as last here is my activity_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/container"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity" tools:ignore="MergeRootFrame" />
Thanks in advance!
Fixed it by making a new project with the same code, had to be a problem way deeper than my code.

Fragment in layout

I'am trying to communicate betwen two fragment extended classes with the help of MainActivity bt always get an error{03-01 14:30:42.675: E/AndroidRuntime(1724): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myfrag/com.example.myfrag.Tool}: android.view.InflateException: Binary XML file line #8: Error inflating class fragment}
package com.example.myfrag;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class ToolBoxFrag extends FragmentActivity implements OnSeekBarChangeListener {
private static int seekvalue = 10;
private static EditText edittext;
ToolbarListener activityCallback;
public interface ToolbarListener {
public void onButtonClick(int position, String text);
}
public void onAttach(Fragment activity) {
super.onAttachFragment(activity);
try {
activityCallback = (ToolbarListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement ToolbarListener");
}
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
seekvalue = progress;
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
setContentView(R.layout.activity_main);
edittext = (EditText)findViewById(R.id.editText1);
final SeekBar seekbar =
(SeekBar) findViewById(R.id.seekBar1);
seekbar.setOnSeekBarChangeListener(this);
final Button button =
(Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttonClicked(v);
}
});
return ;
}
public void buttonClicked (View view) {
activityCallback.onButtonClick(seekvalue,
edittext.getText().toString());
}
}
TextFragment.java
package com.example.myfrag;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TextFragment extends FragmentActivity {
private static TextView textview;
#Override
public void onCreate( Bundle savedInstanceState) {
setContentView(R.layout.main);
textview = (TextView) findViewById(R.id.textView1);
return;
}
public void changeTextProperties(int fontsize, String text)
{
textview.setTextSize(fontsize);
textview.setText(text);
}
}
MainActivity
package com.example.myfrag;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
public class Tool extends FragmentActivity implements ToolBoxFrag.ToolbarListener {
//public TextFragment tf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frag2);
}
public void onButtonClick(int fontsize, String text) {
TextFragment tf = new TextFragment();
getSupportFragmentManager().findFragmentById(R.id.main);
tf.changeTextProperties(fontsize, text);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main,
menu);
return true;
}
}
xml layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FragmentExampleActivity" >
<fragment
android:id="#+id/activity_main"
android:name="com.example.fragmentexample.ToolbarFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:layout="#layout/activity_main" />
<fragment
android:id="#+id/main"
android:name="com.example.fragmentexample.TextFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
tools:layout="#layout/main" />
</RelativeLayout>
Problem is the class path you have described the fragment name path wrong ..
it should be com.example.myfrag not com.example.fragmentexample
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FragmentExampleActivity" >
<fragment
android:id="#+id/activity_main"
android:name="com.example.myfrag.ToolbarFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
tools:layout="#layout/activity_main" />
<fragment
android:id="#+id/main"
android:name="com.example.myfrag.TextFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
tools:layout="#layout/main" />
</RelativeLayout>

Categories

Resources