如何将从recyclerview返回的值存储到数据库

时间:2016-01-14 11:41:29

标签: android json android-sqlite android-recyclerview

作为购物车应用程序的一部分,我正在处理一个回收站视图,该视图从在线和显示器获取一些产品数据,每个视图都有一个增量,减量按钮,允许客户选择购买数量

我想存储最终购物车的数据。即,如果在每个项目中选择的数量大于零,我需要将其存储在购物车页面中显示。我尝试使用数据库,但得到了以下错误,请帮助

java.lang.NullPointerException: Attempt to invoke virtual method 'void 
android.database.sqlite.SQLiteDatabase.execSQL(java.lang.String)' on a null object reference

MainActivity.java

package mmart.raycast.info.recyclerjson;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
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.view.Window;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecycleAdapter recycleAdapter;
List<HashMap<String, String>> onlineData;
ProgressDialog pd;
SQLiteDatabase db;

Toolbar toolbar;

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

    db = openOrCreateDatabase("Cart", Context.MODE_PRIVATE, null);
    db.execSQL("CREATE TABLE IF NOT EXISTS items(name VARCHAR,quantity VARCHAR);");


    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getBaseContext());
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setHasFixedSize(true);

    final String url = "http://www.qa4.org/?json=get_recent_posts&count=45";
    new AsyncHttpTask().execute(url);


}


public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {

    @Override
    protected void onPreExecute() {
        pd=new ProgressDialog(MainActivity.this);
        pd.requestWindowFeature(Window.FEATURE_NO_TITLE);
        pd.setMessage("Loading please wait...");
        pd.setCancelable(false);
        pd.show();
    }

    @Override
    protected Integer doInBackground(String... params) {
        Integer result = 0;
        HttpURLConnection urlConnection;
        try {
            URL url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            int statusCode = urlConnection.getResponseCode();

            // 200 represents HTTP OK
            if (statusCode == 200) {
                BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null) {
                    response.append(line);
                }
                parseResult(response.toString());
                result = 1; // Successful
            } else {
                result = 0; //"Failed to fetch data!";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result; //"Failed to fetch data!";
    }

    @Override
    protected void onPostExecute(Integer result) {
        // Download complete. Let us update UI
        pd.dismiss();

        if (result == 1) {
            recycleAdapter = new RecycleAdapter(MainActivity.this,onlineData);
            recyclerView.setAdapter(recycleAdapter);
        } else {
            Toast.makeText(MainActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show();
        }
    }
}

private void parseResult(String result) {
    try {
        JSONObject response = new JSONObject(result);
        JSONArray posts = response.optJSONArray("posts");
        onlineData = new ArrayList<>();

        for (int i = 0; i < posts.length(); i++) {
            JSONObject post = posts.optJSONObject(i);

            HashMap<String, String> item = new HashMap<>();
            item.put("title", post.optString("title"));

            JSONArray jsonArray = post.getJSONArray("attachments");
            JSONObject jsonObject1 = jsonArray.getJSONObject(0);
            JSONObject jsonArrayImages = jsonObject1.getJSONObject("images");
            JSONObject jsonArrayThumb = jsonArrayImages.getJSONObject("thumbnail");

            item.put("thump", jsonArrayThumb.optString("url"));

            onlineData.add(item);


        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

}

RecycleAdapter.java

package mmart.raycast.info.recyclerjson;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
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 android.widget.Toast;

import com.squareup.picasso.Picasso;

import java.util.HashMap;
import java.util.List;

public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.ViewHolderRec> {

    List<HashMap<String, String>> onlineData;
    SQLiteDatabase db;

    String ItemName, ItemQuantity;
    Context context;
    RecycleAdapter(Context context,List<HashMap<String, String>> onlineData){
        this.onlineData = onlineData;
        this.context=context;
    }

    @Override
    public ViewHolderRec onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolderRec( LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycle, parent, false));
     }

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

        HashMap<String,String> map =onlineData.get(position);

        //Download image using picasso library
        Picasso.with(context).load(map.get("thump"))
                .error(R.drawable.placeholder)
                .placeholder(R.drawable.placeholder)
                .into(holder.iv);

        holder.tv.setText(map.get("title"));

    }

    @Override
    public int getItemCount() {
        return onlineData.size();
    }

    public class ViewHolderRec extends RecyclerView.ViewHolder implements View.OnClickListener{
        ImageView iv;
        TextView tv, quantity;
        ImageView Add_Cart;
        ImageView Remove_Cart;

        public ViewHolderRec(View itemView) {
            super(itemView);
            iv = (ImageView) itemView.findViewById(R.id.thumbnail);
            tv = (TextView) itemView.findViewById(R.id.title);
            quantity = (TextView)itemView.findViewById(R.id.cart_qty);
            Add_Cart = (ImageView)itemView.findViewById(R.id.cart_add);
            Remove_Cart = (ImageView)itemView.findViewById(R.id.cart_remove);
            itemView.setOnClickListener(this);
            Add_Cart.setOnClickListener(this);
            Remove_Cart.setOnClickListener(this);


        }

        @Override
        public void onClick(View v) {
            if(v.getId() == Add_Cart.getId())
            {
                int currentNos = Integer.parseInt(quantity.getText().toString()) ;
                currentNos = currentNos++;
                ItemName = tv.getText().toString();
                ItemQuantity = String.valueOf(currentNos);
                quantity.setText(String.valueOf(++currentNos));
                AddItemToCart(ItemQuantity, ItemName);

            }
            else if(v.getId() == Remove_Cart.getId())
            {
                int currentNos = Integer.parseInt(quantity.getText().toString()) ;
                currentNos = currentNos--;
                ItemName = tv.getText().toString();
                ItemQuantity = String.valueOf(currentNos);
                quantity.setText(String.valueOf(--currentNos));
                AddItemToCart(ItemQuantity, ItemName);
            }
        }


        public  void AddItemToCart(String quantity, String name){

            db.execSQL("INSERT INTO items VALUES('"+name+"','"+quantity+"');");

           Cursor c=db.rawQuery("SELECT * FROM items",null);
            if (c.getCount()==0)
            {

            }
            else{
            while(c.moveToNext())
            {
                Toast.makeText(context, "Name = " + c.getString(0) + "Quantity" + c.getString(1), Toast.LENGTH_SHORT).show();
            }

            }
        }


    }
}

2 个答案:

答案 0 :(得分:0)

您永远不会在RecycleAdapter中初始化SQLiteDatabase db;,因此

db.execSQL("INSERT INTO items VALUES('"+name+"','"+quantity+"');");

导致NPE。

答案 1 :(得分:0)

如果您没有创建特定类的实例,则会出现此错误。因此,请初始化SQLiteDatabase db