如何使用单例类将多个值解析为android中的数据库?

时间:2014-12-04 14:21:56

标签: android json database sqlite singleton

我正在构建一个所有值都在的Android应用程序 使用volley以json数据的形式从URL解析到我的应用程序。现在我 想要将解析后的值存储到我的本地数据库中。

我尝试使用singleton类将值存储在数据库中。 现在我面临的问题是只有最后一个值 解析为singleton类的set函数,插入到我的 本地数据库,但其余值不是。我正在插入 单击按钮时,我的数据库中的值。

这是我的代码,我从URL解析值并设置为 单身人士班 -

package tabsswipe;
public class FragmentPlay extends Fragment {

private static final String TAG = FragmentPlayo.class.getSimpleName();

// Movies json url
private static final String url = "http://URL/api/user/_id/host";
private ProgressDialog pDialog;
private List<Sigleton_class> movieList = new ArrayList<Sigleton_class>();
private ListView listView;
private CustomListAdapter adapter;
DatabaseHelper dbh;
public static ArrayList<String> array;
ImageView hostbtn;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {


    final View rootView = inflater.inflate(R.layout.fragment_play,
            container, false);


    return rootView;
}

@Override
public void onStart() {
    // TODO Auto-generated method stub
    super.onStart();

    // Creating volley request obj
    JsonArrayRequest movieReq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    hidePDialog();

                    // Parsing json
                    for (int i = 0; i < response.length(); i++) {
                        try {

                            JSONObject obj = response.getJSONObject(i);
                            Sigleton_class movie = new Sigleton_class();
                            movie.setTitle(obj.getString("venue"));
                            movie.setGender(obj.getString("gender"));
                            movie.setAddinfo(obj.getString("addinfo"));

                            // adding movie to movies array
                            movieList.add(movie);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    // notifying list adapter about data changes
                    // so that it renders the list view with updated data
                    adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    hidePDialog();

                }
            });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(movieReq);

}

@Override
public void onDestroy() {
    super.onDestroy();
    hidePDialog();
}

private void hidePDialog() {
    if (pDialog != null) {
        pDialog.dismiss();
        pDialog = null;
    }
}
}
  

这是我的单身人士代码。

package volley_signleton_pck;

import java.util.ArrayList;

public class Sigleton_class {
private static String title;
private String thumbnailUrl;
private static String gender;
private String recurring;
private static String addinfo;
private String players;
private String date;
private String venue;
private String time;
private String sportname;
private int year;
private double rating;
private ArrayList<String> genre;


public Sigleton_class() {
}

public Sigleton_class(String name, String thumbnailUrl, int year, double rating,String 
gender,String recurring,String addinfo,
        String player,String date,String venue,String time,String sportname,
        ArrayList<String> genre) {
    this.title = name;
    this.thumbnailUrl = thumbnailUrl;
    this.year = year;
    this.rating = rating;
    this.genre = genre;
    this.gender = gender;
    this.recurring = recurring;
    this.addinfo = addinfo;
    this.players = player;
    this.date = date;
    this.venue = venue;
    this.time = time;
    this.sportname = sportname;
}

public static String getTitle() {
    return title;
}

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

public String getThumbnailUrl() {
    return thumbnailUrl;
}

public void setThumbnailUrl(String thumbnailUrl) {
    this.thumbnailUrl = thumbnailUrl;
}

public int getYear() {
    return year;
}

public void setYear(int year) {
    this.year = year;
}

public double getRating() {
    return rating;
}

public void setRating(double rating) {
    this.rating = rating;
}

public ArrayList<String> getGenre() {
    return genre;
}

public void setGenre(ArrayList<String> genre) {
    this.genre = genre;
}

public static String getGender() {
    return gender;
}

public void setGender(String gender) {
    this.gender = gender;
}

public String getRecurring() {
    return recurring;
}

public void setRecurring(String recurring) {
    this.recurring = recurring;
}

public static String getAddinfo() {
    return addinfo;
}

public void setAddinfo(String addinfo) {
    this.addinfo = addinfo;
}

public String getPlayers() {
    return players;
}

public void setPlayers(String players) {
    this.players = players;
}

public String getDate() {
    return date;
}

public void setDate(String date) {
    this.date = date;
}

public String getVenue() {
    return venue;
}

public void setVenue(String venue) {
    this.venue = venue;
}

public String getTime() {
    return time;
}

public void setTime(String time) {
    this.time = time;
}

public String getSportname() {
    return sportname;
}

public void setSportname(String sportname) {
    this.sportname = sportname;
}
 }
  

