打开我的应用程序时,数据重复两次

时间:2017-02-15 10:25:41

标签: android listview

我有一个以JSON响应的API。当我单击一个按钮时,我很容易解析JSON并在ListView中实现它。问题是当我打开我的应用程序时 再次,数据再次出现在ListView中。 以下是我的代码 -

Monday.java:

package com.example.reema.datatab2;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

/**
 * Created by reema on 30-Jan-17.
 */
public class Monday extends Fragment {
    private String TAG = Monday.class.getSimpleName();
    DatabaseHandler databaseHandler;
    static boolean isDataLoaded = false;

    private ProgressDialog pDialog;

    ArrayList<HashMap<String, String>> mondayList;

    ListView listview;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.monday,container,false);
        mondayList= new ArrayList<>();
        listview =(ListView)v.findViewById(R.id.lstmonday);
        new GetContacts().execute();
        return v;
    }


    class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            databaseHandler = new DatabaseHandler(getActivity());
            HttpHandler sh = new HttpHandler();
            String url = "My link here";
            String jsonStr = sh.makeServiceCall(url);
            Log.e(TAG, "Responce from url:" + jsonStr);


            if(isDataLoaded == false) {
                if (jsonStr != null) {

                    try {
                        JSONObject jsonObj = new JSONObject(jsonStr);


                        JSONArray Monday = jsonObj.getJSONArray("Monday");


                        for (int i = 0; i < Monday.length(); i++) {


                            JSONObject c = Monday.getJSONObject(i);

                            String SubjectName = c.getString("SubjectName");
                            String StandardName;
                            if (c.isNull("StandardName")) {
                                StandardName = null;
                            } else {
                                StandardName = c.getString("StandardName");
                            }


                            String DivisionName;
                            if (c.isNull("DivisionName")) {
                                DivisionName = null;
                            } else {
                                DivisionName = c.getString("DivisionName");
                            }
                            String StartTime = c.getString("StartTime");
                            String EndTime = c.getString("EndTime");

                            String LectureNoId;
                            if (c.isNull("DivisionName") && (c.isNull("StandardName"))) {
                                LectureNoId = null;
                            } else {
                                LectureNoId = c.getString("LectureNoId");
                            }

                            databaseHandler.addMonday(new People(LectureNoId, SubjectName, StandardName, DivisionName, StartTime, EndTime));
                    /*    HashMap<String, String> monday = new HashMap<>();
                        monday.put("LectureNoId",LectureNoId);
                        monday.put("SubjectName", SubjectName);
                        monday.put("StandardName", StandardName);
                        monday.put("DivisionName", DivisionName);
                        monday.put("StartTime", StartTime);
                        monday.put("EndTime", EndTime);

                        mondayList.add(monday);*/

                        }
                    } catch (final JSONException e) {
                        Log.e(TAG, "Json parsing error: " + e.getMessage());
                        getActivity().runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(getActivity().getApplicationContext(),
                                        "Json parsing error: " + e.getMessage(),
                                        Toast.LENGTH_LONG)
                                        .show();
                            }
                        });
                    }
                }
            }
                 else {
                    Log.e(TAG, "Couldn't get json from server.");
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity().getApplicationContext(),
                                    "Couldn't get json from server. Check LogCat for possible errors!",
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }


            return null;
        }
        protected void onPreExecute () {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
               pDialog.show();

        }
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            if (pDialog.isShowing())
                pDialog.dismiss();



            List<People>monday = databaseHandler.getAllMonday();
            for(People p : monday) {

                HashMap<String, String> mondayhash = new HashMap<>();
                mondayhash.put("LectureNoId",p.getLectureNoId());
                mondayhash.put("SubjectName", p.getSubjectName());
                mondayhash.put("StandardName", p.getStandardName());
                mondayhash.put("DivisionName", p.getDivisionName());
                mondayhash.put("StartTime", p.getStartTime());
                mondayhash.put("EndTime", p.getEndTime());

                mondayList.add(mondayhash);
            }

            ListAdapter adapter = new SimpleAdapter(
                    getActivity(), mondayList,
                    R.layout.custom_list, new String[]{"SubjectName", "StandardName",
                    "DivisionName","StartTime","EndTime"}, new int[]{R.id.SubjectName,
                    R.id.StandardName, R.id.DivisionName,R.id.StartTime,R.id.EndTime});
            isDataLoaded=true;
            databaseHandler.deleteMonday();
            listview.setAdapter(adapter);

        }


    }

}

