Json数据没有存储在Sqlite中

时间:2016-08-04 05:31:32

标签: android json sqlite

我正在使用Recyclerview,这里是Json文件,用Json数组编写的插入查询,虽然json数据没有存储在SQLite中。当我们销毁应用程序并再次重启时它只会显示 空白行再次按一个按钮,它将显示json数据aftr emptyrow即:在销毁数据丢失后。帮我谢谢

public class Recyclerview extends AppCompatActivity {
private RecyclerView mRecyclerView;
CustomAdapter cu;

ArrayList<Employee> arr, arr1;
Toolbar toolbar;

TextView t1, t2;

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

    toolbar = (Toolbar) findViewById(R.id.toolbar1);
    setSupportActionBar(toolbar);

    final RecyclerView rv = (RecyclerView) findViewById(R.id.rv);
    rv.setHasFixedSize(true);

    arr = new ArrayList<Employee>();
    arr = InitializeData();

    final LinearLayoutManager llm = new LinearLayoutManager(Recyclerview.this);
    rv.setLayoutManager(llm);
    rv.setHasFixedSize(true);

    cu = new CustomAdapter(Recyclerview.this, arr);

    rv.setAdapter(cu);

    registerForContextMenu(rv);
    final bank ban = new bank(Recyclerview.this);
    ImageButton refresh = (ImageButton) findViewById(R.id.refresh);

    refresh.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Toast.makeText(Recyclerview.this, "ok", Toast.LENGTH_LONG).show();
            if (isNetworkAvailable()) {

                String url = ConstantValues.BASE_URL;
                RequestBody formBody = new FormBody.Builder()
                        .add("key1", "value1")
                        .add("key2", "value2")
                        .add("key3", "value3")
                        .build();

                try {
                    post(url, formBody, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e("JSONDemo", "IOException", e);
                        }

                        @Override
                        public void onResponse(final Call call, final Response response) throws IOException {
                            String JSON = response.body().string();
                            Log.e("res", " " + JSON);
                            try {
                                JSONObject jsonObj = new JSONObject(JSON);

                                JSONArray resultarr = jsonObj.getJSONArray("result");
                                final JSONArray resultarr1 = jsonObj.getJSONArray("result1");

                                ban.OpenDB();
                                ban.OpenDB();
                                for (int i = 0; i < resultarr1.length(); i++) {

                                    Employee emp = new Employee();
                                    JSONObject result1obj = resultarr1.getJSONObject(i);
                                    String result1Id = result1obj.getString(ConstantValues.Bank_ID);
                                    String result1NAME = result1obj.getString(ConstantValues.Bank_NAME);
                                    Log.e("result", " " + result1Id);
                                    Log.e("result", " " + result1NAME);
                                    emp.setId(result1obj.getString(ConstantValues.Bank_ID));
                                    emp.setName(result1obj.getString(ConstantValues.Bank_NAME));
                                    arr.add(emp);
                                    long l = 0;
                                    l=ban.InsertQryForTabEmpData(ConstantValues.Bank_ID,ConstantValues.Bank_NAME);



                                }
                                ban.CloseDB();


                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                                                                    cu.notifyDataSetChanged();
                                    }
                                });
                            } catch (Exception e) {
                                Log.e("JSONDemo", "onResponse", e);
                            }

                        }
                    });

                } catch (Exception e) {
                    Log.e("JSONDemo", "Post Exception", e);
                }

            } else {
                Toast.makeText(Recyclerview.this, "Internet not available", Toast.LENGTH_LONG).show();
            }


        }
    });


}

private ArrayList<Employee> InitializeData() {
    ArrayList<Employee> arr_emp = new ArrayList<Employee>();
    bank ban = new bank(Recyclerview.this);
    long l = 0;
    ban.OpenDB();
    arr_emp = ban.AllSelectQryForTabEmpData1();
    ban.CloseDB();
    return arr_emp;
}


private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}


private final OkHttpClient client = new OkHttpClient();

Call post(String url, RequestBody formBody, Callback callback) throws IOException {

    Request request = new Request.Builder()
            .url(url)
            .post(formBody)
            .build();

    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;
}
}

这是所有SQLite的查询:

public class bank {

private Context context;
private SQLiteDatabase SQLiteDb;

public bank(Context context){
    this.context=context;
}


public static class DBHelper extends SQLiteOpenHelper{

