public class PrivateActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, CardView.OnClickListener {
private static Database db;
private ListView privateDocs;
private CardView Upload;
final int ACTIVITY_CHOOSE_FILE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_private);
try {
db = Database.newInstance();
fillListWithDocuments();
} catch (Exception ex) {
Toast.makeText(this, "Error: " + ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
private void fillListWithDocuments() throws Exception {
ArrayList<PrivateFile> privateDoc = db.getAllPrivateFiles(Database.getCurLoggedInStudent().getVisitedClass().getRoomNr());
ArrayAdapter<PrivateFile> arrayAdapter = new ArrayAdapter<PrivateFile>(
this,
android.R.layout.simple_list_item_1,
privateDoc);
privateDocs.setAdapter(arrayAdapter);
}
@Override
public void onClick(View v) {
try {
switch (v.getId()) {
case R.id.btnUpload: {
Intent chooseFile;
Intent intent;
chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("*/*");
intent = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
}
}
} catch (Exception ex) {
Toast.makeText(this, "Error caused by uploading file: " + ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTIVITY_CHOOSE_FILE: {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
try {
byte[] inputData = getBytes(getContentResolver().openInputStream(uri));
PrivateFile pf = new PrivateFile(1,inputData);
db.addPrivateFile(pf);
fillListWithDocuments(); //refreshing table
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
}
所以我有一个带有列表视图和按钮的活动。 listview显示使用Upload
按钮上传到我的sql数据库的文件的列表。代码运行完美,我苦苦挣扎的唯一问题是添加文件后,列表视图将不会刷新。我总是需要关闭我的活动并重新开始。我还尝试过重新加载该活动,但无法正常工作。
PS:数据库只是调用Web服务功能的类。我只显示了相关的代码片段。