我想在片段中为我的列表视图添加刷卡刷新,但它似乎无法正常工作,因为它根本不更新我的列表视图。以下是我的活动的工作方式:
PictureFragment
图片列表(listview)
显示。 UploadImageActivity
以添加图片。 UploadImageActivity
将关闭,用户现在返回PictureFragment
(尚未更新其最新图片上传)。 希望善良的灵魂能帮助我解决这个问题。
public class PictureFragment extends Fragment {
private ListView listView;
private int smiley_id;
private String title, date, caption, image;
private ImageButton addPicButton;
private SwipeRefreshLayout swipeRefreshLayout;
private PictureAdapter adapter;
private TableDatabase tableDatabase;
private Cursor cursor;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_picture, container, false);
// Set listview
listView = (ListView) rootView.findViewById(R.id.piclistView);
adapter = new PictureAdapter(getActivity().getApplicationContext(), R.layout.row_feed);
listView.setAdapter(adapter);
// Retrieve data from database
tableDatabase = new TableDatabase(getActivity());
// Get rows of database
cursor = tableDatabase.getInformation(tableDatabase);
// Start from the last so that listview displays latest image first
// Check for existing rows
if(cursor.moveToLast()) {
do {
// Get items from each column
smiley_id = cursor.getInt(0);
title = cursor.getString(1);
date = cursor.getString(2);
caption = cursor.getString(3);
image = cursor.getString(4);
// Saves images added by user into listview
PictureItem pictureItem = new PictureItem(smiley_id, title, date, caption, image);
adapter.add(pictureItem);
} while (cursor.moveToPrevious());
}
// Swipe on refresh
swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh);
swipeRefreshLayout.setEnabled(false);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
(new Handler()).postDelayed(new Runnable() {
@Override
public void run() {
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
}, 1000);
}
});
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if(firstVisibleItem == 0) swipeRefreshLayout.setEnabled(true);
else swipeRefreshLayout.setEnabled(false);
}
});
// Lead user to UploadImageActivity to insert image to listview
addPicButton = (ImageButton) rootView.findViewById(R.id.addPictureButton);
addPicButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getActivity().getApplicationContext(), UploadImageActivity.class));
}
});
return rootView;
}
UploadImageActivity.java
public class UploadImageActivity extends ActionBarActivity implements View.OnClickListener{
private Calendar cal = Calendar.getInstance();
private SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMM yyyy, EEE @ hh:mm a");
EditText pic_title, pic_caption;
ImageView picture;
Button smiley1, smiley2, smiley3, smiley4, smiley5, selected_smiley;
// To store in database
int smiley_id = R.drawable.smile1; // Set default smiley as first smiley if not chosen
String title, date, caption;
String uriPicture; // Save uri in string format to store image as text format in database
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_picture);
// Removes shadow under action bar
getSupportActionBar().setElevation(0);
pic_title = (EditText) findViewById(R.id.picture_title);
pic_caption = (EditText) findViewById(R.id.picture_caption);
picture = (ImageView) findViewById(R.id.imagebutton);
smiley1 = (Button) findViewById(R.id.button1);
smiley2 = (Button) findViewById(R.id.button2);
smiley3 = (Button) findViewById(R.id.button3);
smiley4 = (Button) findViewById(R.id.button4);
smiley5 = (Button) findViewById(R.id.button5);
selected_smiley = (Button) findViewById(R.id.select_smiley);
picture.setOnClickListener(this);
smiley1.setOnClickListener(this);
smiley2.setOnClickListener(this);
smiley3.setOnClickListener(this);
smiley4.setOnClickListener(this);
smiley5.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_event, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_ok) {
title = pic_title.getText().toString();
date = dateFormatter.format(cal.getTime());
caption = pic_caption.getText().toString();
// Do not save data
if(title.isEmpty()) {
alertUser("Upload failed!", "Please enter title.");
}
else if(caption.isEmpty()) {
alertUser("Upload failed!", "Please enter caption.");
}
else if(uriPicture.isEmpty()) {
alertUser("Upload failed!", "Please upload an image.");
}
// Save data when title, caption and image are not empty
else {
// Add information into database
TableDatabase tableDatabase = new TableDatabase(this);
tableDatabase.putInformation(tableDatabase, smiley_id, title, date, caption, uriPicture);
Toast.makeText(getBaseContext(), "Details successfully saved", Toast.LENGTH_LONG).show();
finish();
}
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
switch(v.getId()) {
// Show the image picked by user
case R.id.imagebutton:
picture.setImageDrawable(null);
Crop.pickImage(this);
break;
// Saves the user's smiley choice
case R.id.button1:
selected_smiley.setBackgroundResource(R.drawable.smile1);
selected_smiley.setText("");
setSmileyID(R.drawable.smile1);
break;
case R.id.button2:
selected_smiley.setBackgroundResource(R.drawable.smile2);
selected_smiley.setText("");
setSmileyID(R.drawable.smile2);
break;
case R.id.button3:
selected_smiley.setBackgroundResource(R.drawable.smile3);
selected_smiley.setText("");
setSmileyID(R.drawable.smile3);
break;
case R.id.button4:
selected_smiley.setBackgroundResource(R.drawable.smile4);
selected_smiley.setText("");
setSmileyID(R.drawable.smile4);
break;
case R.id.button5:
selected_smiley.setBackgroundResource(R.drawable.smile5);
selected_smiley.setText("");
setSmileyID(R.drawable.smile5);
break;
default:
break;
}
}
// This method sets the smiley ID according to what the user picks.
private void setSmileyID(int smileyID) {
this.smiley_id = smileyID;
}
// This method calls alert dialog to inform users a message.
private void alertUser(String title, String message) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(UploadImageActivity.this);
dialogBuilder.setTitle(title);
dialogBuilder.setMessage(message);
dialogBuilder.setPositiveButton("Ok", null);
dialogBuilder.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) {
beginCrop(data.getData());
} else if(requestCode == Crop.REQUEST_CROP) {
handleCrop(resultCode, data);
}
}
// This method allows users to crop image in square.
private void beginCrop(Uri source) {
Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
Crop.of(source, destination).asSquare().start(this);
}
// This method ensures there are no errors in cropping.
private void handleCrop(int resultCode, Intent result) {
if(resultCode == RESULT_OK) {
picture.setImageURI(Crop.getOutput(result));
uriPicture = Crop.getOutput(result).toString();
} else if(resultCode == Crop.RESULT_ERROR) {
Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
}
}
TableDatabase.java
public class TableDatabase extends SQLiteOpenHelper {
public String query = "CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" +
TableData.TableInfo.SMILEY + " INTEGER NOT NULL, " +
TableData.TableInfo.TITLE + " TEXT, " +
TableData.TableInfo.DATE + " TEXT, " +
TableData.TableInfo.CAPTION + " TEXT, " +
TableData.TableInfo.IMAGE + " TEXT);";
public TableDatabase(Context context) {
super(context, TableData.TableInfo.DATABASE_NAME, null, TableData.TableInfo.DATABASE_VERSION);
// Check if database is created
Log.d("Database operations", "Database created");
}
@Override
public void onCreate(SQLiteDatabase db) {
// Create table
db.execSQL(query);
Log.d("Database operations", "Table created");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// Insert user information into the database
public void putInformation(TableDatabase data, int smiley, String title, String date, String caption, String image) {
// Write data into database
SQLiteDatabase sqLiteDatabase = data.getWritableDatabase();
ContentValues contentValues = new ContentValues();
// Add value from each column into contentvalue
contentValues.put(TableData.TableInfo.SMILEY, smiley);
contentValues.put(TableData.TableInfo.TITLE, title);
contentValues.put(TableData.TableInfo.DATE, date);
contentValues.put(TableData.TableInfo.CAPTION, caption);
contentValues.put(TableData.TableInfo.IMAGE, image);
// Insert into sqlite database
sqLiteDatabase.insert(TableData.TableInfo.TABLE_NAME, null, contentValues);
Log.d("Database operations", "One row inserted");
}
// Retrieve data from database
public Cursor getInformation(TableDatabase data) {
// Read data from sqlite database
SQLiteDatabase sqLiteDatabase = data.getReadableDatabase();
String[] columns = { TableData.TableInfo.SMILEY, TableData.TableInfo.TITLE, TableData.TableInfo.DATE, TableData.TableInfo.CAPTION, TableData.TableInfo.IMAGE };
// Points to first row of table
return sqLiteDatabase.query(TableData.TableInfo.TABLE_NAME, columns, null, null, null, null, null);
}