我是DB新手。我开发了一个应用程序,它获取最新的20个提要(JSON数据)并在自定义ListView中显示。 我也成功地将数据库插入到数据库中。但是当我第二次加载应用程序时,数据库没有更新,而是插入了两次。我的问题是如何更新现有的Feed?如果可能,建议我举例。 FragmentFeed.java
public class FragmentFeeds extends Fragment {
private static String url = "http://agile-tor-8294.herokuapp.com/home/publishedJson";
// JSON Node names
static final String TAG_BODY = "body";
static final String TAG_CREATED_AT = "created_at";
static final String TAG_DATE_TIME = "date_time";
static final String TAG_DEPARTEMENT = "department";
static final String TAG_ID = "id";
static final String TAG_INCLUDE = "include";
static final String TAG_MEDI_TYPE = "mediaType";
static final String TAG_PRIORITY = "priority";
static final String TAG_TITLE = "title";
static final String TAG_UPDATED_AT = "updated_at";
static final String TAG_USER_ID = "user_id";
static final String TAG_TIME = "";
ProgressDialog progressDialog;
Date mDateConvert;
// ...
HttpGet httpGet;
HttpEntity httpEntity;
HttpClient httpClient;
HttpResponse httpResponse;
StatusLine statusLine;
InputStream inputStream;
// to store in setters and getters
List<ModelClass> model = new ArrayList<ModelClass>();
ModelClass mc = null;
/* Data Base */
Cursor cursor = null;
String mDBRowId = null;
public static final String ID_EXTRA = "com.simbotix.leo._ID";
DataBaseNew dataBaseNew;
String dataBaseId = null;
// long listId = 0;
// ListView to display the feeds
ListView listViewFeeds;
NewAdapter adapter;
ArrayList<HashMap<String, String>> arrayListData;
String mTitle = null, mBody = null, mMediaType = null, mPriority = null,
mDepartement = null, mTime = null, mDayDate = null, mDate = null;
CommunictionSingleView communictionSingleView;
// read - unread.
Boolean readUnread = false;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
communictionSingleView = (CommunictionSingleView) activity;
}
/*
* (non-Javadoc)
*
* @see
* android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater,
* android.view.ViewGroup, android.os.Bundle)
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_feeds, container, false);
return view;
}
/*
* (non-Javadoc)
*
* @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle)
*/
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dataBaseNew = new DataBaseNew(getActivity());
// To display the data json feeds
listViewFeeds = (ListView) getActivity().findViewById(
R.id.listViewFeeds);
listViewFeeds.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
System.out.println("You selected " + position);
mMediaType = ((TextView) view
.findViewById(R.id.textViewMediaType)).getText()
.toString();
System.out.println("MediaType " + mMediaType);
mDepartement = ((TextView) view
.findViewById(R.id.textViewDepartement)).getText()
.toString();
System.out.println("Departement " + mDepartement);
mTitle = ((TextView) view.findViewById(R.id.textViewTitleFeeds))
.getText().toString();
System.out.println("Title " + mTitle);
mBody = ((TextView) view.findViewById(R.id.textViewBody))
.getText().toString();
System.out.println("Body " + mBody);
mPriority = ((TextView) view
.findViewById(R.id.textViewPriority)).getText()
.toString();
System.out.println("Priority " + mPriority);
communictionSingleView.onSingleView(mMediaType, mDepartement,
mDayDate, mTime, mPriority, mTitle, mBody);
readUnread = true;
// listId = id;
System.out.println("id: " + id);
}
});
arrayListData = new ArrayList<HashMap<String, String>>();
// Getting adapter by passing data to ArrayList
adapter = new NewAdapter((MainActivity) getActivity(), arrayListData);
if (CheckInternetConnection.isInternetConnected(getActivity())) {
Feeds feeds = new Feeds();
feeds.execute();
} else {
Toast.makeText(getActivity(),
getString(R.string.check_internet_connection),
Toast.LENGTH_SHORT).show();
}
}
class Feeds extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
super.onPreExecute();
}
@SuppressLint("SimpleDateFormat")
@Override
protected Void doInBackground(Void... arg0) {
httpClient = new DefaultHttpClient();
httpGet = new HttpGet(url);
httpGet.setHeader("Accept", "application/json");
try {
httpResponse = httpClient.execute(httpGet);
statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode != 200) {
Toast.makeText(getActivity(), "error" + statusCode,
Toast.LENGTH_SHORT).show();
return null;
}
httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
String jsonData = stringBuilder.toString();
Log.d("Latest 20 feeds", jsonData);
JSONArray array = new JSONArray(jsonData);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
mTitle = object.getString(TAG_TITLE);
mBody = object.getString(TAG_BODY);
mDate = object.getString(TAG_DATE_TIME);
mPriority = object.getString(TAG_PRIORITY);
// Formatting date and time
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
String dateInString = mDate;//
try {
mDateConvert = formatter.parse(dateInString);
System.out.println("Date: " + mDateConvert);
SimpleDateFormat dayDateFormat = new SimpleDateFormat(
"E, MMM dd");// Tue, Apr 22.
mDayDate = dayDateFormat.format(mDateConvert);
System.out.println("Custom date: " + mDayDate);
SimpleDateFormat timeFormat = new SimpleDateFormat(
"HH:mm:ss");// hh:mm:ss
mTime = timeFormat.format(mDateConvert);
System.out.println("Time: " + mTime);
} catch (ParseException e) {
e.printStackTrace();
} catch (java.text.ParseException e) {
e.printStackTrace();
}
mMediaType = object.getString(TAG_MEDI_TYPE);
mDepartement = object.getString(TAG_DEPARTEMENT);
String mDate = object.getString(TAG_DATE_TIME);
System.out.println("Titlte: " + mTitle);
System.out.println("Body: " + mBody);
System.out.println("MediaType: " + mMediaType);
System.out.println("Priority: " + mPriority);
System.out.println("Departement: " + mDepartement);
// System.out.println("Date and Time" + mDate);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, mTitle);
map.put(TAG_BODY, mBody);
map.put(TAG_PRIORITY, mPriority);
map.put(TAG_DEPARTEMENT, mDepartement);
map.put(TAG_DATE_TIME, mDayDate);
map.put(TAG_TIME, mTime);
map.put(TAG_MEDI_TYPE, mMediaType);
System.out.println("clone " + map.clone());
System.out.println("containsKey " + map.containsKey(map));
System.out.println("containsValue "
+ map.containsValue(map));
System.out.println("entrySet " + map.entrySet());
System.out.println("keySet " + map.keySet());
arrayListData.add(map);
// title , body , date , time , mediatype , priority ,
// departement, readunread
/* Data Base */
// inserting in to data base
// dataBaseId = getActivity().getIntent().getStringExtra(
// MainActivity.ID_EXTRA);
// dataBaseId = String.valueOf(listId);
if (dataBaseId == null) {
dataBaseNew.insert(mTitle, mBody, mMediaType,
mPriority, mDepartement, mDayDate, mTime,
readUnread);
} else {
dataBaseNew.update(dataBaseId, mTitle, mBody,
mMediaType, mPriority, mDepartement, mDayDate,
mTime, readUnread);
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listViewFeeds.setAdapter(adapter);
super.onPostExecute(result);
}
}
interface CommunictionSingleView {
public void onSingleView(String mediaType, String departement,
String dayDate, String time, String priority, String title,
String body);
}
@Override
public void onStop() {
super.onStop();
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}}
DataBaseNew.java
public class DataBaseNew {
DBHelper helper;
public DataBaseNew(FragmentActivity activity) {
helper = new DBHelper(activity);
}
public long insert(String title, String body, String mediaType,
String priority, String departement, String dayDate, String time,
Boolean readUnread) {
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.TITLE, title);
contentValues.put(DBHelper.BODY, body);
contentValues.put(DBHelper.MEDIATYPE, mediaType);
contentValues.put(DBHelper.PRIORITY, priority);
contentValues.put(DBHelper.DEPARTEMENT, departement);
contentValues.put(DBHelper.DAYDATE, dayDate);
contentValues.put(DBHelper.TIME, time);
contentValues.put(DBHelper.READUNREAD, readUnread);
long id = db.insert(DBHelper.TABLE_NAME, null, contentValues);
return id;
}
public long update(String dataBaseId, String mTitle, String mBody,
String mMediaType, String mPriority, String mDepartement,
String mDayDate, String mTime, Boolean readUnread) {
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DBHelper.TITLE, mTitle);
contentValues.put(DBHelper.BODY, mBody);
contentValues.put(DBHelper.MEDIATYPE, mMediaType);
contentValues.put(DBHelper.PRIORITY, mPriority);
contentValues.put(DBHelper.DEPARTEMENT, mDepartement);
contentValues.put(DBHelper.DAYDATE, mDayDate);
contentValues.put(DBHelper.TIME, mTime);
contentValues.put(DBHelper.READUNREAD, readUnread);
ModelClass mc = null; //= new ModelClass();
String[] whereArgs = { dataBaseId };
long id = db.update(DBHelper.TABLE_NAME, contentValues, " _ID=?",
new String[] { String.valueOf(mc.getId())});
return id;
}}
class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "feeddatabase";
static final String TABLE_NAME = "FEEDTABLE";
private static final int DATABASE_VERSION = 1;
static final String TITLE = "Title";
static final String BODY = "Body";
static final String MEDIATYPE = "MediaType";
static final String PRIORITY = "Priority";
static final String DEPARTEMENT = "Departement";
static final String DAYDATE = "DayDate";
static final String TIME = "Time";
static final String READUNREAD = "ReadUnread";
// private static final String FLAG = "Flag";
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME
+ " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + TITLE
+ " VARCHAR(255), " + BODY + " VARCHAR(255)," + MEDIATYPE
+ " VARCHAR(255)," + PRIORITY + " VARCHAR(255)," + DEPARTEMENT
+ " VARCHAR(255)," + DAYDATE + " VARCHAR(255)," + TIME
+ " VARCHAR(255)," + READUNREAD + ");";
private Context context;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:1)
dataBaseId
始终是null
。您尚未对其进行更改,因此它始终进入if
条件并插入数据库而不是更新。
您要为其指定任何内容的行已被评论。