KiiObject Upload Picture to use for profile - java

I am a web dev and a couple of weeks ago I started trying to learn android studio and app dev. Im currently using kii cloud for my android app and I am currently trying to figure out how implement the following scenario --
a. I already have user registration, so I am currently working on a "edit profile" page.
b. On the edit profile page Im trying to create a button so that the user clicks on it and it will then open a fragment where the user can upload the image. link
c. Then attach that image to the url, and use the URL where needed such as a view profile page. linkenter link description here
EditUserProfile.java
public class EditUserProfile extends Activity {
Button picbutton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
picbutton = (Button) findViewById(R.id.MypicButton);
// Capture button clicks
picbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
FragmentManager fm = getFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragcon);
if(fragment == null)
fragment = new ProfilePic();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragcon, fragment);
ft.commit();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
ProfilePic.java (Fragment)
public class ProfilePic extends Fragment {
private static final String TAG = "ProfilePic";
String objectUri = null;
private static final int PICK_IMAGE = 1;
private Activity activity;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_attach_file, container,
false);
Bundle args = getArguments();
objectUri = args.getString("object_uri");
Button attachButton = (Button) view
.findViewById(R.id.attach_file_button);
attachButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onAttachFileButtonClicked(v);
}
});
setPageImage(3);
ImageView imageView = (ImageView) view.findViewById(R.id.details);
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = activity;
}
#Override
public void onDetach() {
super.onDetach();
this.activity = null;
}
public void onAttachFileButtonClicked(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {
Uri selectedFileUri = data.getData();
String filePath = getFilePathByUri(selectedFileUri);
Log.v(TAG, "Picture Path : " + filePath);
if (filePath == null) {
showAlert("File not exists, Please select an image that exists locally.");
return;
}
uploadFile(filePath);
} else {
showToast("picking file failed!");
}
}
private void showToast(String message) {
Toast.makeText(this.activity, message, Toast.LENGTH_SHORT).show();
}
private String getFilePathByUri(Uri selectedFileUri) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// Workaround of retrieving file image through ContentResolver
// for Android4.2 or later
String filePath = null;
FileOutputStream fos = null;
try {
Bitmap bmp = MediaStore.Images.Media.getBitmap(
this.activity.getContentResolver(), selectedFileUri);
String cacheDir = Environment.getExternalStorageDirectory()
.getAbsolutePath() + File.separator + "app";
File createDir = new File(cacheDir);
if (!createDir.exists()) {
createDir.mkdir();
}
filePath = cacheDir + File.separator + "upload.jpg";
File file = new File(filePath);
fos = new FileOutputStream(file);
bmp.compress(CompressFormat.JPEG, 95, fos);
fos.flush();
fos.getFD().sync();
} catch (Exception e) {
filePath = null;
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
// Nothing to do
}
}
}
return filePath;
} else {
String[] filePathColumn = { MediaStore.MediaColumns.DATA };
Cursor cursor = this.activity.getContentResolver().query(
selectedFileUri, filePathColumn, null, null, null);
if (cursor == null)
return null;
try {
if (!cursor.moveToFirst())
return null;
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
if (columnIndex < 0) {
return null;
}
String picturePath = cursor.getString(columnIndex);
return picturePath;
} finally {
cursor.close();
}
}
}
private void uploadFile(String path) {
KiiObject object = KiiObject.createByUri(Uri.parse(objectUri));
File f = new File(path);
Log.v(TAG, "file can read : " + f.canRead());
KiiUploader uploader = object.uploader(this.activity, f);
uploader.transferAsync(new KiiRTransferCallback() {
#Override
public void onStart(KiiRTransfer operator) {
setFragmentProgress(View.VISIBLE);
}
#Override
public void onTransferCompleted(KiiRTransfer operator, Exception e) {
setFragmentProgress(View.INVISIBLE);
if (e == null) {
} else {
}
}
});
}
public void moveFromDialogFragment(Class<?> clazz) {
if (clazz != null) {
Intent i = new Intent(this.activity, clazz);
startActivity(i);
}
}
void showAlert(String message) {
DialogFragment newFragment = AlertDialogFragment.newInstance(
R.string.operation_failed, message, null);
newFragment.show(getFragmentManager(), "dialog");
}
void setFragmentProgress(int v) {
ProgressFragment fragment = (ProgressFragment) getFragmentManager()
.findFragmentById(R.id.progressFragment);
if (fragment != null && fragment.isInLayout()) {
fragment.setProgressBarVisiblity(v);
}
}
void setPageImage(int page) {
ProgressFragment fragment = (ProgressFragment) getFragmentManager()
.findFragmentById(R.id.progressFragment);
if (fragment != null && fragment.isInLayout()) {
fragment.setPageImage(page);
}
}
}
Then for things like this, Im trying to find a way to dynamically show the profile pictures associated with the users, and if not use the icon as default.
holder.icon.setImageResource(R.drawable.list_account);
UserListLoader.java
public class UserListAdapter extends AbstractArrayAdapter<IUser> {
private final LayoutInflater inflater;
public UserListAdapter(Context context) {
super(context, R.layout.image_list_item);
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = this.inflater.inflate(R.layout.image_list_item, parent, false);
holder = new ViewHolder();
holder.text = (TextView)convertView.findViewById(R.id.row_text);
holder.icon = (ImageView)convertView.findViewById(R.id.row_icon);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
IUser user = this.getItem(position);
holder.position = position;
holder.text.setText(user.getUsername());
holder.icon.setImageResource(R.drawable.list_account);
return convertView;
}
}
Also when opening in app, the EditUserProfile crashes at
picbutton.setOnClickListener(new View.OnClickListener()
Any guidance or help on the matter is appreciated. Thanks.

I hope this helped someone...
public void uploadImage() {
UserFields userFields = new UserFields();
userFields.putDisplayName("AllDeals");
KiiUser.registerAsPseudoUser(userFields,
new KiiUserRegisterCallback() {
#Override
public void onRegisterCompleted(KiiUser kiiUser,
Exception exception) {
// TODO Auto-generated method stub
if (exception != null) {
// Error handling
Log.e("Exception", exception.toString());
return;
} else {
String accessToken = kiiUser.getAccessToken();
final KiiObject object = Kii.bucket("AllDeals")
.object();
object.set("placeImage", imageURL);
File localFile = new File(picturePath);
KiiUploader uploader = object.uploader(
getApplicationContext(), localFile);
uploader.transferAsync(new KiiRTransferCallback() {
public void onTransferCompleted(
KiiRTransfer operator,
Exception exception) {
if (exception != null) {
return;
}
object.publishBody(new KiiObjectPublishCallback() {
#Override
public void onPublishCompleted(
String url,
KiiObject object,
Exception exception) {
if (exception != null) {
return;
}
object.set("url", url);
object.save(new KiiObjectCallBack() {
public void onSaveCompleted(
int token,
KiiObject object,
Exception exception) {
if (exception != null) {
return;
}
Toast toast = Toast
.makeText(
MainActivity.this,
"Your image is added successfully",
500);
};
});
}
});
};
});
}
});
}

Related

Service not registered

I am trying to setup minimized player in my music player app after setup complete now facing this service not registered problem. When I try to play song it will happen again and again.
here is my code
public class PlayingBottomFragment extends Fragment implements ServiceConnection {
private static final String TAG = PlayingBottomFragment.class.getSimpleName();
RoundedImageView img_song_art;
ImageView img_next_song;
FloatingActionButton fab_pause_play;
TextView tv_song_name, tv_artist_name;
View view;
MusicService musicService;
public PlayingBottomFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_playing_bottom, container, false);
img_song_art = view.findViewById(R.id.img_song_art);
img_next_song = view.findViewById(R.id.img_next_song);
fab_pause_play = view.findViewById(R.id.fab_pause_play);
tv_song_name = view.findViewById(R.id.tv_song_name);
tv_artist_name = view.findViewById(R.id.tv_artist_name);
tv_song_name.setSelected(true);
img_next_song.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (musicService != null){
musicService.nextClicked();
if (getActivity() != null);{
MPPreferenceManager.setString(MPConstants.MUSIC_FILE, musicService.songsModels.get(musicService.position).getPath());
MPPreferenceManager.setString(MPConstants.SONG_NAME, musicService.songsModels.get(musicService.position).getTitle());
MPPreferenceManager.setString(MPConstants.ARTIST_NAME, musicService.songsModels.get(musicService.position).getArtist());
String path = MPPreferenceManager.getString(MPConstants.MUSIC_FILE, null);
String song = MPPreferenceManager.getString(MPConstants.SONG_NAME, null);
String artist = MPPreferenceManager.getString(MPConstants.ARTIST_NAME, null);
if (path != null){
SHOW_MINI_PLAYER = true;
PATH_TO_FLAG = path;
SONG_NAME_TO_FLAG = song;
ARTIST_TO_FLAG = artist;
}else{
SHOW_MINI_PLAYER = false;
PATH_TO_FLAG = null;
SONG_NAME_TO_FLAG = null;
ARTIST_TO_FLAG = null;
}
if (SHOW_MINI_PLAYER){
if (PATH_TO_FLAG != null){
byte[] art = getAlbumArt(PATH_TO_FLAG);
if (art != null) {
Glide.with(getContext()).load(art).into(img_song_art);
}else{
Glide.with(getContext()).load(R.drawable.profile).into(img_song_art);
}
tv_song_name.setText(SONG_NAME_TO_FLAG);
tv_artist_name.setText(ARTIST_TO_FLAG);
}
}
}
}
}
});
fab_pause_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
musicService.playPauseClicked();
if (musicService.isPlaying()){
fab_pause_play.setImageResource(R.drawable.ic_round_pause_24);
}else{
fab_pause_play.setImageResource(R.drawable.ic_round_play_arrow_24);
}
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
if (SHOW_MINI_PLAYER){
if (PATH_TO_FLAG != null){
byte[] art = getAlbumArt(PATH_TO_FLAG);
if (art != null) {
Glide.with(getContext()).load(art).into(img_song_art);
}else{
Glide.with(getContext()).load(R.drawable.profile).into(img_song_art);
}
Log.e(TAG, "onResume: path to flag: " + PATH_TO_FLAG );
Log.e(TAG, "onResume: path to flag: " + ARTIST_TO_FLAG );
tv_song_name.setText(SONG_NAME_TO_FLAG);
tv_artist_name.setText(ARTIST_TO_FLAG);
Intent intent = new Intent(getContext(), MusicService.class);
if (getContext() != null){
getContext().bindService(intent, this, Context.BIND_ABOVE_CLIENT);
}
}
}
}
#Override
public void onPause() {
super.onPause();
if (getContext() != null){
getContext().unbindService(this);
}
}
public byte[] getAlbumArt(String uri){
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(uri);
byte[] art = retriever.getEmbeddedPicture();
retriever.release();
return art;
}
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
MusicService.MyBinder binder = (MusicService.MyBinder) iBinder;
musicService = binder.getService();
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
musicService = null;
}
}
Here is my logcat image

