mercredi 22 juin 2016

SQLite and JSON

I am trying to store some JSON data into the sqlite database. Let me explain this in a bit more detail. I have two model objects. The first one is used to take the json objects and convert them to strings. Those strings are stored in the database via the second model.

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    setRetainInstance(true);
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_testing, container, false);

    modelArrayList = new ArrayList<>();
    dba = new DatabaseHandler(getActivity());

    mRecyclerView = (RecyclerView)v.findViewById(R.id.recycler_view);

    final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(linearLayoutManager);

    myAdapter = new MyAdapter(getActivity(),modelArrayList);
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    //setting the adapter
    mRecyclerView.setAdapter(myAdapter);
    if(savedInstanceState!=null){
        ArrayList<Model> items = 
        savedInstanceState.getParcelableArrayList(TEST_KEY);
        //Here I get all the data of the ArrayList<Model>.


        myAdapter.setMemebers(items);
    }else{
        showTestData();

    }

    return v;


}
//In this method I get the JSON objects with the help of the Volley lib.
public void showTestData()
  {
   modelArrayList.clear();
   // Request a string response from the provided URL.
     final JsonArrayRequest jsObjRequest = new   
    JsonArrayRequest(Request.Method.GET, URLClass.URL, new  
     Response.Listener<JSONArray>() {

       @Override
       public void onResponse(JSONArray response) {
           Log.d("Theo", response.toString());
           //I use i=1 to bypass the first JSON object which doesn't contain  
           the object member.
           //If i set i=0,then I will get an exception.
           for(int i = 1;i<response.length();i++){


               try {

                   //Here I read the 4 objects.
                   JSONObject jsonObject = response.getJSONObject(i);

                   //I get the members array for JSON object
                   JSONArray teamMembersArray =  
                   jsonObject.getJSONArray("members");


                   for(int j=0;j<teamMembersArray.length();j++) {

                       //The model class which contains the setters/getters
                       //in order to "deserialize" the JSON objects into  
                       //string objects.
                      m = new Model();

                       JSONObject teamObject =   
                        teamMembersArray.getJSONObject(j);
                       //I am searching if the teamLead object exists.If yes
                       //then set it to true by reading it! If not then read
                       //the next members!
                       if (teamObject.has("teamLead") && 
                       (!teamObject.isNull("teamLead")))  {
                           m.setTeamLead(teamObject.getBoolean("teamLead"));
                       }else {
                           //Default value
                           m.setTeamLead(false);

                       }
                       m.setId(teamObject.getInt("id"));


             m.setProfileImageURL(teamObject.getString("profileImageURL"));
                       m.setFirstName(teamObject.getString("firstName"));
                       m.setLastName(teamObject.getString("lastName"));
                       m.setRole(teamObject.getString("role"));

                       //Finally I am adding the string objects into an        
                      ArrayList.
                       modelArrayList.add(m);

                       id = Integer.parseInt(teamObject.getString("id"));
                       fname = teamObject.getString("firstName");
                       lname = teamObject.getString("lastName");
                       role = teamObject.getString("role");
                       proImage = teamObject.getString("profileImageURL");
                       //uncomment this you will see the exception I describe  
                       //inside
                       //the DatabaseHandler Class
                       saveToDB();
                   }
               } catch (JSONException e) {
                   e.printStackTrace();
               }
               // Update list by notifying the adapter of changes
               myAdapter.notifyDataSetChanged();
           }



           myAdapter.notifyDataSetChanged();
       }
   }, new Response.ErrorListener() {
       @Override
       public void onErrorResponse(VolleyError error) {

           //hidePD();
       }
   });
   AppController.getInstance().addToRequestQueue(jsObjRequest);

}
   //Calling the saveToDB from the DatabaseHandler
   private void saveToDB(){
    SQLiteModel sqLiteModel = new SQLiteModel();
    sqLiteModel.setSqliteId(id);
    sqLiteModel.setSqliteFirstName(fname);
    sqLiteModel.setSqliteSecondName(lname);
    sqLiteModel.setSqliteRole(role);
    sqLiteModel.setSqliteImage(proImage);

    dba.addMembers(sqLiteModel);

    dba.close();

 }


