Search code examples
androiddatabaserealmxlm

Realm Database / App crashes in start up / call realm.init(context) before creating a realm configuration


I'm a newbie in Android and I'm trying to create a Realm database by watching tutorials. But my app doesn't start, it crashes. My main idea is the user finds nearby shops, by his location, select type of shop if he wants (restaurant, caffee etc) and if he can't find the shop he wants, the app gives him the option to add a shop (by pin a marker in a map, select a name and a type). In the errors gives me call realm.init(context) before creating a realm configuration Whoever can help I'd appreciate it. This app is my graduation project. I've reached this far; MainScreen.java

public class MainScreen extends AppCompatActivity {
private ImageButton btn;
Animation scale;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_screen);
    scale = AnimationUtils.loadAnimation(this, R.anim.gps_button_animation);
    btn = (ImageButton) findViewById(R.id.ImageButton);
    btn.startAnimation(scale);

}

public void InfoActivity(View view) {
    Intent intent = new Intent(this, InfoActivity.class);
    startActivity(intent);
}

public void MapsActivity (View view){
    Intent intent = new Intent(this, MapsActivity.class);
    startActivity(intent);
}

public void Anazitisi (View view){
    Intent intent = new Intent(this, Anazitisi.class);
    startActivity(intent);
}

public void AddShopActivity (View view){
    Intent intent = new Intent(this, AddShopActivity.class);
    startActivity(intent);
}
}

AddShopActivity.java

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.konarx.a11042016.ShopProperties.Shop;

import io.realm.Realm;
import io.realm.RealmResults;

public class AddShopActivity extends MainScreen{

private EditText editText_name;
private Spinner spinner;
private ArrayAdapter<CharSequence> adapter;
private Button button_save;
private Realm realm;
private TextView textView_log;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_shop);

    realm = Realm.getDefaultInstance();

    editText_name = (EditText) findViewById(R.id.editName);
    button_save = (Button) findViewById(R.id.buttonSave);
    textView_log = (TextView) findViewById(R.id.textView_Log);
    spinner = (Spinner)findViewById(R.id.spinner);
    adapter = ArrayAdapter.createFromResource(this,R.array.eidoskatastimatos, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener(){

        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            Toast.makeText(getBaseContext(), adapterView.getItemAtPosition(i)+" selected", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });

    button_save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            save_into_database(editText_name.getText().toString().trim(), spinner.getAdapter().toString().trim());
            refresh_views();
        }
    });




}

private void refresh_views() {
    RealmResults<Shop> shopRealmResults = realm.where(Shop.class).findAll();
    String output = "";
    for (Shop shop: shopRealmResults){
        output += shop.toString();
    }
    textView_log.setText(output);
}

private void save_into_database(final String title, final String type) {
    realm.executeTransactionAsync(new Realm.Transaction() {
        @Override
        public void execute(Realm bgRealm) {
            Shop shop = bgRealm.createObject(Shop.class);
            shop.setTitle(title);
            shop.setType(type);
        }
    }, new Realm.Transaction.OnSuccess() {
        @Override
        public void onSuccess() {
            Log.v("Database", "saved!");
        }
    }, new Realm.Transaction.OnError() {
        @Override
        public void onError(Throwable error) {
            Log.v("Database", error.getMessage());
        }
    });
}

@Override
protected void onDestroy() {
    super.onDestroy();
    realm.close();
}
}

Shop.java

package com.example.konarx.a11042016.ShopProperties;


import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;

public class Shop extends RealmObject{

@PrimaryKey
private int id;

private String title;

private String type;

private String Latitude;

private String Longitude;

// Standard getters & setters
public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public String getLatitude() {
    return Latitude;
}

public void setLatitude(String latitude) {
    Latitude = latitude;
}

public String getLongitude() {
    return Longitude;
}

public void setLongitude(String longitude) {
    Longitude = longitude;
}

@Override
public String toString() {
    return "Shop{" +
            "id=" + id +
            ", title='" + title + '\'' +
            ", type='" + type + '\'' +
            ", Latitude='" + Latitude + '\'' +
            ", Longitude='" + Longitude + '\'' +
            '}';
}
}

BaseApplication.java

import android.app.Application;

import io.realm.Realm;
import io.realm.RealmConfiguration;

public class BaseApplication extends Application{
@Override
public void onCreate() {
    super.onCreate();

    RealmConfiguration config = new RealmConfiguration.Builder().build();
    Realm.setDefaultConfiguration(config);
}
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.konarx.a11042016">

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.location.gps" />

<application
    android:allowBackup="true"
    android:icon="@drawable/logo"
    android:label="@string/app_name"
    android:name=".BaseApplication"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainScreen">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:name=".InfoActivity"
        android:label="Πληροφορίες"></activity>

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

    <activity
        android:name=".MapsActivity"
        android:label="Χάρτης"></activity>

    <activity
        android:name=".Anazitisi"
        android:label="Αναζήτηση"></activity>

    <activity
        android:name=".AddShopActivity"
        android:label="Προσθήκη Καταστήματος"></activity>

</application>

</manifest>

Solution

  • public class BaseApplication extends Application{
         @Override
         public void onCreate() {
             super.onCreate();
             Realm.init(this);  // add this line
             RealmConfiguration config = new RealmConfiguration.Builder().build();
             Realm.setDefaultConfiguration(config);
         }
      }