2016-08-15 181 views
0

我是android新手。從領域檢索數據時遇到問題。我使用retrofit,並希望使用Realm(Sqlite成功)保存數據,但從數據庫中檢索數據時出現了一些我發佈的錯誤。從領域檢索數據時出錯

package np.com.rabindraacharya.retrofitintern.ui; 

import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.design.widget.FloatingActionButton; 
import android.support.design.widget.Snackbar; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.LinearLayoutManager; 
import android.support.v7.widget.RecyclerView; 
import android.support.v7.widget.Toolbar; 
import android.util.Log; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 

import java.util.List; 

import np.com.rabindraacharya.retrofitintern.Controller.RestManager; 
import np.com.rabindraacharya.retrofitintern.R; 
import np.com.rabindraacharya.retrofitintern.model.Flower; 
import np.com.rabindraacharya.retrofitintern.model.adapter.FlowerAdapter; 
import np.com.rabindraacharya.retrofitintern.model.helper.Constants; 
import np.com.rabindraacharya.retrofitintern.model.helper.FlowerDatabase; 
import np.com.rabindraacharya.retrofitintern.model.helper.Utils; 
import retrofit2.Call; 
import retrofit2.Callback; 
import retrofit2.Response; 

public class MainActivity 
     extends AppCompatActivity 
     implements FlowerAdapter.FlowersClickListener { 
    private RecyclerView recyclerView; 
    private RestManager mManager; 
    FlowerAdapter mFlowerAdapter; 
    FlowerDatabase mDatabase; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show(); 
      } 
     }); 

     configViews(); 
     mManager = new RestManager(); 
     mDatabase = new FlowerDatabase(); 
     if(Utils.isNetworkAvailable(getApplicationContext())) { 
      getFeed(); 
     } else { 
      getFeedFromDatabase(); 
     } 
    } 

    private void getFeedFromDatabase() { 
     Log.e("RetData", "RetData"); 
     List<Flower> flowerList = mDatabase.getFlower(); 
     for(int i = 0; i < flowerList.size(); i++) { 
      Flower flower = flowerList.get(i); 
      mFlowerAdapter.addFlower(flower); 
     } 
    } 

    private void configViews() { 
     recyclerView = (RecyclerView) findViewById(R.id.recyclerView); 
     recyclerView.setHasFixedSize(true); 
     recyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool()); 

     LinearLayoutManager verticalLayoutmanager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false); 
     recyclerView.setLayoutManager(verticalLayoutmanager); 
     mFlowerAdapter = new FlowerAdapter(this); 
     recyclerView.setAdapter(mFlowerAdapter); 
    } 

    @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 onClick(int position) { 
     Flower selectedFlower = mFlowerAdapter.getSelectedFlower(position); 
     Intent intent = new Intent(MainActivity.this, DetailActivity.class); 
     intent.putExtra(Constants.REFERENCE.FLOWER, selectedFlower); 
     startActivity(intent); 
    } 

    public void getFeed() { 
     Call<List<Flower>> listCall = mManager.getFlowerService().getAllFlowers(); 
     listCall.enqueue(new Callback<List<Flower>>() { 
      @Override 
      public void onResponse(Call<List<Flower>> call, Response<List<Flower>> response) { 
       if(response.isSuccessful()) { 
        List<Flower> flowerList = response.body(); 
        for(int i = 0; i < flowerList.size(); i++) { 
         Flower flower = flowerList.get(i); 

         SaveIntoDatabase task = new SaveIntoDatabase(); 
         task.execute(flower); 
         mFlowerAdapter.addFlower(flower); 
        } 
       } else { 
        int st = response.code(); 
        switch(st) { 
        } 
       } 
      } 

      @Override 
      public void onFailure(Call<List<Flower>> call, Throwable t) { 
      } 
     }); 
    } 

    public class SaveIntoDatabase 
      extends AsyncTask<Flower, Flower, Boolean> { 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
     } 

     @Override 
     protected Boolean doInBackground(Flower... params) { 
      Flower flower = params[0]; 
      try { 
       //InputStream stream = new URL("http://services.hanselandpetal.com/photos/" + flower.getPhoto()).openStream(); 
       // Bitmap bitmap = BitmapFactory.decodeStream(stream); 
       //flower.setPicture(bitmap); 
       mDatabase.addFlower(flower); 
       Log.e("ErrorAft", "ErrorAft"); 
      } catch(Exception e) { 

      } 
      return null; 
     } 
    } 
} 