@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    //all the data of the ArrayList<Model> are stored.
    Log.d("Theo","onSaveInstanceState called");
    outState.putParcelableArrayList(TEST_KEY,modelArrayList);
}
}

As shown the Model m = new Model is used convert the json objects to Strings.

 m.setId(teamObject.getInt("id"));

 m.setProfileImageURL(teamObject.getString("profileImageURL"));
 m.setFirstName(teamObject.getString("firstName"));
 m.setLastName(teamObject.getString("lastName"));
 m.setRole(teamObject.getString("role"));

 //Finally I am adding the string objects into an   
 //ArrayList.
 modelArrayList.add(m);

Next I extract the values from that response.

      id = Integer.parseInt(teamObject.getString("id"));
      fname = teamObject.getString("firstName");
      lname = teamObject.getString("lastName");
      role = teamObject.getString("role");
      proImage = teamObject.getString("profileImageURL");

I do that to pass those values inside the SQLiteModel.

  private void saveToDB(){
    SQLiteModel sqLiteModel = new SQLiteModel();
    sqLiteModel.setSqliteId(id);
    sqLiteModel.setSqliteFirstName(fname);
    sqLiteModel.setSqliteSecondName(lname);
    sqLiteModel.setSqliteRole(role);
    sqLiteModel.setSqliteImage(proImage);

    dba.addMembers(sqLiteModel);

    dba.close();

}

I put a breakpoint to the line dba.addMembers(sqliteMode),to see if the data are stored.And yes they are:). The addMethod() of the DatabaseHanderClass is this one.

//add content to table
public void addMembers(SQLiteModel m) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(Constants.MEMBER_ID,m.getSqliteId());
    values.put(Constants.FIRST_NAME, m.getSqliteFirstName());
    values.put(Constants.LAST_NAME,m.getSqliteSecondName());
    values.put(Constants.JOB_ROLE,m.getSqliteRole());
    values.put(Constants.PROFILE_IMAGE,m.getSqliteImage());


    db.insertWithOnConflict(Constants.TABLE_NAME, Constants.MEMBER_ID,   values,
            SQLiteDatabase.CONFLICT_REPLACE);
    db.close();
    Log.v("DB","heeeey!data saved");
}

And here is main question. I disable the internet,in order to start another activity. However,the same recyclerview with all the data are shown,and this is really weird!!! I do a check if there is an internet connection in my main activity. So I say,if yes,attach the fragment that handles the webservice stuff and displayes it in a recycler view. If not,then start a new activity(i will change it to fragment later),and read the data from the SQLiteDatabase.

public class MainActivity extends AppCompatActivity {
private static final String TESTING_FRAGMENT = "testing_fragment";
TestingFragment ts;
private FragmentManager fragmentManager;

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

        fragmentManager = getSupportFragmentManager();
        ts = (TestingFragment) fragmentManager.findFragmentByTag(TESTING_FRAGMENT);
        //When the fragment is rotating ie savedInstanceState !=null
        if (savedInstanceState != null) {
            //Restore the fragment's state
            ts = (TestingFragment) getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
        }
        if(ts==null) {
            //Attach fragment to main activity
            ts = new TestingFragment();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.add(android.R.id.content, ts);
            fragmentTransaction.commit();
        }

    } else {
        Intent i = new Intent(MainActivity.this, NoInternetActivity.class);
        startActivity(i);
    }



}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    //Save the fragment's state
    getSupportFragmentManager().putFragment(outState, "mContent", ts);
}

private boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    return cm.getActiveNetworkInfo() != null;
  }
}

Any ideas why this is happening?

Thanks Theo.

Aucun commentaire:

Enregistrer un commentaire