How to allow multiple windows on webview to get facebook login working?

I'm creating an app for my website and need to when you click on external links like facebook and google login you get a new window tab that closes after login.
I`ve added mWebView.getSettings().setSupportMultipleWindows(true); but now when I click on the link nothing happens
MainFragment.java
public class MainFragment extends TaskFragment implements SwipeRefreshLayout.OnRefreshListener, AdvancedWebView.Listener {
private static final String ARGUMENT_URL = "url";
private static final String ARGUMENT_SHARE = "share";
private static final int REQUEST_FILE_PICKER = 1;
private boolean mProgress = false;
private View mRootView;
private StatefulLayout mStatefulLayout;
private AdvancedWebView mWebView;
private String mUrl = "about:blank";
private String mShare;
private boolean mLocal = false;
private ValueCallback<Uri> mFilePathCallback4;
private ValueCallback<Uri[]> mFilePathCallback5;
private int mStoredActivityRequestCode;
private int mStoredActivityResultCode;
private Intent mStoredActivityResultIntent;
public static MainFragment newInstance(String url, String share) {
MainFragment fragment = new MainFragment();
// arguments
Bundle arguments = new Bundle();
arguments.putString(ARGUMENT_URL, url);
arguments.putString(ARGUMENT_SHARE, share);
fragment.setArguments(arguments);
return fragment;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setRetainInstance(true);
// handle fragment arguments
Bundle arguments = getArguments();
if (arguments != null) {
handleArguments(arguments);
}
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int layout = WebViewAppConfig.PULL_TO_REFRESH == PullToRefreshMode.DISABLED ? R.layout.fragment_main : R.layout.fragment_main_swipeable;
mRootView = inflater.inflate(layout, container, false);
mWebView = mRootView.findViewById(R.id.main_webview);
return mRootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// restore webview state
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
}
// setup webview
setupView();
// pull to refresh
setupSwipeRefreshLayout();
// setup stateful layout
setupStatefulLayout(savedInstanceState);
// load data
if (mStatefulLayout.getState() == StatefulLayout.EMPTY) loadData();
// progress popup
showProgress(mProgress);
// check permissions
if (WebViewAppConfig.GEOLOCATION) {
PermissionUtility.checkPermissionAccessLocation(this);
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
mWebView.onResume();
}
#Override
public void onPause() {
super.onPause();
mWebView.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroyView() {
super.onDestroyView();
mRootView = null;
}
#Override
public void onDestroy() {
super.onDestroy();
mWebView.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(this)) {
// permitted
mWebView.onActivityResult(requestCode, resultCode, intent);
} else {
// not permitted
mStoredActivityRequestCode = requestCode;
mStoredActivityResultCode = resultCode;
mStoredActivityResultIntent = intent;
}
//handleFilePickerActivityResult(requestCode, resultCode, intent); // not used, used advanced webview instead
}
#Override
public void onSaveInstanceState(Bundle outState) {
// save current instance state
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
// stateful layout state
if (mStatefulLayout != null) mStatefulLayout.saveInstanceState(outState);
// save webview state
mWebView.saveState(outState);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// action bar menu
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_main, menu);
// show or hide share button
MenuItem share = menu.findItem(R.id.menu_main_share);
share.setVisible(mShare != null && !mShare.trim().equals(""));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// action bar menu behavior
switch (item.getItemId()) {
case R.id.menu_main_share:
IntentUtility.startShareActivity(getContext(), getString(R.string.app_name), getShareText(mShare));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PermissionUtility.REQUEST_PERMISSION_READ_EXTERNAL_STORAGE_AND_CAMERA:
case PermissionUtility.REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE:
case PermissionUtility.REQUEST_PERMISSION_ACCESS_LOCATION: {
// if request is cancelled, the result arrays are empty
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
// permission granted
if (requestCode == PermissionUtility.REQUEST_PERMISSION_READ_EXTERNAL_STORAGE_AND_CAMERA) {
// continue with activity result handling
if (mStoredActivityResultIntent != null) {
mWebView.onActivityResult(mStoredActivityRequestCode, mStoredActivityResultCode, mStoredActivityResultIntent);
mStoredActivityRequestCode = 0;
mStoredActivityResultCode = 0;
mStoredActivityResultIntent = null;
}
}
} else {
// permission denied
}
}
} else {
// all permissions denied
}
break;
}
}
}
#Override
public void onRefresh() {
runTaskCallback(new Runnable() {
#Override
public void run() {
refreshData();
}
});
}
#Override
public void onPageStarted(String url, Bitmap favicon) {
Logcat.d("");
}
#Override
public void onPageFinished(String url) {
Logcat.d("");
}
#Override
public void onPageError(int errorCode, String description, String failingUrl) {
Logcat.d("");
}
#Override
public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {
Logcat.d("");
if (PermissionUtility.checkPermissionWriteExternalStorage(MainFragment.this)) {
Toast.makeText(getActivity(), R.string.main_downloading, Toast.LENGTH_LONG).show();
DownloadUtility.downloadFile(getActivity(), url, DownloadFileUtility.getFileName(url));
}
}
#Override
public void onExternalPageRequest(String url) {
Logcat.d("");
}
public void refreshData() {
if (NetworkUtility.isOnline(getActivity()) || mLocal) {
// show progress popup
showProgress(true);
// load web url
String url = mWebView.getUrl();
if (url == null || url.equals("")) url = mUrl;
mWebView.loadUrl(url);
} else {
showProgress(false);
Toast.makeText(getActivity(), R.string.global_network_offline, Toast.LENGTH_LONG).show();
}
}
private void handleArguments(Bundle arguments) {
if (arguments.containsKey(ARGUMENT_URL)) {
mUrl = arguments.getString(ARGUMENT_URL);
mLocal = mUrl.contains("file://");
}
if (arguments.containsKey(ARGUMENT_SHARE)) {
mShare = arguments.getString(ARGUMENT_SHARE);
}
}
// not used, used advanced webview instead
private void handleFilePickerActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_FILE_PICKER) {
if (mFilePathCallback4 != null) {
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
if (result != null) {
String path = ContentUtility.getPath(getActivity(), result);
Uri uri = Uri.fromFile(new File(path));
mFilePathCallback4.onReceiveValue(uri);
} else {
mFilePathCallback4.onReceiveValue(null);
}
}
if (mFilePathCallback5 != null) {
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
if (result != null) {
String path = ContentUtility.getPath(getActivity(), result);
Uri uri = Uri.fromFile(new File(path));
mFilePathCallback5.onReceiveValue(new Uri[]{uri});
} else {
mFilePathCallback5.onReceiveValue(null);
}
}
mFilePathCallback4 = null;
mFilePathCallback5 = null;
}
}
private void loadData() {
if (NetworkUtility.isOnline(getActivity()) || mLocal) {
// show progress
if (WebViewAppConfig.PROGRESS_PLACEHOLDER) {
mStatefulLayout.showProgress();
} else {
mStatefulLayout.showContent();
}
// load web url
mWebView.loadUrl(mUrl);
} else {
mStatefulLayout.showOffline();
}
}
private void showProgress(boolean visible) {
// show pull to refresh progress bar
SwipeRefreshLayout contentSwipeRefreshLayout = mRootView.findViewById(R.id.container_content_swipeable);
SwipeRefreshLayout offlineSwipeRefreshLayout = mRootView.findViewById(R.id.container_offline_swipeable);
SwipeRefreshLayout emptySwipeRefreshLayout = mRootView.findViewById(R.id.container_empty_swipeable);
if (contentSwipeRefreshLayout != null) contentSwipeRefreshLayout.setRefreshing(visible);
if (offlineSwipeRefreshLayout != null) offlineSwipeRefreshLayout.setRefreshing(visible);
if (emptySwipeRefreshLayout != null) emptySwipeRefreshLayout.setRefreshing(visible);
mProgress = visible;
}
private void showContent(final long delay) {
final Handler timerHandler = new Handler();
final Runnable timerRunnable = new Runnable() {
#Override
public void run() {
runTaskCallback(new Runnable() {
public void run() {
if (getActivity() != null && mRootView != null) {
Logcat.d("timer");
mStatefulLayout.showContent();
}
}
});
}
};
timerHandler.postDelayed(timerRunnable, delay);
}
private void setupView() {
// webview settings
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.getSettings().setAppCachePath(getActivity().getCacheDir().getAbsolutePath());
mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setDatabaseEnabled(true);
mWebView.getSettings().setGeolocationEnabled(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(false);
mWebView.getSettings().setSupportMultipleWindows(true);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
// user agent
if (WebViewAppConfig.WEBVIEW_USER_AGENT != null && !WebViewAppConfig.WEBVIEW_USER_AGENT.equals("")) {
mWebView.getSettings().setUserAgentString(WebViewAppConfig.WEBVIEW_USER_AGENT);
}
// advanced webview settings
mWebView.setListener(getActivity(), this);
mWebView.setGeolocationEnabled(true);
// webview style
mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); // fixes scrollbar on Froyo
// webview hardware acceleration
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
// webview chrome client
View nonVideoLayout = getActivity().findViewById(R.id.main_non_video_layout);
ViewGroup videoLayout = getActivity().findViewById(R.id.main_video_layout);
View progressView = getActivity().getLayoutInflater().inflate(R.layout.placeholder_progress, null);
VideoEnabledWebChromeClient webChromeClient = new VideoEnabledWebChromeClient(nonVideoLayout, videoLayout, progressView, (VideoEnabledWebView) mWebView);
webChromeClient.setOnToggledFullscreen(new MyToggledFullscreenCallback());
mWebView.setWebChromeClient(webChromeClient);
//mWebView.setWebChromeClient(new MyWebChromeClient()); // not used, used advanced webview instead
// webview client
mWebView.setWebViewClient(new MyWebViewClient());
// webview key listener
mWebView.setOnKeyListener(new WebViewOnKeyListener((DrawerStateListener) getActivity()));
// webview touch listener
mWebView.requestFocus(View.FOCUS_DOWN); // http://android24hours.blogspot.cz/2011/12/android-soft-keyboard-not-showing-on.html
mWebView.setOnTouchListener(new WebViewOnTouchListener());
// webview scroll listener
//((RoboWebView) mWebView).setOnScrollListener(new WebViewOnScrollListener()); // not used
// admob
setupBannerView();
}
private void setupBannerView() {
if (WebViewAppConfig.ADMOB_UNIT_ID_BANNER != null && !WebViewAppConfig.ADMOB_UNIT_ID_BANNER.equals("") && NetworkUtility.isOnline(getActivity())) {
ViewGroup contentLayout = mRootView.findViewById(R.id.container_content);
AdMobUtility.createAdView(getActivity(), WebViewAppConfig.ADMOB_UNIT_ID_BANNER, AdSize.BANNER, contentLayout);
}
}
private void controlBack() {
if (mWebView.canGoBack()) mWebView.goBack();
}
private void controlForward() {
if (mWebView.canGoForward()) mWebView.goForward();
}
private void controlStop() {
mWebView.stopLoading();
}
private void controlReload() {
mWebView.reload();
}
private void setupStatefulLayout(Bundle savedInstanceState) {
// reference
mStatefulLayout = (StatefulLayout) mRootView;
// state change listener
mStatefulLayout.setOnStateChangeListener(new StatefulLayout.OnStateChangeListener() {
#Override
public void onStateChange(View view, #StatefulLayout.State int state) {
Logcat.d(String.valueOf(state));
// do nothing
}
});
// restore state
mStatefulLayout.restoreInstanceState(savedInstanceState);
}
private void setupSwipeRefreshLayout() {
SwipeRefreshLayout contentSwipeRefreshLayout = mRootView.findViewById(R.id.container_content_swipeable);
SwipeRefreshLayout offlineSwipeRefreshLayout = mRootView.findViewById(R.id.container_offline_swipeable);
SwipeRefreshLayout emptySwipeRefreshLayout = mRootView.findViewById(R.id.container_empty_swipeable);
if (WebViewAppConfig.PULL_TO_REFRESH == PullToRefreshMode.ENABLED) {
contentSwipeRefreshLayout.setOnRefreshListener(this);
offlineSwipeRefreshLayout.setOnRefreshListener(this);
emptySwipeRefreshLayout.setOnRefreshListener(this);
} else if (WebViewAppConfig.PULL_TO_REFRESH == PullToRefreshMode.PROGRESS) {
contentSwipeRefreshLayout.setDistanceToTriggerSync(Integer.MAX_VALUE);
offlineSwipeRefreshLayout.setDistanceToTriggerSync(Integer.MAX_VALUE);
emptySwipeRefreshLayout.setDistanceToTriggerSync(Integer.MAX_VALUE);
}
}
private String getShareText(String text) {
if (mWebView != null) {
if (mWebView.getTitle() != null) {
text = text.replaceAll("\\{TITLE\\}", mWebView.getTitle());
}
if (mWebView.getUrl() != null) {
text = text.replaceAll("\\{URL\\}", mWebView.getUrl());
}
}
return text;
}
private boolean isLinkExternal(String url) {
for (String rule : WebViewAppConfig.LINKS_OPENED_IN_EXTERNAL_BROWSER) {
if (url.contains(rule)) return true;
}
return false;
}
private boolean isLinkInternal(String url) {
for (String rule : WebViewAppConfig.LINKS_OPENED_IN_INTERNAL_WEBVIEW) {
if (url.contains(rule)) return true;
}
return false;
}
// not used, used advanced webview instead
private class MyWebChromeClient extends WebChromeClient {
#Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(MainFragment.this)) {
mFilePathCallback5 = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_FILE_PICKER);
return true;
}
return false;
}
#Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
}
public void openFileChooser(ValueCallback<Uri> filePathCallback) {
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(MainFragment.this)) {
mFilePathCallback4 = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_FILE_PICKER);
}
}
public void openFileChooser(ValueCallback<Uri> filePathCallback, String acceptType) {
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(MainFragment.this)) {
mFilePathCallback4 = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_FILE_PICKER);
}
}
public void openFileChooser(ValueCallback<Uri> filePathCallback, String acceptType, String capture) {
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(MainFragment.this)) {
mFilePathCallback4 = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_FILE_PICKER);
}
}
}
private class MyToggledFullscreenCallback implements VideoEnabledWebChromeClient.ToggledFullscreenCallback {
#Override
public void toggledFullscreen(boolean fullscreen) {
if (fullscreen) {
WindowManager.LayoutParams attrs = getActivity().getWindow().getAttributes();
attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
attrs.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
getActivity().getWindow().setAttributes(attrs);
getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
} else {
WindowManager.LayoutParams attrs = getActivity().getWindow().getAttributes();
attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
attrs.flags &= ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
getActivity().getWindow().setAttributes(attrs);
getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
}
}
private class MyWebViewClient extends WebViewClient {
private boolean mSuccess = true;
#Override
public void onPageFinished(final WebView view, final String url) {
runTaskCallback(new Runnable() {
public void run() {
if (getActivity() != null && mSuccess) {
showContent(500); // hide progress bar with delay to show webview content smoothly
showProgress(false);
if (WebViewAppConfig.ACTION_BAR_HTML_TITLE) {
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(view.getTitle());
}
CookieSyncManager.getInstance().sync(); // save cookies
}
mSuccess = true;
}
});
}
#SuppressWarnings("deprecation")
#Override
public void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl) {
runTaskCallback(new Runnable() {
public void run() {
if (getActivity() != null) {
mSuccess = false;
mStatefulLayout.showEmpty();
showProgress(false);
}
}
});
}
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
// forward to deprecated method
onReceivedError(view, error.getErrorCode(), error.getDescription().toString(), request.getUrl().toString());
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (DownloadFileUtility.isDownloadableFile(url)) {
if (PermissionUtility.checkPermissionWriteExternalStorage(MainFragment.this)) {
Toast.makeText(getActivity(), R.string.main_downloading, Toast.LENGTH_LONG).show();
DownloadUtility.downloadFile(getActivity(), url, DownloadFileUtility.getFileName(url));
return true;
}
return true;
} else if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
// load url listener
((LoadUrlListener) getActivity()).onLoadUrl(url);
// determine for opening the link externally or internally
boolean external = isLinkExternal(url);
boolean internal = isLinkInternal(url);
if (!external && !internal) {
external = WebViewAppConfig.OPEN_LINKS_IN_EXTERNAL_BROWSER;
}
// open the link
if (external) {
IntentUtility.startWebActivity(getContext(), url);
return true;
} else {
showProgress(true);
return false;
}
} else if (url != null && url.startsWith("file://")) {
// load url listener
((LoadUrlListener) getActivity()).onLoadUrl(url);
return false;
} else {
return IntentUtility.startIntentActivity(getContext(), url);
}
}
}
}

Show Capture images and gallary images in Recyclerview

I am trying to show Camera capture images and gallary images in Recyclerview. It works fine but when I capture a second image or select from gallary it replaces the first image in Recyclerview. I want to show all images in Recyclerview that I have selected or captured from camera.
Activity code:
public void ShowDialog() {
final Dialog dialog = new Dialog(AttachDisputeDocActivity.this, android.R.style.Theme_Translucent_NoTitleBar);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.rc_img_dialog_layt);
WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
layoutParams.gravity = Gravity.BOTTOM;
layoutParams.dimAmount = 0.5f;
dialog.getWindow().setAttributes(layoutParams);
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
RelativeLayout UploadImage = dialog.findViewById(R.id.rela_upload);
RelativeLayout TakeCamera = dialog.findViewById(R.id.rela_camera);
UploadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (ActivityCompat.checkSelfPermission(AttachDisputeDocActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(AttachDisputeDocActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, DspConstant.REQUEST_GALLARY_IMAGE);
} else {
gallaryintent();
}
} catch (Exception e) {
e.printStackTrace();
}
dialog.dismiss();
}
});
dialog.show();
TakeCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (ActivityCompat.checkSelfPermission(AttachDisputeDocActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(AttachDisputeDocActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, DspConstant.REQUEST_CAPTURE_IMAGE);
} else {
openCameraIntent();
}
} catch (Exception e) {
e.printStackTrace();
}
dialog.dismiss();
}
});
}
private void openCameraIntent() {
Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
pictureIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (pictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID+".fileprovider", photoFile);
pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(pictureIntent, DspConstant.REQUEST_CAPTURE_IMAGE);
}
}
}
private void gallaryintent() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent .setType("image/*");
startActivityForResult(galleryIntent, DspConstant.REQUEST_GALLARY_IMAGE);
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "IMG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
imagefilepath = image.getAbsolutePath();
return image;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == DspConstant.REQUEST_GALLARY_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
loadRecyclerView(picturePath);
} else if (requestCode == DspConstant.REQUEST_CAPTURE_IMAGE && requestCode == RESULT_OK && null != data) {
loadRecyclerView(imagefilepath);
}
}
private void loadRecyclerView(String image) {
documentlist.add(image);
attachDocAdapter = new AttachDocAdapter(this, documentlist);
recyclerView.setAdapter(attachDocAdapter);
attachDocAdapter.updateList(documentlist);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case DspConstant.REQUEST_GALLARY_IMAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
gallaryintent();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
break;
case DspConstant.REQUEST_CAPTURE_IMAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCameraIntent();
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
break;
}
}
Adapter Code:
public class AttachDocAdapter extends RecyclerView.Adapter<AttachDocAdapter.MyViewHolder> {
private ArrayList<String> imageslist=new ArrayList<>();
private Activity activity;
public AttachDocAdapter(Activity activity,ArrayList<String> imageslist)
{
this.activity=activity;
this.imageslist=imageslist;
}
public class MyViewHolder extends RecyclerView.ViewHolder{
ImageView img_document;
CitiTextView txt_deleteimage;
public MyViewHolder(View itemView) {
super(itemView);
img_document=itemView.findViewById(R.id.img_document);
txt_deleteimage=itemView.findViewById(R.id.txt_delete);
}
}
#Override
public AttachDocAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemview= LayoutInflater.from(parent.getContext()).inflate(R.layout.rc_img_attach_layout,parent,false);
return new MyViewHolder(itemview);
}
#Override
public void onBindViewHolder(AttachDocAdapter.MyViewHolder holder, int position) {
Glide.with(activity).load(imageslist.get(position)).into(holder.img_document);
holder.txt_deleteimage.setOnClickListener(view -> removeItem(holder.getAdapterPosition()));
}
#Override
public int getItemCount() {
if (imageslist==null)
{
return 0;
}return imageslist.size();
}
public void updateList(ArrayList<String> imageslist) {
this.imageslist = imageslist;
notifyDataSetChanged();
}
public void removeItem(int position) {
imageslist.remove(position);
notifyItemRemoved(position);
}
}
And when I click on TakeCamera nothing happens on the Samsung S5.

Class variable not changing in IF or Switch statements

Seems simple, but I can't get it to work. I have a public class string variable that should change within a if or switch statement. I haven't declared the variable inside the statement so it should change given the scope, no? But it only reads "FROM" and when I do go to change it in the if statement that applies, it does change to "TO" but only in that instance and reverts back to "FROM". I would pass it along the methods, but the full code is more cluttered and I don't think it's possible to do so.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
String typeOfText = "FROM";
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantRequest) {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.faboptions_favorite) {
Toast.makeText(MainActivity.this, "FROM", Toast.LENGTH_SHORT).show();
typeOfText = "FROM";
cameraSource.takePicture(null, new CameraSource.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes) {
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
cropPicFile(bmp);
}
});
} else if (view.getId() == R.id.faboptions_textsms) {
Toast.makeText(MainActivity.this, "TO", Toast.LENGTH_SHORT).show();
typeOfText = "TO";
Log.d("VARIABLE","" + typeOfText);
cameraSource.takePicture(null, new CameraSource.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes) {
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
cropPicFile(bmp);
}
});
} else {
typeOfText = "FROM";
Toast.makeText(MainActivity.this, "Share", Toast.LENGTH_SHORT).show();
createDialogSaveInfo();
}
}
private void createDialogSaveInfo() {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.dialog_confirm_address_scan);
//Establish Dialog Views
Button submit = (Button) dialog.findViewById(R.id.button_dialog_scanner_submit);
Button cancel = (Button) dialog.findViewById(R.id.button_dialog_scanner_cancel);
final EditText fromEditText = (EditText) dialog.findViewById(R.id.editText_dialog_scanner_from);
final EditText toEditText = (EditText) dialog.findViewById(R.id.editText_dialog_scanner_to);
//Set text from captured strings in surface view
fromEditText.setText(fromAddress);
toEditText.setText(toAddress);
//Setup listeners
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO save info to realm
saveLabelInfoIntoRealm(fromEditText.getText().toString(), toEditText.getText().toString());
dialog.dismiss();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
private void saveLabelInfoIntoRealm(final String from, final String to) {
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Package userPackage = realm.createObject(Package.class, 0);
userPackage.setFromAddress(from);
userPackage.setToAddress(to);
}
});
}
private int getPrimaryKey() {
try {
return realm.where(Package.class).max("primaryKey").intValue() + 1;
} catch (ArrayIndexOutOfBoundsException e) {
return 0;
}
}
private void configureListeners() {
fabOptions.setOnClickListener(this);
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
if (path == null) {
Log.d("TAG", "" + path.toString());
}
return Uri.parse(path);
}
private void cropPicFile(Bitmap file) {
Uri imageToCrop = getImageUri(this, file);
CropImage.activity(imageToCrop)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri photo = result.getUri();
readImage(photo);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void readImage(Uri photo) {
StringBuilder stringBuilder = new StringBuilder();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photo);
Frame imageFrame = new Frame.Builder()
.setBitmap(bitmap)
.build();
final SparseArray<TextBlock> items = textRecognizer.detect(imageFrame);
for (int i = 0; i < items.size(); i++) {
TextBlock item = items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
Log.d("VARIABLE","" + typeOfText);
if (typeOfText.equals("FROM")) {
fromAddress = stringBuilder.toString();
} else if (typeOfText.equals("TO")){
toAddress = stringBuilder.toString();
}
}
}
The reason the code keeps reverting is because the call to readImage() is in onActivityResult() which recreates the activity when called. So basically, you are getting a fresh object, and the onTypeText() is reinitialized. onActivityResult() is basically a callback from your previous activity.
Your onClick() is not being called due you don't assign clicklistener to R.id.faboptions_favorite and the other View
in onCreate add :
findViewById(R.id.faboptions_favorite).setOnClickListener(this);
and same for the other view.

Creating Object: Exception Caught in onSaveCompleted

I followed the Kii Cloud tutorial on creating and archieving an object, and tried to implement it to my own app. What it basically does is, when user clicks on the "existingButton", it opens a new activity where user can pick an image from the gallery and upload it. I'm facing no issues on the second activity, yet the uri from the first activity comes as "null" to the second activity and I'm getting a NullPointerException eventually, since I'm trying to parse a null String. I examined this issue through debugger and found out that the problem is in the first activity's "onSaveCompleted" method. The if (exception == null) condition is not met, which basically means that I'm getting some kind of an exception, I guess. Then, if (exception instanceof CloudExecutionException) condition is not met, too. As a result, it shows the Toast of the else condition of my main if. Code is below. Thanks for any help guys.
First Activity:
public class SendNotePreActivity extends AppCompatActivity {
public static final String APP_BUCKET_NAME = "tutorial";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_note_pre);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button existingButton = (Button) findViewById(R.id.existingButton);
existingButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
KiiBucket bucket = Kii.bucket(APP_BUCKET_NAME);
KiiObject object = bucket.object();
object.set("deneme", 313131);
object.save(new KiiObjectCallBack() {
#Override
public void onSaveCompleted(int token, #NonNull KiiObject object,
Exception exception) {
if (exception == null) {
final String uri = object.toUri().toString();
SharedPreferences.Editor mEditor = getSharedPreferences("args", MODE_PRIVATE).edit();
mEditor.putString("uri", uri);
mEditor.apply();
Toast.makeText(SendNotePreActivity.this, "SUCCESSFUL", Toast.LENGTH_LONG).show();
} else {
if (exception instanceof CloudExecutionException) {
Toast.makeText(SendNotePreActivity.this, "Please choose an image", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(SendNotePreActivity.this, "Please choose an image222", Toast.LENGTH_LONG).show();
}
}
}
});
Intent intent = new Intent(SendNotePreActivity.this, SendNoteActivity.class);
startActivity(intent);
}
});
}
}
Second Activity:
public class SendNoteActivity extends AppCompatActivity {
ImageView imagePreview;
private static final int PICK_IMAGE = 1;
String filePath = null;
String objectUri = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_note);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
imagePreview = (ImageView) findViewById(R.id.imagePreview);
Button chooseButton = (Button) findViewById(R.id.chooseButton);
chooseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Note"), PICK_IMAGE);
}
});
Button sendButton = (Button) findViewById(R.id.sendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (filePath == null) {
Toast.makeText(SendNoteActivity.this, "Please choose an image", Toast.LENGTH_LONG).show();
} else {
uploadFile(filePath);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK && data != null) {
Uri selectedFileUri = data.getData();
imagePreview.setImageURI(selectedFileUri);
filePath = getFilePathByUri(selectedFileUri);
if (filePath == null) {
Toast.makeText(SendNoteActivity.this, "File does not exist", Toast.LENGTH_LONG).show();
return;
}
} else {
super.onActivityResult(requestCode, resultCode, data);
Toast.makeText(SendNoteActivity.this, "Picking failed", Toast.LENGTH_SHORT).show();
}
}
private String getFilePathByUri(Uri selectedFileUri) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// Workaround of retrieving file image through ContentResolver
// for Android4.2 or later
String filePath = null;
FileOutputStream fos = null;
try {
Bitmap bmp = MediaStore.Images.Media.getBitmap(
SendNoteActivity.this.getContentResolver(), selectedFileUri);
String cacheDir = Environment.getExternalStorageDirectory()
.getAbsolutePath() + File.separator + "tutorialapp";
File createDir = new File(cacheDir);
if (!createDir.exists()) {
createDir.mkdir();
}
filePath = cacheDir + File.separator + "upload.jpg";
File file = new File(filePath);
fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 95, fos);
fos.flush();
fos.getFD().sync();
} catch (Exception e) {
filePath = null;
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
// Nothing to do
}
}
}
return filePath;
} else {
String[] filePathColumn = { MediaStore.MediaColumns.DATA };
Cursor cursor = SendNoteActivity.this.getContentResolver().query(
selectedFileUri, filePathColumn, null, null, null);
if (cursor == null)
return null;
try {
if (!cursor.moveToFirst())
return null;
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
if (columnIndex < 0) {
return null;
}
String picturePath = cursor.getString(columnIndex);
return picturePath;
} finally {
cursor.close();
}
}
}
private void uploadFile(String path) {
SharedPreferences prefs = getSharedPreferences("args", MODE_PRIVATE);
objectUri = prefs.getString("uri", "OLMADI AQ");
KiiObject object = KiiObject.createByUri(Uri.parse(objectUri));
File f = new File(path);
KiiUploader uploader = object.uploader(SendNoteActivity.this, f);
uploader.transferAsync(new KiiRTransferCallback() {
#Override
public void onStart(KiiRTransfer operator) {
}
#Override
public void onTransferCompleted(KiiRTransfer operator, Exception e) {
if (e == null) {
Toast.makeText(SendNoteActivity.this, "Successful", Toast.LENGTH_LONG).show();
} else {
Throwable cause = e.getCause();
if (cause instanceof CloudExecutionException)
Toast.makeText(SendNoteActivity.this, "Error", Toast.LENGTH_LONG).show();
else
Toast.makeText(SendNoteActivity.this, "Error2", Toast.LENGTH_LONG).show();
}
}
});
}
}
log:
FATAL EXCEPTION: main
Process: com.theoc.proto, PID: 8050
java.lang.NullPointerException: uriString
at android.net.Uri$StringUri.<init>(Uri.java:470)
at android.net.Uri$StringUri.<init>(Uri.java:460)
at android.net.Uri.parse(Uri.java:432)
at com.theoc.proto.SendNoteActivity.uploadFile(SendNoteActivity.java:163)
at com.theoc.proto.SendNoteActivity.access$000(SendNoteActivity.java:44)
at com.theoc.proto.SendNoteActivity$2.onClick(SendNoteActivity.java:82)
at android.view.View.performClick(View.java:4763)
at android.view.View$PerformClick.run(View.java:19821)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
Move startActivity into onSaveCompleted, because now you start the 2nd activity before save is finishec

Categories

Resources