这是我的代码,我将单例类中的数据插入到我的代码中   数据库

btnSave = (Button) findViewById(R.id.btnSave);
    btnSave.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            long res = dbh.addRec(Sigleton_class.getTitle(),
                    Sigleton_class.getGender(), Sigleton_class.getAddinfo());

            if (res > 0) {

                AlertDialog.Builder build = new AlertDialog.Builder(
                        MainActivity_DB.this);
                build.setTitle("Success");
                build.setMessage("Record inserted successfully");
                build.setNeutralButton("Ok",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                // TODO Auto-generated method stub

                                etMail.setText(" ");
                                etPword.setText(" ");
                                etMobile.setText(" ");
                            }
                        });
                build.show();
            }

        }
    });
  

这是我的datahelper类

package com.example.mydatabase;
import android.util.Log;

public class DatabaseHelper {
SQLiteDatabase db;
DbHelper dbHelper;
//Context mContext;
public static final String DB_NAME = "contact";
public static final int DB_VER = 4;

public static final String TBL_NAME = "info";
public static final String COL_ID = "_id";
public static final String COL_EMAIL = "email";
public static final String COL_PWORD = "password";
public static final String COL_MOBILE = "mobile";

String[] allColumns ={COL_ID, COL_EMAIL, COL_PWORD, COL_MOBILE};

public DatabaseHelper(Context context)
{

    dbHelper = new DbHelper(context);
    db = dbHelper.getWritableDatabase();

}
public void addData(List<Sigleton_class> mov) {

       for (Sigleton_class movie : mov) {
           ContentValues values = new ContentValues();
           values.put(COL_EMAIL, movie.getTitle());
           values.put(COL_PWORD, movie.getDate());//get name
           values.put(COL_MOBILE, movie.getAddinfo());//get phone number
           //insert contact
           db.insert(TBL_NAME, COL_ID, values);
       }
       db.close();
   }
public long addRec(String email, String pword, String mobile)
{
    long i=0;
    ContentValues cv = new ContentValues();
    cv.put(COL_EMAIL, email);
    cv.put(COL_PWORD, pword);
    cv.put(COL_MOBILE, mobile);

    i=db.insert(TBL_NAME, COL_ID, cv);  

    return i;

}
public Cursor getRec(String strMail)
{
    Cursor cur = null;
    if((strMail==null)&&(strMail.length()==0))
    {
        cur = db.query(TBL_NAME, allColumns, null, null,null,null, null);
        //"like '" +name+"%'", 

    }
    else
    {

     String sel[] = {strMail+"'%'"};
    //  cur= db.query(TBL_NAME, allColumns, 
        //      COL_EMAIL+ " like '"+ strMail + "%'" ,null, null, null, null);

        cur = db.query(TBL_NAME, allColumns, COL_EMAIL+ " like ", sel, 
                null,null, null);
    }   
    return cur;

}

public long updateRec(int id, String email, String pw, String mob)
{
    long i=0;
    ContentValues cv = new ContentValues();
    cv.put(COL_EMAIL, email);
    cv.put(COL_PWORD, pw);
    cv.put(COL_MOBILE, mob);
    i=db.update(TBL_NAME, cv, COL_ID+"=?", new String[]{String.valueOf(id)});


    return i;
}
public long  deleteRec(int id)
{
    long i=0;
    i=db.delete(TBL_NAME, COL_ID + "=?" , new String[]{String.valueOf(id)});

    return i;       
}
public Cursor fetchAllRec()
{
    db= dbHelper.getReadableDatabase();
    Cursor cur= null;
    cur = db.query(TBL_NAME, allColumns, null, null, null, null, null);
    if(cur != null)
    {

        cur.moveToFirst();
    }   

    return cur;
}




public class DbHelper extends SQLiteOpenHelper
{

    public DbHelper(Context context)
    {
        super(context, DB_NAME, null, DB_VER);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String createSql = "create table " + TBL_NAME + "(" +COL_ID + 
                " INTEGER primary key autoincrement," +
                COL_EMAIL + " TEXT(50)," + COL_PWORD + " TEXT(40),"
                +COL_MOBILE + " TEXT(50))";

        Log.d("Create ", createSql);
        db.execSQL(createSql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS " + TBL_NAME);
        onCreate(db);
    }       
}   
}

0 个答案:

没有答案