    public DBHelper(Context context) {
        super(context, ConstantValues.DBName, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(" create table if not exists " + ConstantValues.TabEmpData+"("
                + ConstantValues.Bank_ID + " text, "
                + ConstantValues.Bank_NAME  + " text )");




    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        db.execSQL(" create table if not exists " + ConstantValues.TabEmpData+"("
                + ConstantValues.Bank_ID + " text, "
                + ConstantValues.Bank_NAME  + " text )");



    }
}

public void OpenDB() {

    SQLiteDb = new DBHelper(context).getWritableDatabase();
}

public void CloseDB() {
    if (SQLiteDb.isOpen()) {
        SQLiteDb.close();
    }
}

public long InsertQryForTabEmpData(String ID, String NAME) {
    ContentValues cv = new ContentValues();
    cv.put(ConstantValues.Bank_ID, ID);
    cv.put(ConstantValues.Bank_NAME, NAME);


    long l = SQLiteDb.insert(ConstantValues.TabEmpData, null, cv);
    return l;
}

public long UpdateQryForTabEmpData(String ID
        , String NAME
) {
    ContentValues cv = new ContentValues();
    cv.put(ConstantValues.Bank_ID, ID);
    cv.put(ConstantValues.Bank_NAME, NAME);

    long l = SQLiteDb.update(ConstantValues.TabEmpData, cv, ConstantValues.Bank_ID+ "=" + ID, null);
    return l;
}

public long DeleteQryForTabEmpData(String ID) {
    long l = SQLiteDb.delete(ConstantValues.TabEmpData, ConstantValues.Bank_ID+ "=" + ID, null);

    return l;
}

public ArrayList SelectQryForTabEmpData(String ID) {
    ArrayList<String> data = new ArrayList();

    String[] arg = {
            "ID"
            , "NAME"

    };

    String selection = "  ID=  " + ID;
    String QRY = " SELECT ID,NAME FROM  TabEmpData WHERE  ID =  " + ID;// +" AND EmpFName = 'test' grup by empid,fname,lastname  having Empsalary > = 2000 order by fname asc,salry desc limit 100";
    Cursor cursor = SQLiteDb.rawQuery(QRY, null);//
    SQLiteDb.query(ConstantValues.TabEmpData, arg, selection, null, null, null, null, null);
    while (cursor.moveToNext()) {
        data.add(0, cursor.getString(cursor.getColumnIndex(ConstantValues.Bank_ID)));
        data.add(1, cursor.getString(cursor.getColumnIndex(ConstantValues.Bank_NAME)));

    }
    cursor.close();
    return data;
}

public ArrayList AllSelectQryForTabEmpData1() {
    ArrayList<Employee> data = new ArrayList();


    Cursor cursor = SQLiteDb.query(ConstantValues.TabEmpData, null, null, null, null, null, null, null);
    while (cursor.moveToNext()) {
        String id = cursor.getString(cursor.getColumnIndex(ConstantValues.Bank_ID));
        String name = cursor.getString(cursor.getColumnIndex(ConstantValues.Bank_NAME));


        data.add(new Employee(id, name));


    }
    cursor.close();
    return data;
}



}

我的自定义适配器:

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.EmpDataViewHolder> {
    final bank ban = new bank(CustomAdapter.this.context);
    private ArrayList<Employee> arr,filterlist;
    private Context context;

    public CustomAdapter(Context context, ArrayList<Employee> arr) {
        this.arr=arr;
        this.context=context;

        Toast.makeText(context,""+arr.size(),Toast.LENGTH_LONG).show();



    }

    @Override
    public EmpDataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(context).inflate(R.layout.cardview, parent, false);
        EmpDataViewHolder edvh = new EmpDataViewHolder(v);
        return edvh;
    }

    @Override
    public void onBindViewHolder(EmpDataViewHolder holder, int position) {

        Employee emp=arr.get(position) ;

        holder.id.setText(emp.getId());
        holder.name.setText(emp.getName());

        holder.cv.setTag(R.string.KeyForCV,position);




    }


    @Override
    public int getItemCount() {

            return arr.size();



    }

    public class EmpDataViewHolder extends RecyclerView.ViewHolder  {

        CardView cv;
        TextView id;
        TextView name;


        public EmpDataViewHolder(View itemView) {
            super(itemView);
            cv= (CardView) itemView.findViewById(R.id.cv);
            id= (TextView) itemView.findViewById(R.id.id);
            name= (TextView) itemView.findViewById(R.id.name);
        }
    }
}

请帮助我,我想摆脱这个问题,提前谢谢

0 个答案:

没有答案