Databasehandler.java:

package com.example.reema.datatab2;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

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


public class DatabaseHandler extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "mondayManager";
    private static final String Monday = "monday";



    private static final String LectureNoId = "LectureNoId";
    private static final String SubjectName = "SubjectName";
    private static final String StandardName = "StandardName";
    private static final String DivisionName = "DivisionName";
    private static final String StartTime = "StartTime";
    private static final String EndTime = "EndTime";


    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String monday = "CREATE TABLE " + Monday + "(" + LectureNoId + " TEXT,"
                + SubjectName + " TEXT," + StandardName + " TEXT," + DivisionName + " TEXT," + StartTime + " TEXT,"
                + EndTime + " TEXT" + ")";
        db.execSQL(monday);




    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS Monday ");
        db.execSQL("DROP TABLE IF EXISTS Tuesday" );
        db.execSQL("DROP TABLE IF EXISTS Wensday" );
        db.execSQL("DROP TABLE IF EXISTS  Thursday");
        db.execSQL("DROP TABLE IF EXISTS  Friday");
        db.execSQL("DROP TABLE IF EXISTS  Saturday");



        onCreate(db);
    }
    public void addMonday(People contact) {

        if (!SearchExistingLectureID(contact.getLectureNoId(), Monday)) {

          SQLiteDatabase db = this.getWritableDatabase();

            ContentValues values = new ContentValues();
            values.put(LectureNoId, contact.getLectureNoId());
            values.put(SubjectName, contact.getSubjectName());
            values.put(StandardName, contact.getStandardName());
            values.put(DivisionName, contact.getDivisionName());
            values.put(StartTime, contact.getStartTime());
            values.put(EndTime, contact.getEndTime());


            db.insert(Monday, null, values);
            Log.d("db", "insert called");
            db.close();

        }
    }
void deleteMonday()
{
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("delet from Monday");
}



    public Boolean SearchExistingLectureID(String LectureID, String Table)
    {
        String selectQuery = "SELECT  * FROM " + Table + " where LectureNoId = "  +LectureID;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        Boolean retValue = false;
        //there is a chance of exceptoin if the lectureid is not found in db.
        try {
            if (cursor.getCount()>0 && cursor.moveToFirst()) {
                String val =  cursor.getString(1);

                retValue = true;
            }
        }catch (Exception ex){
            Log.d("error", ex.getMessage());
        }
        return  retValue;
    }

    public List<People> getAllMonday() {
        List<People> MondayList = new ArrayList<People>();

        String selectQuery = "SELECT  * FROM " + Monday;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {

            do {
                People contact = new People(cursor.getString(0),cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5));
                contact.setLectureNoId(cursor.getString(0));
                contact.setSubjectName(cursor.getString(1));
                contact.setStandardName(cursor.getString(2));
                contact.setDivisionName(cursor.getString(3));
                contact.setStartTime(cursor.getString(4));
                contact.setEndTime(cursor.getString(5));

                MondayList.add(contact);

            } while (cursor.moveToNext());
        }


        return MondayList;

    }



   }

3 个答案:

答案 0 :(得分:2)

检查表行否

     if(databaseHandler.getRows()==0)
     {
        new GetContacts().execute(); //Calling
        databaseHandler.addMethod();
     }
    else
    {

    }

方式

public int getRows()
{
    String countQuery = "SELECT * FROM your_table_name";
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    int cnt = cursor.getCount();
    cursor.close();
    return cnt;
}

答案 1 :(得分:0)

将以下代码添加到您的DatabaseHandler

数据库清算方法

public void removeAll()
{

    SQLiteDatabase db = this.getWritableDatabase(); // helper is object extends SQLiteOpenHelper
    db.delete(DatabaseHelper.TAB_USERS, null, null);
    db.delete(DatabaseHelper.TAB_USERS_GROUP, null, null);
}

请致电

databaseHandler.removeAll();之前

databaseHandler.addMonday(new People(LectureNoId, SubjectName, StandardName, DivisionName, StartTime, EndTime));

GetContacts AsyncTask。

  

这是因为您通过对数据库执行相同的数据来复制数据库。

致谢:请参阅this

答案 2 :(得分:-1)

List<People>monday = databaseHandler.getAllMonday();
monday.clear;
for(People p : monday) {}

尝试这个我认为你应该清除数组