NullPointerException: Attempt to invoke virtual method 'void io.realm.Realm.beginTransaction()' on a null object reference - nullpointerexception

So I am making an app where I use an activity to introduce data about cities using Realm. I want to save the data when the floating action button is pressed but I keep getting a NullPointerExeption and when I debbug the app I see that realm in realm.beginTransaction() is null..
Can someone give an advice on why this happens? Thank you!
City class:
package com.android.bianca.cityworld2.models;
import com.android.bianca.cityworld2.app.MyApplication;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import io.realm.annotations.Required;
/**
* Created by Bianca on 25/01/2017.
*/
public class City extends RealmObject {
#PrimaryKey
private int id;
#Required
private String nombre;
#Required
private String description;
#Required
private String imagen;
public City(){
};
public City(String nombre, String description, String imagen) {
this.id = MyApplication.CityID.incrementAndGet();
this.nombre = nombre;
this.description = description;
this.imagen = imagen;
}
public int getID(){ return id;}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImagen() {
return imagen;
}
public void setImagen(String imagen) {
this.imagen = imagen;
}
}
AddEditActivity:
package com.android.bianca.cityworld2.activities;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.bianca.cityworld2.R;
import com.android.bianca.cityworld2.models.City;
import com.squareup.picasso.Picasso;
import io.realm.Realm;
public class AddEditActivity extends AppCompatActivity {
private FloatingActionButton fabSave;
private Realm realm;
private TextView textViewNombre;
private TextView textViewDescription;
private ImageView imageViewImagen;
private TextView textViewUrlFoto;
private ImageView imageViewPreview;
private City ciudadNueva;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_edit);
Realm.init(getApplicationContext());
Realm realm = Realm.getDefaultInstance();
bindReferences();
imageViewPreview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String imageURL = textViewUrlFoto.getText().toString();
if(imageURL.equals("")) {
Toast.makeText(AddEditActivity.this, "No has introducido ningun url", Toast.LENGTH_SHORT).show();
}else {
Picasso.with(AddEditActivity.this).load(imageURL).error(R.mipmap.ic_star).fit().into(imageViewImagen);
}
}
});
fabSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
crearNuevaCiudad();
}
});
}
private void crearNuevaCiudad(){
String nombre = textViewNombre.getText().toString().trim();
String desc = textViewDescription.getText().toString().trim();
String img = textViewUrlFoto.getText().toString().trim();
ciudadNueva = new City(nombre,desc,img);
realm.beginTransaction();
realm.copyToRealm(ciudadNueva);
realm.commitTransaction();
//<Toast.makeText(AddEditActivity.this, nombre + "|"+description+"|"+img, Toast.LENGTH_SHORT).show();
}
private void bindReferences(){
fabSave = (FloatingActionButton) findViewById(R.id.fabSave);
textViewNombre =(TextView) findViewById(R.id.editTextEditAddNombre);
textViewDescription =(TextView) findViewById(R.id.editTextAddEditDescription);
textViewUrlFoto =(TextView) findViewById(R.id.editTextEditAddUrl);
imageViewImagen = (ImageView) findViewById(R.id.imageViewEditAddBackground);
imageViewPreview = (ImageView) findViewById(R.id.imageViewEditAddPreview);
}
}
MyApplication:
package com.android.bianca.cityworld2.app;
import android.app.Application;
import com.android.bianca.cityworld2.models.City;
import java.util.concurrent.atomic.AtomicInteger;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmObject;
import io.realm.RealmResults;
/**
* Created by Bianca on 26/01/2017.
*/
public class MyApplication extends Application {
public static AtomicInteger CityID = new AtomicInteger();
#Override
public void onCreate() {
setUpRealmConfig();
Realm realm = Realm.getDefaultInstance();
CityID = getIdByTable(realm, City.class);
realm.close();
}
private void setUpRealmConfig() {
Realm.init(this);
RealmConfiguration config = new RealmConfiguration.Builder().deleteRealmIfMigrationNeeded().build();
Realm.setDefaultConfiguration(config);
}
private <T extends RealmObject> AtomicInteger getIdByTable(Realm realm, Class<T> anyClass) {
RealmResults<T> results = realm.where(anyClass).findAll();
return (results.size() > 0) ? new AtomicInteger(results.max("id").intValue()) : new AtomicInteger();
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.bianca.cityworld2">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".activities.MainActivity">
</activity>
<activity android:name=".activities.AddEditActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Related

How is it possible to reach a checkbox or something else object from an other class

I have a list application what uses Recyclerview. All line have an checkbox, 2pcs TextView and a button. These are declarated in the RecyclerView class.
The application has got an other class what handles the data for example SharedPreferences, and calculations and so on...
How is it possible that I reach the objects what are in RecyclerView from the other class.
Here is the RecyclerView class:
package com.example.homehandling;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder>
{
public List<String> mData, subdata, subdata2;
public LayoutInflater mInflater;
public ItemClickListener mClickListener;
public Context context;
public TextView myTextView, subtext;
public Button add;
public CheckBox done;
MyRecyclerViewAdapter(Context context, List<String> data, List<String> subdata, List<String> subdata2) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
this.subdata = subdata;
this.subdata2 = subdata2;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String meta_data = mData.get(position);
String meta_subdata = subdata.get(position);
String meta_subdata2 = subdata2.get(position);
myTextView.setText(meta_data);
subtext.setText(meta_subdata +" "+ meta_subdata2);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] item_param = myTextView.getText().toString().split(" ");
final Intent intent;
intent = new Intent(context, NewSLItem.class);
intent.putExtra("param",item_param[0]);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
public ViewHolder(View itemView)
{
super(itemView);
context = itemView.getContext();
myTextView = itemView.findViewById(R.id.tvAnimalName);
subtext = itemView.findViewById(R.id.subtext);
add = itemView.findViewById(R.id.add);
done =itemView.findViewById(R.id.done);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
String getItem(int id) {return mData.get(id);
}
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
public interface ItemClickListener
{
void onItemClick(View view, int position);
}
}
and Here is the list class:
package com.example.homehandling;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class ToDoList extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener, View.OnClickListener {
public MyRecyclerViewAdapter adapter;
public Button btn;
public SharedPreferences sharedPreferences;
public SharedPreferences.Editor myEdit;
public LinkedList<String> items, remain_days, prio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shoppinglist);
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
myEdit = sharedPreferences.edit();
btn = findViewById(R.id.button);
items = new LinkedList<>();
remain_days = new LinkedList<>();
prio = new LinkedList<>();
RecyclerView recyclerView = findViewById(R.id.list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this,items,remain_days,prio);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
btn.setOnClickListener(this);
StartDisplay();
adapter.done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(adapter.done.isChecked()) Toast.makeText(ToDoList.this,"Something is done",Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onItemClick(View view, int position) {
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
String item_click =adapter.getItem(position);
String[] itemarray = item_click.split(" ",0);
myEdit = sharedPreferences.edit();
myEdit.remove(itemarray[0]);
myEdit.commit();
adapter.notifyItemRemoved(position);
items.remove(item_click);
}
#Override
public void onClick(View v) {
Intent NewTLItem = new Intent(ToDoList.this, NewTLItem.class);
startActivity(NewTLItem);
}
#Override
public void onResume() {
super.onResume();
StartDisplay();
}
public void StartDisplay()
{
sharedPreferences = getSharedPreferences("ToDoList", Context.MODE_PRIVATE);
Map<String, ?> allEntries = sharedPreferences.getAll();
items.clear();
prio.clear();
remain_days.clear();
for (Map.Entry<String, ?> entry : allEntries.entrySet())
{
String key_word = entry.getKey();
String [] item_total = entry.getValue().toString().split(";");
if(key_word.contains("_")) key_word = key_word.replace("_"," ");
items.add(key_word);
remain_days.add(Long.toString(DateCalc(item_total[0])));
prio.add(item_total[1]);
}
adapter.notifyDataSetChanged();
}
public long DateCalc(String startdate)
{
Date system_date, due_date;
long diff_date = 0;
String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
SimpleDateFormat dates = new SimpleDateFormat("dd-MM-yyyy");
try {
system_date = dates.parse(currentDate);
due_date = dates.parse(startdate);
diff_date = (due_date.getTime()-system_date.getTime())/86400000;
} catch (ParseException e) {
e.printStackTrace();
}
return diff_date;
}
}
The first attemption was that the objects were declarated in the ViewHolder class, but I can not reach that from the list class.
I put the objects to the RecyclerView class and now I can reach thoose because for example the adapter.done.setOnClickListener() is valid from Android Studio point of view, but I always got null object reference. I think I know why, because the layout xml what the list class uses haven't got checkbox item, but then I don't know how can I solve this.
I also try to inflate the RecyclerView layout:
final View view = mInflater.inflate(R.layout.recyclerview_row,null);
...
...
...
adapter.done = view.findViewById(R.id.done);
but then I got LayoutInflater null object reference exception.

Why my arraylist size equal to 0 on the adapter page?

I started to wrote app that gets input from the user (in edittext) and after pressing button it should pass the valued to another activity in custom listview.
I found a problem during the debugging that the arraylist in the adapter getting null or 0.
Here is the Adapter code and main activity.
I hope someone could help me with this issue.
Adapter
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class exampleAdapter extends RecyclerView.Adapter<exampleAdapter.ExampleViewHolder> {
private ArrayList<exampleItem> mExampleList;
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public TextView mTextViewLine1;
public TextView mTextViewLine2;
public ImageView imageView;
public ExampleViewHolder(View itemView) {
super(itemView);
mTextViewLine1 = itemView.findViewById(R.id.textview_line1);
mTextViewLine2 = itemView.findViewById(R.id.textview_line2);
imageView = itemView.findViewById(R.id.icond);
}
}
public exampleAdapter(ArrayList<exampleItem> exampleList) {
mExampleList = exampleList;
this.notifyDataSetChanged();
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
exampleItem currentItem = mExampleList.get(position);
holder.mTextViewLine1.setText(currentItem.getLine1());
holder.mTextViewLine2.setText(currentItem.getLine2());
if (currentItem.getLineimg().equalsIgnoreCase("s")) {
holder.imageView.setImageResource(R.drawable.salary);
}
if (currentItem.getLineimg().equalsIgnoreCase("e")){
holder.imageView.setImageResource(R.drawable.money);
}
}
#Override
public int getItemCount() {
return mExampleList.size();
}
}
MainActivity2
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class MainActivity2 extends AppCompatActivity {
private ArrayList<exampleItem> mExampleList = new ArrayList<>();
private exampleAdapter mAdapter = new exampleAdapter(mExampleList);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
setInsertButton();
loadData();
}
private void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences4", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list4", null);
Type type = new TypeToken<ArrayList<exampleItem>>() {
}.getType();
mExampleList = gson.fromJson(json, type);
if (mExampleList == null) {
mExampleList = new ArrayList<>();
}
}
private void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences4", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(mExampleList);
editor.putString("task list4", json);
editor.apply();
}
private void setInsertButton() {
Button buttonInsert = findViewById(R.id.insert);
buttonInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText line1 = findViewById(R.id.categ);
final EditText lineimg = findViewById(R.id.summ);
final EditText line2 = findViewById(R.id.date2);
String lin1 = line1.getText().toString();
String lin2 = line2.getText().toString();
String lin3 = lineimg.getText().toString();
insertItem(lin1, lin2, lin3);
saveData();
finish();
}
private void insertItem(String toString, String toString1, String toString2) {
mExampleList.add(new exampleItem(toString, toString2, toString1));
mAdapter.notifyItemInserted(mExampleList.size());
mAdapter.notifyDataSetChanged();
}
});
}
}
MainActivity
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<exampleItem> mExampleList = new ArrayList<>();
RecyclerView mRecyclerView;
private exampleAdapter mAdapter = new exampleAdapter(mExampleList);
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState1) {
super.onCreate(savedInstanceState1);
setContentView(R.layout.activity_main);
findViewById(R.id.buttoni).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
startActivity(intent);
}
});
buildRecyclerView();
}
private void buildRecyclerView() {
mRecyclerView = findViewById(R.id.recyclerview);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new exampleAdapter(mExampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
}
Bring out the inserItem method as separate from onClickListener and try out
private void insertItem(String toString, String toString1, String toString2) {
mExampleList.add(new exampleItem(toString, toString2, toString1));
mAdapter.notifyItemInserted(mExampleList.size());
mAdapter.notifyDataSetChanged();
}
you can remove this.notifydatachange() from adapter constructor
public exampleAdapter(ArrayList<exampleItem> exampleList) {
mExampleList = exampleList;
this.notifyDataSetChanged();
}

Users of android app are not showing up in Firebase

I made an android app and in that I just created login and registration page using firebase but when I sign up with a new account then that respective account should be recorded or it should be displayed in the user section of my Firebase But in the user section "No users are added yet" this message is displayed. Why is it so?
This is my AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.easylearn">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".HomeActivity"></activity>
<activity android:name=".LoginActivity" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
This is my MainActivity.java
package com.example.easylearn;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity {
EditText emailId,password;
Button btnSignUp;
TextView tvSignIn;
FirebaseAuth mFirebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFirebaseAuth = FirebaseAuth.getInstance();
emailId = findViewById(R.id.editText);
password = findViewById(R.id.editText2);
btnSignUp = findViewById(R.id.button2);
tvSignIn = findViewById(R.id.textView);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = emailId.getText().toString();
String pwd = password.getText().toString();
if(email.isEmpty())
{
emailId.setError("Please enter email id");
emailId.requestFocus();
}
else if(pwd.isEmpty())
{
password.setError("Please enter password");
password.requestFocus();
}
else if(email.isEmpty() && pwd.isEmpty())
{
Toast.makeText(MainActivity.this,"Fiels are Empty!",Toast.LENGTH_SHORT).show();
}
else if(!(email.isEmpty() && pwd.isEmpty()))
{
mFirebaseAuth.createUserWithEmailAndPassword(email,pwd).addOnCompleteListener(MainActivity.this,
new OnCompleteListener<com.google.firebase.auth.AuthResult>() {
#Override
public void onComplete(#NonNull Task<com.google.firebase.auth.AuthResult> task)
{
if(task.isSuccessful())
{
Toast.makeText(MainActivity.this,"SignUp Unsuccessful,Please Try
Again..",Toast.LENGTH_SHORT).show();
}
else {
startActivity(new Intent(MainActivity.this,HomeActivity.class));
}
}
});
}
else
{
Toast.makeText(MainActivity.this,"Error Occured!",Toast.LENGTH_SHORT).show();
}
}
});
tvSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,LoginActivity.class);
startActivity(i);
}
});
}
}
This is my LoginActivity.java
package com.example.easylearn;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseUser;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
public class LoginActivity extends AppCompatActivity {
EditText emailId,password;
Button btnSignIn;
TextView tvSignUp;
FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mFirebaseAuth = FirebaseAuth.getInstance();
emailId = findViewById(R.id.editText);
password = findViewById(R.id.editText2);
btnSignIn = findViewById(R.id.button2);
tvSignUp = findViewById(R.id.textView);
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser mFirebaseUser = mFirebaseAuth.getCurrentUser();
if(mFirebaseUser != null){
Toast.makeText(LoginActivity.this,"You are logged in",Toast.LENGTH_SHORT).show();
Intent i = new Intent(LoginActivity.this,HomeActivity.class);
startActivity(i);
}
else{
Toast.makeText(LoginActivity.this,"Please login",Toast.LENGTH_SHORT).show();
}
}
};
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = emailId.getText().toString();
String pwd = password.getText().toString();
if(email.isEmpty())
{
emailId.setError("Please enter email id");
emailId.requestFocus();
}
else if(pwd.isEmpty())
{
password.setError("Please enter password");
password.requestFocus();
}
else if(email.isEmpty() && pwd.isEmpty())
{
Toast.makeText(LoginActivity.this,"Fiels are Empty!",Toast.LENGTH_SHORT).show();
}
else if(!(email.isEmpty() && pwd.isEmpty()))
{
mFirebaseAuth.signInWithEmailAndPassword(email,pwd).addOnCompleteListener(LoginActivity.this, new
OnCompleteListener<com.google.firebase.auth.AuthResult>() {
#Override
public void onComplete(#NonNull Task<com.google.firebase.auth.AuthResult> task)
{
if(!task.isSuccessful()){
Toast.makeText(LoginActivity.this,"Login Error,Please Login
again..",Toast.LENGTH_SHORT).show();
}
else{
Intent inToHome = new Intent(LoginActivity.this,HomeActivity.class);
startActivity(inToHome);
}
}
});
}
else
{
Toast.makeText(LoginActivity.this,"Error Occured!",Toast.LENGTH_SHORT).show();
}
}
});
tvSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intSignUp = new Intent(LoginActivity.this,MainActivity.class);
startActivity(intSignUp);
}
});
}
#Override
protected void onStart() {
super.onStart();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
}`

Retrofit with recyclerview issue

I am not getting data in recycler view but not getting any error .
This is Main Activity class
package in.co.getonlinerecharge.cab.bw_cab.activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import in.co.getonlinerecharge.cab.bw_cab.AppController;
import in.co.getonlinerecharge.cab.bw_cab.R;
import in.co.getonlinerecharge.cab.bw_cab.adepter.CarTypeAdepter;
import in.co.getonlinerecharge.cab.bw_cab.helper.ToastHelper;
import in.co.getonlinerecharge.cab.bw_cab.model.Cartype;
import in.co.getonlinerecharge.cab.bw_cab.model.CartypeArray;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class Slect_Car_Activity extends AppCompatActivity {
RecyclerView rvGetCartype;
private ArrayList<Cartype> data;
private CarTypeAdepter carTypeAdepter;
private TextView txt_data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slect__car_);
rvGetCartype = (RecyclerView)findViewById(R.id.RV_list);
txt_data = (TextView)findViewById(R.id.txt_data);
getAndSetCarType();
}
private void getAndSetCarType() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage(getString(R.string.please_wait));
progressDialog.show();
Call<CartypeArray> call = AppController.getInstance().getApiInterface().getCartype();
call.enqueue(new Callback<CartypeArray>() {
#Override
public void onResponse(Call<CartypeArray> call, Response<CartypeArray> response) {
progressDialog.dismiss();
CartypeArray cartypeArray = response.body();
Collections.reverse(cartypeArray.getCtypes());
carTypeAdepter = new CarTypeAdepter(cartypeArray,getApplicationContext());
rvGetCartype.setAdapter(carTypeAdepter);
}
#Override
public void onFailure(Call<CartypeArray> call, Throwable t) {
progressDialog.dismiss();
}
});
}
}
This is my model class for retrofit which gives Json array with status
package in.co.getonlinerecharge.cab.bw_cab.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Cartype {
#SerializedName("id")
#Expose
private String id;
#SerializedName("vehicle_type")
#Expose
private String Vehicale_type;
#SerializedName("vehicle_name")
#Expose
private String Vehicale_name;
#SerializedName("vehicle_no")
#Expose
private String Vehicale_no;
#SerializedName("vimage")
#Expose
private String Vimage;
#SerializedName("status")
#Expose
private String status;
#SerializedName("created_at")
#Expose
private String created_at;
#SerializedName("updated_at")
#Expose
private String updated_at;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getVehicale_type() {
return Vehicale_type;
}
public void setVehicale_type(String vehicale_type) {
Vehicale_type = vehicale_type;
}
public String getVehicale_name() {
return Vehicale_name;
}
public void setVehicale_name(String vehicale_name) {
Vehicale_name = vehicale_name;
}
public String getVehicale_no() {
return Vehicale_no;
}
public void setVehicale_no(String vehicale_no) {
Vehicale_no = vehicale_no;
}
public String getVimage() {
return Vimage;
}
public void setVimage(String vimage) {
Vimage = vimage;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
}
This is my Adapter class with view holder for recycler view
package in.co.getonlinerecharge.cab.bw_cab.adepter;
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.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import in.co.getonlinerecharge.cab.bw_cab.R;
import in.co.getonlinerecharge.cab.bw_cab.model.Cartype;
import in.co.getonlinerecharge.cab.bw_cab.model.CartypeArray;
import in.co.getonlinerecharge.cab.bw_cab.utils.Constans;
public class CarTypeAdepter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private CartypeArray cartypeArray;
private Context mcontext;
public CarTypeAdepter(CartypeArray cartypeArray, Context mcontext) {
this.cartypeArray = cartypeArray;
this.mcontext = mcontext;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = (LayoutInflater.from(parent.getContext()).inflate(R.layout.list_car,parent, false));
CartypeHolder cartypeHolder = new CartypeHolder(view);
return cartypeHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder Holder, int position) {
CartypeHolder cartypeHolder = (CartypeHolder) Holder;
cartypeHolder.txt_cartype.setText(cartypeArray.getCtypes().get(position).getVehicale_name());
}
#Override
public int getItemCount() {
return cartypeArray.getCtypes().size();
}
private class CartypeHolder extends RecyclerView.ViewHolder {
ImageView img_car;
TextView txt_cartype;
public CartypeHolder(View itemview) {
super(itemview);
img_car = (ImageView)itemview.findViewById(R.id.CarImageView);
txt_cartype = (TextView)itemview.findViewById(R.id.titleTextView);
}
}
}
My second model class for retrofit for getting JSON data
package in.co.getonlinerecharge.cab.bw_cab.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class CartypeArray {
#SerializedName("status")
#Expose
private Boolean status;
#SerializedName("Cartype")
#Expose
private List<Cartype> ctypes;
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public List<Cartype> getCtypes() {
return ctypes;
}
public void setCtypes(List<Cartype> ctypes) {
this.ctypes = ctypes;
}
}
This is Activity main XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical" tools:context="in.co.getonlinerecharge.cab.bw_cab.activity.Slect_Car_Activity">
<android.support.design.widget.AppBarLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:title="Select Your Car" />
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/RV_list"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txt_data"/>
</LinearLayout>
List of display data for list view
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="50dp"
card_view:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/card_height"
android:orientation="vertical"
>
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/CarImageView"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:scaleType="centerCrop"
android:src="#drawable/suv"
/>
<TextView
android:layout_gravity="center"
android:id="#+id/titleTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp"
android:text="SUV"
android:textSize="#dimen/card_text_size"
android:textColor="#color/colorPrimary"/>
</LinearLayout>
</android.support.v7.widget.CardView>
set Layout Manager to your recycler in onCreate:
rvGetCartype = (RecyclerView)findViewById(R.id.RV_list);
rvGetCartype.setLayoutManager(new LinearLayoutManager(this));
If it didnt help try next:
1.Make sure, that in your response ArrayList isnt empty.
2.If it isnt, try to next:
public class CarTypeAdepter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
ArrayList<Cartype> cartypeArray;
private Context mcontext;
public CarTypeAdapter(Context context){
this.mcontext = context;
cartypeArray = new ArrayList<>();
}
public void setList(ArrayList<Cartype> list){
this. cartypeArray = list;
notifyDataSetChanges();
}
//other methods
}
then create variable of this adapter in activity and init it in onCreate, and set it to your recycler view. Then in onResponse use method setList(cartypeArray) to set array to adapter.
Hope you understand me and its help.

My android service Mqtt client app keeps crashing

Good day, i really need help because this is now a big headache. the code looks fine but when i click on the subscribe button, the app will crash.
this is my android manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.generalsteinacoz.realmqttclient" >
<uses-permission android:name="android.permission.INTERNET">
</uses-permission>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".FirstActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MQTTService"/>
</application>
</manifest>
this is the code for the main Activity (i.e UI)
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.generalsteinacoz.realmqttclient.MQTTService;
public class FirstActivity extends Activity {
EditText edt_host, edt_port, editTopicSub;
TextView txt_message;
Button btnSub;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
edt_host = (EditText) findViewById(R.id.edt_host);
edt_port = (EditText) findViewById(R.id.edt_port);
editTopicSub = (EditText) findViewById(R.id.edt_sub);
btnSub = (Button) findViewById(R.id.btnSave_sub);
txt_message = (TextView) findViewById(R.id.txt_messageBody);
onClick_Btn_Sub();
}
public void getMessage(String mess){
txt_message.setText(mess);
}
public String setTopic(){
String mainTopic = editTopicSub.getText().toString();
return mainTopic;
}
public String setbrokerPort(){
String mainBrokerPort = edt_host.getText()+":"+ edt_port.getText().toString();
return mainBrokerPort;
}
public void onClick_Btn_Sub(){
btnSub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent("MQTTService"));
}
});
}
#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_first, 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);
}
}
this is the code for the service class
import org.eclipse.paho.client.mqttv3.IMqttAsyncClient;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import com.example.generalsteinacoz.realmqttclient.FirstActivity;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MQTTService extends Service {
FirstActivity fa = new FirstActivity();
private static final String TAG = "MQTTService";
private static boolean hasWifi = false;
private static boolean hasMmobile = false;
private Thread thread;
private ConnectivityManager mConnMan;
private volatile IMqttAsyncClient mqttClient;
private String deviceId;
class MQTTBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
IMqttToken token;
boolean hasConnectivity = false;
boolean hasChanged = false;
NetworkInfo infos[] = mConnMan.getAllNetworkInfo();
for (int i = 0; i < infos.length; i++){
if (infos[i].getTypeName().equalsIgnoreCase("MOBILE")){
if((infos[i].isConnected() != hasMmobile)){
hasChanged = true;
hasMmobile = infos[i].isConnected();
}
Log.d(TAG, infos[i].getTypeName() + " is " + infos[i].isConnected());
} else if ( infos[i].getTypeName().equalsIgnoreCase("WIFI") ){
if((infos[i].isConnected() != hasWifi)){
hasChanged = true;
hasWifi = infos[i].isConnected();
}
Log.d(TAG, infos[i].getTypeName() + " is " + infos[i].isConnected());
}
}
hasConnectivity = hasMmobile || hasWifi;
Log.v(TAG, "hasConn: " + hasConnectivity + " hasChange: " + hasChanged + " - "+(mqttClient == null || !mqttClient.isConnected()));
if (hasConnectivity && hasChanged && (mqttClient == null || !mqttClient.isConnected())) {
doConnect();
} else if (!hasConnectivity && mqttClient != null && mqttClient.isConnected()) {
Log.d(TAG, "doDisconnect()");
try {
token = mqttClient.disconnect();
token.waitForCompletion(1000);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
};
public class MQTTBinder extends Binder {
public MQTTService getService(){
return MQTTService.this;
}
}
#Override
public void onCreate() {
IntentFilter intentf = new IntentFilter();
setClientID();
intentf.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(new MQTTBroadcastReceiver(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
mConnMan = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
Log.d(TAG, "onConfigurationChanged()");
android.os.Debug.waitForDebugger();
super.onConfigurationChanged(newConfig);
}
private void setClientID(){
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
deviceId = wInfo.getMacAddress();
if(deviceId == null){
deviceId = MqttAsyncClient.generateClientId();
}
}
private void doConnect(){
Log.d(TAG, "doConnect()");
IMqttToken token;
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(true);
try {
// mqttClient = new MqttAsyncClient(fa.setbrokerPort(), deviceId, new MemoryPersistence());
mqttClient = new MqttAsyncClient("tcp://iot.eclipse.org:1883", deviceId, new MemoryPersistence());
token = mqttClient.connect();
token.waitForCompletion(3500);
mqttClient.setCallback(new MqttEventCallback());
token = mqttClient.subscribe("#", 0);
//token = mqttClient.subscribe(fa.setTopic(), 0);
token.waitForCompletion(5000);
} catch (MqttSecurityException e) {
e.printStackTrace();
} catch (MqttException e) {
switch (e.getReasonCode()) {
case MqttException.REASON_CODE_BROKER_UNAVAILABLE:
case MqttException.REASON_CODE_CLIENT_TIMEOUT:
case MqttException.REASON_CODE_CONNECTION_LOST:
case MqttException.REASON_CODE_SERVER_CONNECT_ERROR:
Log.v(TAG, "c" +e.getMessage());
e.printStackTrace();
break;
case MqttException.REASON_CODE_FAILED_AUTHENTICATION:
Intent i = new Intent("RAISEALLARM");
i.putExtra("ALLARM", e);
Log.e(TAG, "b"+ e.getMessage());
break;
default:
Log.e(TAG, "a" + e.getMessage());
}
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, "onStartCommand()");
return START_STICKY;
}
private class MqttEventCallback implements MqttCallback {
#Override
public void connectionLost(Throwable arg0) {
}
#Override
public void deliveryComplete(IMqttDeliveryToken arg0) {
}
#Override
#SuppressLint("NewApi")
public void messageArrived(String topic, final MqttMessage msg) throws Exception {
Log.i(TAG, "Message arrived from topic" + topic);
Handler h = new Handler(getMainLooper());
h.post(new Runnable() {
#Override
public void run() {
Intent launchA = new Intent(MQTTService.this, FirstActivity.class);
launchA.putExtra("message", msg.getPayload());
//TODO write somethinkg that has some sense
if(Build.VERSION.SDK_INT >= 11){
launchA.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_REORDER_TO_F RONT|Intent.FLAG_ACTIVITY_NO_ANIMATION);
} /*else {
launchA.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}*/
startActivity(launchA);
Toast.makeText(getApplicationContext(), "MQTT Message:\n" + new String(msg.getPayload()), Toast.LENGTH_SHORT).show();
fa.getMessage(msg.getPayload().toString());
}
});
}
}
public String getThread(){
return Long.valueOf(thread.getId()).toString();
}
#Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "onBind called");
return null;
}
}