FlowerDatabase

package np.com.rabindraacharya.retrofitintern.model.helper; 

import android.os.Bundle; 
import android.support.annotation.Nullable; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 

import java.util.ArrayList; 
import java.util.List; 

import io.realm.Realm; 
import io.realm.RealmResults; 
import np.com.rabindraacharya.retrofitintern.model.Flower; 
import np.com.rabindraacharya.retrofitintern.model.adapter.FlowerAdapter; 

/** 
* Created by Rabindra on 8/12/2016. 
*/ 
public class FlowerDatabase 
     extends AppCompatActivity { 
    private Realm myRealm; 
    private int productID; 
    private static FlowerDatabase flowerDatabase; 
    private static List<Flower> arrayListFlower = new ArrayList<>(); 
    private FlowerAdapter flowerAdapter; 

    @Override 
    protected void onCreate(@Nullable Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     myRealm = Realm.getDefaultInstance(); 
     flowerDatabase = this; 
    } 

    public void addFlower(Flower model) { 
     Log.e("RealmData", "RealmData"); 
     myRealm.beginTransaction(); 
     Flower flower = myRealm.createObject(Flower.class); 
     flower.setProductId(model.getProductId()); 
     flower.setCategory(model.getCategory()); 
     flower.setName(model.getName()); 
     flower.setPrice(model.getPrice()); 
     flower.setInstruction(model.getInstruction()); 
     arrayListFlower.add(flower); 
     myRealm.commitTransaction(); 
     flowerAdapter.notifyDataSetChanged(); 
    } 

    public List<Flower> getFlower() { 
     Flower model = new Flower(); 
     productID = model.getProductId(); 

     RealmResults<Flower> results = myRealm.where(Flower.class).findAll(); 
     myRealm.beginTransaction(); 

     for(int i = 0; i < results.size(); i++) { 
      arrayListFlower.add(results.get(i)); 
     } 
     if(results.size() > 0) { 
      productID = myRealm.where(Flower.class).max("id").intValue() + 1; 
     } 
     myRealm.commitTransaction(); 
     flowerAdapter.notifyDataSetChanged(); 
     return arrayListFlower; 
    } 
} 

錯誤的logcat:

否E/AndroidRuntime:致命異常:主 工藝:np.com.rabindraacharya.retrofitintern,PID:17091

java.lang.RuntimeException:無法啓動活動 ComponentInfo {np.com.rabindraacharya.retrofitintern/np.com.rabindraacharya.retrofitintern.ui.MainActivity}: 顯示java.lang.NullPointerException 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2375) at android.app.ActivityThread.access $ 900(ActivityThread.java:164) at android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1268)在Android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:157)012( )at android.app.ActivityThread.main(ActivityThread.java:5377) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1265) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081) at dalvik.system.NativeStart。 main(Native Method) 引起:java.lang.NullPointerException at np.com.rabindraacharya.retrofitintern.model.helper.FlowerDatabase.getFlower(FlowerDataba se.java:70) 在 np.com.rabindraacharya.retrofitintern.ui.MainActivity.getFeedFromDatabase(MainActivity.java:69) 在 np.com.rabindraacharya.retrofitintern.ui.MainActivity.onCreate(MainActivity.java: 63) 在android.app.Activity.performCreate(Activity.java:5428) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java: 2281) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2375) at android.app.ActivityThread.access $ 900(ActivityThread.java:164) at android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1268) at android.os.Handler.dispatchMessage(Handler.java: 102) at android.os.Looper.loop(Looper.java:157) at android.app.ActivityThread.main(ActivityThread.java:5377) at java.lang。方法.invokeNative(本地方法) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1265) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081) 在dalvik.system.NativeStart.main(本機方法)

+0

1)你使用的Realm版本是什麼,2)你打算在'FlowerDatabase'中做什麼,因爲這個類是完全錯誤的。 – EpicPandaForce

+0

最後我解決了這個問題。感謝你的評論 –

回答

0

可能嘗試與您FlowerDatabase類擴展AppCompatActivity沒有真正有效的原因,但onCreate()永遠不會運行,因爲你mDatabase = new FlowerDatabase();實例化的flowerDatabase,並且因此不會由系統管理。 (這甚至不應該是一個活動,即使是這樣,你也必須創建一個Intent,就像你對任何活動做過的一樣)。

從技術上講,你應該重寫你的代碼,因爲目前它在概念上是錯誤的。

特別是你的FlowerDatabase類完全,因爲你濫用Realm以及。