I have this code, but not because it works, it keeps opening in webview and what I want is that the links do not belong to my website open in default browser. Any idea?
Can someone tell me if it's possible and how to do it? Thank you very much!
package com.example.webviewapp;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.MimeTypeMap;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
public class MainActivity extends Activity {
private WebView mainWebView;
private String HomeUrl, AppName, ShareUrl, AD_ID, sdrUrl, ext;
private VideoView mVideoView;
private RelativeLayout mContentView;
private FrameLayout mCustomViewContainer;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
private AdView adView;
Integer vidPosition;
ProgressBar progressBar;
#SuppressWarnings("deprecation")
#SuppressLint({"CutPasteId","NewApi", "SetJavaScriptEnabled"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ========================Create adView
AD_ID = getString(R.string.admob_publisher_id);
adView = new AdView(this, AdSize.BANNER, AD_ID);
/* // Dynamic add LinearLayout
// android:id="#+id/adLayout"
LinearLayout layout = (LinearLayout)findViewById(R.id.adLayout);
// Add adView
layout.addView(adView);*/
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
//========================== home url
HomeUrl = getString(R.string.base_url);
//First share link
ShareUrl = HomeUrl;
// App name url
AppName = getString(R.string.app_name);
//Find objects with ID
mainWebView = (WebView) findViewById(R.id.webView1);
progressBar = (ProgressBar)findViewById(R.id.progressBar1);
// focus with touch
mainWebView.setFocusable(true);
mainWebView.setFocusableInTouchMode(true);
mainWebView.requestFocus(View.FOCUS_DOWN|View.FOCUS_UP);
mainWebView.getSettings().setLightTouchEnabled(true);
// enabled Java Script
mainWebView.getSettings().setJavaScriptEnabled(true);
mainWebView.getSettings().setPluginState(PluginState.ON_DEMAND);
mainWebView.getSettings().setDomStorageEnabled(true);
//mainWebView.getSettings().setUseWideViewPort(true);
//Customaze Web View
mainWebView.setWebViewClient(new MyCustomWebViewClient());
mainWebView.setWebChromeClient(new MyChromeClient());
//Webview scroll
mainWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
//Cache enable
mainWebView.getSettings().setAppCacheEnabled(true);
mainWebView.getSettings().setRenderPriority(RenderPriority.HIGH);
// Load Home url
mainWebView.loadUrl(HomeUrl);
mainWebView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
if (!v.hasFocus()) {
v.requestFocus();
v.requestFocusFromTouch();
}
break;
}
return false;
}
});
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("url");
//mainWebView.getSettings().setUseWideViewPort(true);
mainWebView.loadUrl(value);
}
// Menu category
TextView text1= (TextView) findViewById(R.id.title_bar_home);
text1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mainWebView.loadUrl(HomeUrl);
}
});
// Menu category
TextView text2= (TextView) findViewById(R.id.title_bar_share);
text2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, ShareUrl);
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Interesting for you!");
startActivity(Intent.createChooser(intent, "Share via"));
}
});
}
private class MyCustomWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
// On load Spinner visible
progressBar.setVisibility(View.VISIBLE);
view.setVisibility(View.GONE);
}
//#SuppressWarnings("deprecation")
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
// On load Spinner hide
progressBar.setVisibility(View.GONE);
view.setVisibility(View.VISIBLE);
}
#SuppressLint("NewApi")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//share page or link
ShareUrl = url;
// One touch call link Call
if (url.startsWith("tel:"))
{
Intent intent = new Intent(Intent.ACTION_DIAL,
Uri.parse(url));
startActivity(intent);
}
else
// One touch sms link Sms
if (url.startsWith("sms:"))
{
Intent message = new Intent(Intent.ACTION_SENDTO,
Uri.parse(url));
startActivity(message);
}
// One share text or url link share text
else
if (url.startsWith("share:"))
{
String[] share_link = url.split(":");
try {
String ID= URLDecoder.decode(share_link[1], "UTF-8");
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "http://www.youtube.com/watch?v="+ID);
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Interesting for you!");
startActivity(Intent.createChooser(intent, "Share via"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// One touch image link Image
else
if(url.endsWith(".jpg") || url.endsWith(".png") || url.endsWith(".gif") || url.endsWith(".JPG") || url.endsWith(".jpeg") )
{
Intent intent=new Intent (MainActivity.this, Image.class);
intent.putExtra("href", url);
startActivity(intent);
}
else
// else if it's a 3GP file link
if(url.endsWith(".3gp")){
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "video/3gp");
startActivity(intent);
return true;
}
else
//Link mp4 file Download mp4
if(url.endsWith(".mp4")){
if(url.startsWith("download")){
String[] download_link = url.split(":");
try {
//Download mp4
sdrUrl= URLDecoder.decode(download_link[1], "UTF-8")+":"+URLDecoder.decode(download_link[2], "UTF-8");
ext = MimeTypeMap.getFileExtensionFromUrl(sdrUrl);
if (ext != null) {
MimeTypeMap mime = MimeTypeMap.getSingleton();
String mimeType = mime.getMimeTypeFromExtension(ext);
if (mimeType != null) {
if (ext.toLowerCase().contains("mp4")) {
DownloadManager mdDownloadManager = (DownloadManager) MainActivity.this
.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(sdrUrl));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
request.setAllowedOverRoaming(true);
File destinationFile = new File(
Environment.getExternalStorageDirectory(),
getFileName(sdrUrl, ext));
request.setDestinationUri(Uri.fromFile(destinationFile));
mdDownloadManager.enqueue(request);
}
}
}
return true;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "video/mp4");
startActivity(intent);
return true;
}
}
else
//Open MP3 file Download mp3
if(url.endsWith(".mp3") || url.endsWith(".MP3")){
// Download files
if(url.startsWith("download")){
String[] download_link = url.split(":");
try {
//Download mp3
sdrUrl= URLDecoder.decode(download_link[1], "UTF-8")+":"+URLDecoder.decode(download_link[2], "UTF-8");
//ext=url.substring(url.lastIndexOf("."));
ext = MimeTypeMap.getFileExtensionFromUrl(sdrUrl);
if (ext != null) {
MimeTypeMap mime = MimeTypeMap.getSingleton();
String mimeType = mime.getMimeTypeFromExtension(ext);
if (mimeType != null) {
if (ext.toLowerCase().contains("mp3")) {
DownloadManager mdDownloadManager = (DownloadManager) MainActivity.this
.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(sdrUrl));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
request.setAllowedOverRoaming(true);
File destinationFile = new File(
Environment.getExternalStorageDirectory(),
getFileName(sdrUrl, ext));
request.setDestinationUri(Uri.fromFile(destinationFile));
mdDownloadManager.enqueue(request);
}
}
}
return true;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "audio/mp3");
startActivity(intent);
return true;
}
}
//View file < a href="www.text.com/test.txt"> View text</a>
if (
url.endsWith(".pdf")
|| url.endsWith(".txt")
|| url.endsWith(".doc")
|| url.endsWith(".docx")
|| url.endsWith(".xls")
|| url.endsWith(".xlsx")
|| url.endsWith(".ppt")
|| url.endsWith(".pptx")
|| url.endsWith(".pages")
|| url.endsWith(".ai")
|| url.endsWith(".psd")
|| url.endsWith(".tiff")
|| url.endsWith(".dxf")
|| url.endsWith(".svg")
|| url.endsWith(".eps")
|| url.endsWith(".ps")
|| url.endsWith(".ttf")
|| url.endsWith(".xps")
|| url.endsWith(".zip")
|| url.endsWith(".rar")
)
{
if(url.startsWith("download")){
String[] download_link = url.split(":");
try {
sdrUrl= URLDecoder.decode(download_link[1], "UTF-8")+":"+URLDecoder.decode(download_link[2], "UTF-8");
ext = MimeTypeMap.getFileExtensionFromUrl(sdrUrl);
if (ext != null) {
MimeTypeMap mime = MimeTypeMap.getSingleton();
String mimeType = mime.getMimeTypeFromExtension(ext);
if (mimeType != null) {
DownloadManager mdDownloadManager = (DownloadManager) MainActivity.this
.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(sdrUrl));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
request.setAllowedOverRoaming(true);
File destinationFile = new File(
Environment.getExternalStorageDirectory(),
getFileName(sdrUrl, ext));
request.setDestinationUri(Uri.fromFile(destinationFile));
mdDownloadManager.enqueue(request);
}
}
return true;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
String googleDocs = "https://docs.google.com/viewer?url=";
mainWebView.loadUrl(googleDocs + url);
return true;
}
}
else
if(url.startsWith("http:") || url.startsWith("https:")) {view.loadUrl(url); }
return true;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
view.loadUrl("file:///android_asset/error.html");
}
}
private class MyChromeClient extends WebChromeClient implements OnCompletionListener, OnErrorListener {
FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
#Override
public void onShowCustomView(View view, int requestedOrientation,
WebChromeClient.CustomViewCallback callback) // Available in API level 14+, deprecated in API level 18+
{
onShowCustomView(view, callback);
if(Build.VERSION.SDK_INT >=14) {
if (view instanceof FrameLayout) {
mainWebView.addView(view, new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
Gravity.CENTER));
mainWebView.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
if (view instanceof FrameLayout) {
// mainWebView is the view that the video should've played inside.
mainWebView = (WebView)findViewById(R.id.webView1);
mCustomViewContainer = (FrameLayout) view;
mCustomViewCallback = callback;
// mainLayout is the root layout that (ex. the layout that contains the webview)
mContentView = (RelativeLayout)findViewById(R.id.RootLayout);
if (mCustomViewContainer.getFocusedChild() instanceof VideoView) {
mVideoView = (VideoView) mCustomViewContainer.getFocusedChild();
// frame.removeView(video);
mContentView.setVisibility(View.GONE);
mCustomViewContainer.setVisibility(View.VISIBLE);
setContentView(mCustomViewContainer);
mVideoView.setOnCompletionListener((OnCompletionListener) this);
mVideoView.setOnErrorListener((OnErrorListener) this);
mVideoView.start();
}
}
}
public void onHideCustomView() {
if (mVideoView == null){
return;
}else{
// Hide the custom view.
mVideoView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mVideoView);
mVideoView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
mContentView.setVisibility(View.VISIBLE);
}
}
public void onCompletion(MediaPlayer mp) {
mp.stop();
mCustomViewContainer.setVisibility(View.GONE);
onHideCustomView();
setContentView(mContentView);
}
#SuppressWarnings("unused")
public void onPrepared(MediaPlayer mp) {
mCustomViewCallback.onCustomViewHidden();
}
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
setContentView(mContentView);
return true;
}
//Java script alert dialog
#Override
public boolean onJsAlert(WebView view, String url, String message,
final JsResult result) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Attention !")
.setMessage(message)
.setPositiveButton(R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do your stuff here
result.confirm();
}
}).setCancelable(false).create().show();
return true;
}
//Java script confirm dialog
#Override
public boolean onJsConfirm(WebView view, String url, String message,
final JsResult result) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Confirm !")
.setMessage(message)
.setPositiveButton(R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do your stuff here
result.confirm();
}
}).setCancelable(false).create().show();
return true;
}
//Java script Prompt dialog
#Override
public boolean onJsPrompt(WebView view, String url, String message,
String defaultValue, final JsPromptResult result) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Prompt Alert !")
.setMessage(message)
.setPositiveButton(R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do your stuff here
result.confirm();
}
}).setCancelable(false).create().show();
return true;
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mainmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_rate:
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("market://details?id=" + getPackageName()));
startActivity(i);
break;
case R.id.action_refresh:
mainWebView.loadUrl( "javascript:window.location.reload( true )" );
break;
case R.id.action_exit:
finish();
break;
default:
break;
}
return true;
}
#Override
protected void onPause() {
if(mCustomViewContainer != null){
vidPosition = mVideoView.getCurrentPosition();
}
super.onPause();
}
#Override
protected void onResume() {
if(mCustomViewContainer != null){
mVideoView.seekTo(vidPosition);
}
super.onResume();
}
#Override
public void onBackPressed() {
if(mCustomViewContainer != null){
mVideoView.stopPlayback();
mCustomViewContainer.setVisibility(View.GONE);
if (mVideoView == null){
return;
}else{
// Hide the custom view.
mVideoView.setVisibility(View.GONE);
// Remove the custom view from its container.
mCustomViewContainer.removeView(mVideoView);
mVideoView = null;
mCustomViewContainer.setVisibility(View.GONE);
mCustomViewCallback.onCustomViewHidden();
// Show the content view.
mContentView.setVisibility(View.VISIBLE);
setContentView(mContentView);
mCustomViewContainer = null;
}
}else if(mainWebView.canGoBack()){
mainWebView.goBack();
}else{
super.onBackPressed();
}
}
public String getFileName(String url, String ext1) {
String filenameWithoutExtension = "";
filenameWithoutExtension = String.valueOf(System.currentTimeMillis()+"."+ext1);
return filenameWithoutExtension;
}
}
There is no built in "Popup" class in Android. So it depends on what do you need from "Popup". You can use dialog as it says here. Or you can create dynamically WebView and add it into some container (RelativeLayout for instance).
An intent is an abstract description of an operation to be performed.To open a URL/website you do the following:
String url = "http://www.stackexchange.com";
Intent browserIntent = new Intent(Intent.ACTION_VIEW);
browserIntent.setData(Uri.parse(url));
startActivity(browserIntent);
Related
I am completely new to Android and just learned Object-oriented programming. My project requires me to build something on open-source code. I am really struggling with this special case. Two fragments are under activity_main, one of them is TerminalFragment. I added a menuItem (R.id.plot) in it and set if the user clicks this Item that will lead him from TerminalFragment to activity_main2. Due to receive(byte data) and TerminalFragment still on active, the data is still printing out by receiveText.append(TextUtil.toCaretString(msg, newline.length() != 0)); in activity_main.
Now, I want to convert the data to String and send it to activity_main2 for display in recyclerview and plotting graph. I am trying to use putextra and getextra but not sure how to access data from getextra in activity_main2. In my testing, the recyclerview just showed "John". Is something missing in my method? Does anyone have a better idea? Much Appreciated.
TerminalFragment
package de.kai_morich.simple_bluetooth_le_terminal;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class TerminalFragment extends Fragment implements ServiceConnection, SerialListener {
private MenuItem menuItem;
private enum Connected { False, Pending, True }
private String deviceAddress;
private SerialService service;
private TextView receiveText;
private TextView sendText;
private TextUtil.HexWatcher hexWatcher;
private Connected connected = Connected.False;
private boolean initialStart = true;
private boolean hexEnabled = false;
private boolean pendingNewline = false;
private String newline = TextUtil.newline_crlf;
private String output;
/*
* Lifecycle
*/
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
//Register with activity
// You must inform the system that your app bar fragment is participating in the population of the options menu.
// tells the system that your fragment would like to receive menu-related callbacks.
setRetainInstance(true);
deviceAddress = getArguments().getString("device");
}
#Override
public void onDestroy() {
if (connected != Connected.False)
disconnect();
getActivity().stopService(new Intent(getActivity(), SerialService.class));
super.onDestroy();
}
#Override
public void onStart() {
super.onStart();
if(service != null)
service.attach(this);
else
getActivity().startService(new Intent(getActivity(), SerialService.class)); // prevents service destroy on unbind from recreated activity caused by orientation change
}
#Override
public void onStop() {
if(service != null && !getActivity().isChangingConfigurations())
service.detach();
super.onStop();
}
#SuppressWarnings("deprecation") // onAttach(context) was added with API 23. onAttach(activity) works for all API versions
#Override
public void onAttach(#NonNull Activity activity) {
super.onAttach(activity);
getActivity().bindService(new Intent(getActivity(), SerialService.class), this, Context.BIND_AUTO_CREATE);
}
#Override
public void onDetach() {
try { getActivity().unbindService(this); } catch(Exception ignored) {}
super.onDetach();
}
#Override
public void onResume() {
super.onResume();
if(initialStart && service != null) {
initialStart = false;
getActivity().runOnUiThread(this::connect);
}
}
#Override
public void onServiceConnected(ComponentName name, IBinder binder) {
service = ((SerialService.SerialBinder) binder).getService();
service.attach(this);
if(initialStart && isResumed()) {
initialStart = false;
getActivity().runOnUiThread(this::connect);
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
service = null;
}
/*
* UI
*/
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_terminal, container, false);
receiveText = view.findViewById(R.id.receive_text); // TextView performance decreases with number of spans
receiveText.setTextColor(getResources().getColor(R.color.colorRecieveText)); // set as default color to reduce number of spans
receiveText.setMovementMethod(ScrollingMovementMethod.getInstance());
sendText = view.findViewById(R.id.send_text);
hexWatcher = new TextUtil.HexWatcher(sendText);
hexWatcher.enable(hexEnabled);
sendText.addTextChangedListener(hexWatcher);
sendText.setHint(hexEnabled ? "HEX mode" : "");
View sendBtn = view.findViewById(R.id.send_btn);
sendBtn.setOnClickListener(v -> send(sendText.getText().toString()));
return view;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_terminal, menu);
menu.findItem(R.id.hex).setChecked(hexEnabled);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.clear) {
receiveText.setText("");
return true;
} if (id == R.id.plot){
Intent intent = new Intent(getActivity(), MainActivity2.class);
startActivity(intent);
//receive.;
return true;
}else if (id == R.id.newline) {
String[] newlineNames = getResources().getStringArray(R.array.newline_names);
String[] newlineValues = getResources().getStringArray(R.array.newline_values);
int pos = java.util.Arrays.asList(newlineValues).indexOf(newline);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Newline");
builder.setSingleChoiceItems(newlineNames, pos, (dialog, item1) -> {
newline = newlineValues[item1];
dialog.dismiss();
});
builder.create().show();
return true;
} else if (id == R.id.hex) {
hexEnabled = !hexEnabled;
sendText.setText("");
hexWatcher.enable(hexEnabled);
sendText.setHint(hexEnabled ? "HEX mode" : "");
item.setChecked(hexEnabled);
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
/*
* Serial + UI
*/
private void connect() {
try {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
status("connecting...");
connected = Connected.Pending;
SerialSocket socket = new SerialSocket(getActivity().getApplicationContext(), device);
service.connect(socket);
} catch (Exception e) {
onSerialConnectError(e);
}
}
private void disconnect() {
connected = Connected.False;
service.disconnect();
}
private void send(String str) {
if(connected != Connected.True) {
Toast.makeText(getActivity(), "not connected", Toast.LENGTH_SHORT).show();
return;
}
try {
String msg;
byte[] data;
if(hexEnabled) {
StringBuilder sb = new StringBuilder();
TextUtil.toHexString(sb, TextUtil.fromHexString(str));
TextUtil.toHexString(sb, newline.getBytes());
msg = sb.toString();
data = TextUtil.fromHexString(msg);
} else {
msg = str;
data = (str + newline).getBytes();
}
SpannableStringBuilder spn = new SpannableStringBuilder(msg + '\n');
spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorSendText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
receiveText.append(spn);
service.write(data);
} catch (Exception e) {
onSerialIoError(e);
}
}
private void receive(byte[] data) {
if(hexEnabled) {
receiveText.append("Hello" + TextUtil.toHexString(data) + '\n');
} else {
String msg = new String(data);
if(newline.equals(TextUtil.newline_crlf) && msg.length() > 0) {
// don't show CR as ^M if directly before LF
msg = msg.replace(TextUtil.newline_crlf, TextUtil.newline_lf);
// special handling if CR and LF come in separate fragments
if (pendingNewline && msg.charAt(0) == '\n') {
Editable edt = receiveText.getEditableText();
if (edt != null && edt.length() > 1)
edt.replace(edt.length() - 2, edt.length(), "");
}
pendingNewline = msg.charAt(msg.length() - 1) == '\r';
}
receiveText.append(TextUtil.toCaretString(msg, newline.length() != 0)); //print out data
output = receiveText.toString(); // CharSequence to String
Intent intent = new Intent(getActivity(), MainActivity2.class);
intent.putExtra("output",output); // send data to next activity, MainActivity2
}
}
private void status(String str) {
SpannableStringBuilder spn = new SpannableStringBuilder(str + '\n');
spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorStatusText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
receiveText.append(spn);
}
/*
* SerialListener
*/
#Override
public void onSerialConnect() {
status("connected");
connected = Connected.True;
}
#Override
public void onSerialConnectError(Exception e) {
status("connection failed: " + e.getMessage());
disconnect();
}
#Override
public void onSerialRead(byte[] data) {// receive data
receive(data); // send data to printout
}
#Override
public void onSerialIoError(Exception e) {
status("connection lost: " + e.getMessage());
disconnect();
}
}
MainActivity2.java (new activity)
package de.kai_morich.simple_bluetooth_le_terminal;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity2 extends AppCompatActivity {
Fragment CustomFragment;
private ArrayList<Data> dataList;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
recyclerView = findViewById(R.id.dataflow);
dataList = new ArrayList<>();
String data;
if (savedInstanceState == null) {
Bundle extra = getIntent().getExtras();
if (extra == null) {
data = null;
receiveData(data);
} else {
data = extra.getString("output");
receiveData(data);
}
} else {
data = (String) savedInstanceState.getSerializable("output");
receiveData(data);
}
setAdapter();
}
private void receiveData(String data){
String Data = data;
dataList.add(new Data("John"));
dataList.add(new Data(Data));
}
private void setAdapter() {
recyclerAdapter adapter = new recyclerAdapter(dataList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_plot, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.dataplot:
Toast.makeText(this, "dataplot", Toast.LENGTH_SHORT).show();
replaceFragment(new DataPlotFragment());
return true;
case R.id.fft:
Toast.makeText(this, "FFT", Toast.LENGTH_SHORT).show();
replaceFragment(new FftFragment());
return true;
case R.id.data:
Toast.makeText(this, "DATA", Toast.LENGTH_SHORT).show();
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void replaceFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.plotframelayout,fragment);
fragmentTransaction.commit();
}
}
I realized I also need to add getText() in receive(). However, the recycler view won't update itself, it just captures what it has in the recyclerview of activity_main with TerminalFragment when the user click the menuItem (id,plot). Either getextrastring() or using bundle able to pass the data to Mainactivity2.
I think I need to add something else to keep adding data to the recyclerview of activity_main2 from activity_main.
onOptionsItemSelected of TerminalFragment
if (id == R.id.plot){
Intent intent = new Intent(getActivity(), MainActivity2.class);
intent.putExtra("output",output); //output
startActivity(intent);
return true;
}
receive() of TerminalFragment
private void receive(byte[] data) {
if(hexEnabled) {
receiveText.append("Hello" + TextUtil.toHexString(data) + '\n');
} else {
String msg = new String(data);
if(newline.equals(TextUtil.newline_crlf) && msg.length() > 0) {
// don't show CR as ^M if directly before LF
msg = msg.replace(TextUtil.newline_crlf, TextUtil.newline_lf);
// special handling if CR and LF come in separate fragments
if (pendingNewline && msg.charAt(0) == '\n') {
Editable edt = receiveText.getEditableText();
if (edt != null && edt.length() > 1)
edt.replace(edt.length() - 2, edt.length(), "");
}
pendingNewline = msg.charAt(msg.length() - 1) == '\r';
}
receiveText.append(TextUtil.toCaretString(msg, newline.length() != 0)); //print out data
output = receiveText.getText().toString(); // CharSequence to String
}
}
OnCreate of mainActivity2
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
recyclerView = findViewById(R.id.dataflow);
dataList = new ArrayList<>();
String data;
Bundle extras = getIntent().getExtras();
if (extras != null)
{
data = extras.getString("output");
receiveData(data);
}
setAdapter();
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
hope you doing great.i'm very new to android programming and i have source of an app which i intend to modify and add PatternLockView library to it . i watched a youtube video tutorial but i can't use handler.postdelay option in the code (android studio returns with : Cannot resolve symbol 'postdelayed').the coder who made the tutorial didn't got any errors or so but android studio gives me lots of them . any help or hint is appreciated.
here is the code :
Handler handler = new Handler ();
handler.postdelayed {
#Override
public void run() {
SharedPreferences preferences = getSharedPreferences("PREFS", 0);
String password = preferences.getString("password","0");
if (password.equals("0")) {
Intent intent = new Intent (getApplicationContext(),CreatePasswordActivity.class);
startActivity(intent);
finish();
} else {
Intent intent = new Intent (getApplicationContext(),InputPasswordActivity.class);
startActivity(intent);
finish();
}
}
}2000
/*#######################################################
*
* Maintained by Gregor Santner, 2017-
* https://gsantner.net/
*
* License of this file: Apache 2.0 (Commercial upon request)
* https://www.apache.org/licenses/LICENSE-2.0
*
#########################################################*/
package net.gsantner.markor.activity;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import com.pixplicity.generate.Rate;
import net.gsantner.markor.BuildConfig;
import net.gsantner.markor.R;
import net.gsantner.markor.format.TextFormat;
import net.gsantner.markor.ui.FilesystemViewerCreator;
import net.gsantner.markor.ui.NewFileDialog;
import net.gsantner.markor.util.ActivityUtils;
import net.gsantner.markor.util.AppSettings;
import net.gsantner.markor.util.PermissionChecker;
import net.gsantner.markor.util.ShareUtil;
import net.gsantner.opoc.activity.GsFragmentBase;
import net.gsantner.opoc.format.markdown.SimpleMarkdownParser;
import net.gsantner.opoc.ui.FilesystemViewerAdapter;
import net.gsantner.opoc.ui.FilesystemViewerData;
import net.gsantner.opoc.ui.FilesystemViewerFragment;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.concurrent.TimeUnit;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnLongClick;
import butterknife.OnPageChange;
public class MainActivity extends AppActivityBase implements FilesystemViewerFragment.FilesystemFragmentOptionsListener, BottomNavigationView.OnNavigationItemSelectedListener {
//START
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed( () -> {
SharedPreferences preferences = getSharedPreferences("PREFS", 0);
String password = preferences.getString("password","0");
if (password.equals("0")) {
Intent intent = new Intent (getApplicationContext(),CreatePasswordActivity.class);
startActivity(intent);
finish();
} else {
Intent intent = new Intent (getApplicationContext(),InputPasswordActivity.class);
startActivity(intent);
finish();
}
}, 2000);
// END
public static boolean IS_DEBUG_ENABLED = false;
#BindView(R.id.toolbar)
public Toolbar _toolbar;
#BindView(R.id.bottom_navigation_bar)
BottomNavigationView _bottomNav;
#BindView(R.id.fab_add_new_item)
FloatingActionButton _fab;
#BindView(R.id.main__view_pager_container)
ViewPager _viewPager;
private SectionsPagerAdapter _viewPagerAdapter;
private boolean _doubleBackToExitPressedOnce;
private MenuItem _lastBottomMenuItem;
private AppSettings _appSettings;
private ActivityUtils _contextUtils;
private ShareUtil _shareUtil;
#SuppressLint("SdCardPath")
#Override
protected void onCreate(Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setExitTransition(null);
}
_appSettings = new AppSettings(this);
_contextUtils = new ActivityUtils(this);
_shareUtil = new ShareUtil(this);
_contextUtils.setAppLanguage(_appSettings.getLanguage());
if (_appSettings.isOverviewStatusBarHidden()) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
setTheme(_appSettings.isDarkThemeEnabled() ? R.style.AppTheme_Dark : R.style.AppTheme_Light);
super.onCreate(savedInstanceState);
setContentView(R.layout.main__activity);
ButterKnife.bind(this);
setSupportActionBar(_toolbar);
_toolbar.setOnClickListener(this::onToolbarTitleClicked);
optShowRate();
try {
if (_appSettings.isAppCurrentVersionFirstStart(true)) {
SimpleMarkdownParser smp = SimpleMarkdownParser.get().setDefaultSmpFilter(SimpleMarkdownParser.FILTER_ANDROID_TEXTVIEW);
String html = "";
html += smp.parse(getString(R.string.copyright_license_text_official).replace("\n", " \n"), "").getHtml();
html += "<br/><br/><br/><big><big>" + getString(R.string.changelog) + "</big></big><br/>" + smp.parse(getResources().openRawResource(R.raw.changelog), "", SimpleMarkdownParser.FILTER_ANDROID_TEXTVIEW);
html += "<br/><br/><br/><big><big>" + getString(R.string.licenses) + "</big></big><br/>" + smp.parse(getResources().openRawResource(R.raw.licenses_3rd_party), "").getHtml();
ActivityUtils _au = new ActivityUtils(this);
_au.showDialogWithHtmlTextView(0, html);
}
} catch (IOException e) {
e.printStackTrace();
}
IntroActivity.optStart(this);
// Setup viewpager
_viewPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
_viewPager.setAdapter(_viewPagerAdapter);
_viewPager.setOffscreenPageLimit(4);
_bottomNav.setOnNavigationItemSelectedListener(this);
// noinspection PointlessBooleanExpression - Send Test intent
if (BuildConfig.IS_TEST_BUILD && false) {
DocumentActivity.launch(this, new File("/sdcard/Documents/mordor/aa-beamer.md"), false, true, null, null);
}
(new ActivityUtils(this)).applySpecialLaunchersVisibility(_appSettings.isSpecialFileLaunchersEnabled());
_bottomNav.postDelayed(() -> {
if (_appSettings.getAppStartupTab() != R.id.nav_notebook) {
_bottomNav.setSelectedItemId(_appSettings.getAppStartupTab());
}
}, 1);
}
private void optShowRate() {
new Rate.Builder(this)
.setTriggerCount(4)
.setMinimumInstallTime((int) TimeUnit.MINUTES.toMillis(30))
.setFeedbackAction(() -> new ActivityUtils(this).showGooglePlayEntryForThisApp())
.build().count().showRequest();
}
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
PermissionChecker permc = new PermissionChecker(this);
permc.checkPermissionResult(requestCode, permissions, grantResults);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
AppSettings as = new AppSettings(this);
switch (item.getItemId()) {
case R.id.action_preview: {
File f = _bottomNav.getSelectedItemId() == R.id.nav_quicknote ? as.getQuickNoteFile() : as.getTodoFile();
DocumentActivity.launch(MainActivity.this, f, false, true, null, null);
return true;
}
case R.id.action_settings: {
new ActivityUtils(this).animateToActivity(SettingsActivity.class, false, null);
return true;
}
}
return false;
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.main__menu, menu);
menu.findItem(R.id.action_settings).setVisible(_appSettings.isShowSettingsOptionInMainToolbar());
_contextUtils.tintMenuItems(menu, true, Color.WHITE);
_contextUtils.setSubMenuIconsVisiblity(menu, true);
return true;
}
#Override
protected void onResume() {
//new AndroidSupportMeWrapper(this).mainOnResume();
super.onResume();
IS_DEBUG_ENABLED = BuildConfig.IS_TEST_BUILD;
if (_appSettings.isRecreateMainRequired()) {
// recreate(); // does not remake fragments
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && _appSettings.isMultiWindowEnabled()) {
setTaskDescription(new ActivityManager.TaskDescription(getString(R.string.app_name)));
}
int color = ContextCompat.getColor(this, _appSettings.isDarkThemeEnabled()
? R.color.dark__background : R.color.light__background);
_viewPager.getRootView().setBackgroundColor(color);
if (_appSettings.isKeepScreenOn()) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
#Override
#SuppressWarnings("unused")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Determine some results and forward using Local Broadcast
Object result = _shareUtil.extractResultFromActivityResult(requestCode, resultCode, data, this);
try {
FilesystemViewerFragment frag = (FilesystemViewerFragment) _viewPagerAdapter.getFragmentByTag(FilesystemViewerFragment.FRAGMENT_TAG);
frag.getAdapter().reconfigure();
} catch (Exception ignored) {
recreate();
}
}
#OnLongClick({R.id.fab_add_new_item})
public boolean onLongClickFab(View view) {
PermissionChecker permc = new PermissionChecker(this);
FilesystemViewerFragment fsFrag = (FilesystemViewerFragment) _viewPagerAdapter.getFragmentByTag(FilesystemViewerFragment.FRAGMENT_TAG);
if (fsFrag != null && permc.mkdirIfStoragePermissionGranted()) {
fsFrag.getAdapter().setCurrentFolder(fsFrag.getCurrentFolder().equals(FilesystemViewerAdapter.VIRTUAL_STORAGE_RECENTS)
? FilesystemViewerAdapter.VIRTUAL_STORAGE_FAVOURITE : FilesystemViewerAdapter.VIRTUAL_STORAGE_RECENTS
, true);
}
return true;
}
#SuppressWarnings("SwitchStatementWithTooFewBranches")
#OnClick({R.id.fab_add_new_item})
public void onClickFab(View view) {
PermissionChecker permc = new PermissionChecker(this);
FilesystemViewerFragment fsFrag = (FilesystemViewerFragment) _viewPagerAdapter.getFragmentByTag(FilesystemViewerFragment.FRAGMENT_TAG);
if (fsFrag == null) {
return;
}
if (fsFrag.getAdapter().isCurrentFolderVirtual()) {
fsFrag.getAdapter().loadFolder(_appSettings.getNotebookDirectory());
return;
}
if (permc.mkdirIfStoragePermissionGranted()) {
switch (view.getId()) {
case R.id.fab_add_new_item: {
if (_shareUtil.isUnderStorageAccessFolder(fsFrag.getCurrentFolder()) && _shareUtil.getStorageAccessFrameworkTreeUri() == null) {
_shareUtil.showMountSdDialog(this);
return;
}
if (!fsFrag.getAdapter().isCurrentFolderWriteable()) {
return;
}
NewFileDialog dialog = NewFileDialog.newInstance(fsFrag.getCurrentFolder(), true, (ok, f) -> {
if (ok) {
if (f.isFile()) {
DocumentActivity.launch(MainActivity.this, f, false, false, null, null);
} else if (f.isDirectory()) {
FilesystemViewerFragment wrFragment = (FilesystemViewerFragment) _viewPagerAdapter.getFragmentByTag(FilesystemViewerFragment.FRAGMENT_TAG);
if (wrFragment != null) {
wrFragment.reloadCurrentFolder();
}
}
}
});
dialog.show(getSupportFragmentManager(), NewFileDialog.FRAGMENT_TAG);
break;
}
}
}
}
#Override
public void onBackPressed() {
// Exit confirmed with 2xBack
if (_doubleBackToExitPressedOnce) {
super.onBackPressed();
_appSettings.setFileBrowserLastBrowsedFolder(_appSettings.getNotebookDirectory());
return;
}
// Check if fragment handled back press
GsFragmentBase frag = _viewPagerAdapter.getCachedFragments().get(_viewPager.getCurrentItem());
if (frag != null && frag.onBackPressed()) {
return;
}
// Confirm exit with back / snackbar
_doubleBackToExitPressedOnce = true;
new ActivityUtils(this).showSnackBar(R.string.press_back_again_to_exit, false, R.string.exit, view -> finish());
new Handler().postDelayed(() -> _doubleBackToExitPressedOnce = false, 2000);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
updateFabVisibility(item.getItemId() == R.id.nav_notebook);
PermissionChecker permc = new PermissionChecker(this);
switch (item.getItemId()) {
case R.id.nav_notebook: {
_viewPager.setCurrentItem(0);
_toolbar.setTitle(getFileBrowserTitle());
return true;
}
case R.id.nav_todo: {
permc.doIfExtStoragePermissionGranted(); // cannot prevent bottom tab selection
restoreDefaultToolbar();
_viewPager.setCurrentItem(1);
_toolbar.setTitle(R.string.todo);
return true;
}
case R.id.nav_quicknote: {
permc.doIfExtStoragePermissionGranted(); // cannot prevent bottom tab selection
restoreDefaultToolbar();
_viewPager.setCurrentItem(2);
_toolbar.setTitle(R.string.quicknote);
return true;
}
case R.id.nav_more: {
restoreDefaultToolbar();
_viewPager.setCurrentItem(3);
_toolbar.setTitle(R.string.more);
return true;
}
}
return false;
}
public void updateFabVisibility(boolean visible) {
if (visible) {
_fab.show();
} else {
_fab.hide();
}
}
public String getFileBrowserTitle() {
final File file = _appSettings.getFileBrowserLastBrowsedFolder();
String title = getString(R.string.app_name);
if (!_appSettings.getNotebookDirectory().getAbsolutePath().equals(file.getAbsolutePath())) {
title = "> " + file.getName();
}
return title;
}
#OnPageChange(value = R.id.main__view_pager_container, callback = OnPageChange.Callback.PAGE_SELECTED)
public void onViewPagerPageSelected(int pos) {
Menu menu = _bottomNav.getMenu();
PermissionChecker permc = new PermissionChecker(this);
(_lastBottomMenuItem != null ? _lastBottomMenuItem : menu.getItem(0)).setChecked(false);
_lastBottomMenuItem = menu.getItem(pos).setChecked(true);
updateFabVisibility(pos == 0);
_toolbar.setTitle(new String[]{getFileBrowserTitle(), getString(R.string.todo), getString(R.string.quicknote), getString(R.string.more)}[pos]);
if (pos > 0 && pos < 3) {
permc.doIfExtStoragePermissionGranted(); // cannot prevent bottom tab selection
}
}
private FilesystemViewerData.Options _filesystemDialogOptions = null;
#Override
public FilesystemViewerData.Options getFilesystemFragmentOptions(FilesystemViewerData.Options existingOptions) {
if (_filesystemDialogOptions == null) {
_filesystemDialogOptions = FilesystemViewerCreator.prepareFsViewerOpts(getApplicationContext(), false, new FilesystemViewerData.SelectionListenerAdapter() {
#Override
public void onFsViewerConfig(FilesystemViewerData.Options dopt) {
dopt.descModtimeInsteadOfParent = true;
//opt.rootFolder = _appSettings.getNotebookDirectory();
dopt.rootFolder = _appSettings.getFolderToLoadByMenuId(_appSettings.getAppStartupFolderMenuId());
dopt.folderFirst = _appSettings.isFilesystemListFolderFirst();
dopt.doSelectMultiple = dopt.doSelectFolder = dopt.doSelectFile = true;
dopt.mountedStorageFolder = _shareUtil.getStorageAccessFolder();
dopt.showDotFiles = _appSettings.isShowDotFiles();
dopt.fileComparable = FilesystemViewerFragment.sortFolder(null);
}
#Override
public void onFsViewerDoUiUpdate(FilesystemViewerAdapter adapter) {
if (adapter != null && adapter.getCurrentFolder() != null && !TextUtils.isEmpty(adapter.getCurrentFolder().getName())) {
_appSettings.setFileBrowserLastBrowsedFolder(adapter.getCurrentFolder());
_toolbar.setTitle(adapter.areItemsSelected() ? "" : getFileBrowserTitle());
invalidateOptionsMenu();
if (adapter.getCurrentFolder().equals(FilesystemViewerAdapter.VIRTUAL_STORAGE_FAVOURITE)) {
adapter.getFsOptions().favouriteFiles = _appSettings.getFavouriteFiles();
}
}
}
#Override
public void onFsViewerSelected(String request, File file, final Integer lineNumber) {
if (TextFormat.isTextFile(file)) {
DocumentActivity.launch(MainActivity.this, file, false, null, null, lineNumber);
} else if (file.getName().toLowerCase().endsWith(".apk")) {
_shareUtil.requestApkInstallation(file);
} else {
DocumentActivity.askUserIfWantsToOpenFileInThisApp(MainActivity.this, file);
}
}
});
}
return _filesystemDialogOptions;
}
class SectionsPagerAdapter extends FragmentPagerAdapter {
private HashMap<Integer, GsFragmentBase> _fragCache = new LinkedHashMap<>();
SectionsPagerAdapter(FragmentManager fragMgr) {
super(fragMgr);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
GsFragmentBase fragment = (GsFragmentBase) super.instantiateItem(container, position);
_fragCache.put(position, fragment);
return fragment;
}
#Override
public Fragment getItem(int pos) {
final Fragment existing = _fragCache.get(pos);
if (existing != null) {
return existing;
}
switch (_bottomNav.getMenu().getItem(pos).getItemId()) {
default:
case R.id.nav_notebook: {
return FilesystemViewerFragment.newInstance(getFilesystemFragmentOptions(null));
}
case R.id.nav_quicknote: {
return DocumentEditFragment.newInstance(_appSettings.getQuickNoteFile(), false, -1);
}
case R.id.nav_todo: {
return DocumentEditFragment.newInstance(_appSettings.getTodoFile(), false, -1);
}
case R.id.nav_more: {
return MoreFragment.newInstance();
}
}
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
_fragCache.remove(position);
}
#Override
public int getCount() {
return _bottomNav.getMenu().size();
}
public GsFragmentBase getFragmentByTag(String fragmentTag) {
for (GsFragmentBase frag : _fragCache.values()) {
if (fragmentTag.equals(frag.getFragmentTag())) {
return frag;
}
}
return null;
}
public HashMap<Integer, GsFragmentBase> getCachedFragments() {
return _fragCache;
}
}
#Override
protected void onStop() {
super.onStop();
restoreDefaultToolbar();
}
/**
* Restores the default toolbar. Used when changing the tab or moving to another activity
* while {#link FilesystemViewerFragment} action mode is active (e.g. when renaming a file)
*/
private void restoreDefaultToolbar() {
FilesystemViewerFragment wrFragment = (FilesystemViewerFragment) _viewPagerAdapter.getFragmentByTag(FilesystemViewerFragment.FRAGMENT_TAG);
if (wrFragment != null) {
wrFragment.clearSelection();
}
}
private void onToolbarTitleClicked(View v) {
Fragment f = _viewPagerAdapter.getItem(_viewPager.getCurrentItem());
if (f instanceof DocumentEditFragment) {
DocumentEditFragment def = (DocumentEditFragment) f;
def.onToolbarTitleClicked(_toolbar);
}
}
}
Since the postDelayed is a method, you have to use () along with it. It takes 2 parameters, first one is a Runnable object and second one is a millisecond value to delay which is an int type. Also Handler() constructor is depracated, that's why you have to bind your handler to a looper object, commonly to the main looper. Here is the fixed code:
// Make sure you import the right Handler class
import android.os.Handler;
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed( () -> {
SharedPreferences preferences = getSharedPreferences("PREFS", 0);
String password = preferences.getString("password","0");
if (password.equals("0")) {
Intent intent = new Intent (getApplicationContext(),CreatePasswordActivity.class);
startActivity(intent);
finish();
} else {
Intent intent = new Intent (getApplicationContext(),InputPasswordActivity.class);
startActivity(intent);
finish();
}
}, millisecondDelay);
UPDATE
I've noted that your postdelayed syntax isn't correct. It must be as postDelayed. I updated my answer chek the code out again.
The following code allows you to start a video player and play the video.
The problem is that the NavigationBar hides a piece of the video, I would like to make it transparent.
import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Point;
import android.media.MediaPlayer;
import android.widget.MediaController;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.view.MotionEvent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.VideoView;
public class SimpleVideoStream extends Activity implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {
private String TAG = getClass().getSimpleName();
private VideoView mVideoView = null;
private MediaPlayer mMediaPlayer = null;
private MediaController mMediaController = null;
private ProgressBar mProgressBar = null;
private String mVideoUrl;
private Boolean mShouldAutoClose = true;
private boolean mControls;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
Bundle b = getIntent().getExtras();
mVideoUrl = b.getString("mediaUrl");
mShouldAutoClose = b.getBoolean("shouldAutoClose", true);
mControls = b.getBoolean("controls", true);
RelativeLayout relLayout = new RelativeLayout(this);
relLayout.setBackgroundColor(Color.BLACK);
RelativeLayout.LayoutParams relLayoutParam = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
relLayoutParam.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
mVideoView = new VideoView(this);
mVideoView.setLayoutParams(relLayoutParam);
relLayout.addView(mVideoView);
// Create progress throbber
mProgressBar = new ProgressBar(this);
mProgressBar.setIndeterminate(true);
// Center the progress bar
RelativeLayout.LayoutParams pblp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
pblp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
mProgressBar.setLayoutParams(pblp);
// Add progress throbber to view
relLayout.addView(mProgressBar);
mProgressBar.bringToFront();
setOrientation(b.getString("orientation"));
setContentView(relLayout, relLayoutParam);
play();
}
private void play() {
mProgressBar.setVisibility(View.VISIBLE);
Uri videoUri = Uri.parse(mVideoUrl);
try {
mVideoView.setOnCompletionListener(this);
mVideoView.setOnPreparedListener(this);
mVideoView.setOnErrorListener(this);
mVideoView.setVideoURI(videoUri);
mMediaController = new MediaController(this);
mMediaController.setAnchorView(mVideoView);
mMediaController.setMediaPlayer(mVideoView);
if (!mControls) {
mMediaController.setVisibility(View.GONE);
}
mVideoView.setMediaController(mMediaController);
} catch (Throwable t) {
Log.d(TAG, t.toString());
}
}
private void setOrientation(String orientation) {
if ("landscape".equals(orientation)) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}else if("portrait".equals(orientation)) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
private Runnable checkIfPlaying = new Runnable() {
#Override
public void run() {
if (mVideoView.getCurrentPosition() > 0) {
// Video is not at the very beginning anymore.
// Hide the progress bar.
mProgressBar.setVisibility(View.GONE);
} else {
// Video is still at the very beginning.
// Check again after a small amount of time.
mVideoView.postDelayed(checkIfPlaying, 100);
}
}
};
#Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Stream is prepared");
mMediaPlayer = mp;
mMediaPlayer.setOnBufferingUpdateListener(this);
mVideoView.requestFocus();
mVideoView.start();
mVideoView.postDelayed(checkIfPlaying, 0);
}
private void pause() {
Log.d(TAG, "Pausing video.");
mVideoView.pause();
}
private void stop() {
Log.d(TAG, "Stopping video.");
mVideoView.stopPlayback();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy triggered.");
stop();
}
private void wrapItUp(int resultCode, String message) {
Log.d(TAG, "wrapItUp was triggered.");
Intent intent = new Intent();
intent.putExtra("message", message);
setResult(resultCode, intent);
finish();
}
public void onCompletion(MediaPlayer mp) {
Log.d(TAG, "onCompletion triggered.");
stop();
if (mShouldAutoClose) {
wrapItUp(RESULT_OK, null);
}
}
public boolean onError(MediaPlayer mp, int what, int extra) {
StringBuilder sb = new StringBuilder();
sb.append("MediaPlayer Error: ");
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
}
sb.append(" (" + what + ") ");
sb.append(extra);
Log.e(TAG, sb.toString());
wrapItUp(RESULT_CANCELED, sb.toString());
return true;
}
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.d(TAG, "onBufferingUpdate : " + percent + "%");
}
#Override
public void onBackPressed() {
// If we're leaving, let's finish the activity
wrapItUp(RESULT_OK, null);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// The screen size changed or the orientation changed... don't restart the activity
super.onConfigurationChanged(newConfig);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (mMediaController != null)
mMediaController.show();
return false;
}
}
I tried to add this, but it does not work very well, the problem is that the progressBar overlaps the NavigationBar, when the device is in portrait mode.
#Override
public boolean onTouchEvent(MotionEvent event) {
if (mMediaController != null){
mMediaController.show();
this.getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
| View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
| View.SYSTEM_UI_FLAG_IMMERSIVE
);
}
return false;
}
Recently I made webview app on Android Studio. And I notice weird problem: When user click on "Browse Image" link nothing happens. I am trying to make a code so user can choose file from their Gallery on mobile phone.
emulator screenshot
Here is my MainActivity.java
package com.ijust2.ijust2;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.ValueCallback;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.File;
public class MainActivity extends Activity {
private WebView webView;
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE=1;
private static final int PICK_IMAGE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new myWebClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://ijust2.com");
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
// This method is used to detect back button
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
// Let the system handle the back button
super.onBackPressed();
}
}
}
my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ijust2.ijust2.MainActivity">
<WebView
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</RelativeLayout>
Can anyone give me some tips or suggest what should I do. I am newbie.
Thanks, Edi
I found a solution. Here is a code:
package it.floryn90.webapp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends ActionBarActivity {
private static final int INPUT_FILE_REQUEST_CODE = 1;
private static final int FILECHOOSER_RESULTCODE = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private WebView webView;
private WebSettings webSettings;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e,
Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
return;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setAllowFileAccess(true);
webView.setWebViewClient(new Client());
webView.setWebChromeClient(new ChromeClient());
if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
else if(Build.VERSION.SDK_INT >=11 && Build.VERSION.SDK_INT < 19) {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.loadUrl("http://example.com"); //change with your website
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return imageFile;
}
public class ChromeClient extends WebChromeClient {
// For Android 5.0
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePath;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
// Create AndroidExampleFolder at sdcard
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
, "AndroidExampleFolder");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
imageStorageDir + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
, new Parcelable[] { captureIntent });
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
// openFileChooser for Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
openFileChooser(uploadMsg, "");
}
//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType,
String capture) {
openFileChooser(uploadMsg, acceptType);
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
public class Client extends WebViewClient {
ProgressDialog progressDialog;
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// If url contains mailto link then open Mail Intent
if (url.contains("mailto:")) {
// Could be cleverer and use a regex
//Open links in new browser
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
// Here we can open new activity
return true;
}else {
// Stay within this webview and load url
view.loadUrl(url);
return true;
}
}
//Show loader on url load
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// Then show progress Dialog
// in standard case YourActivity.this
if (progressDialog == null) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
// Called when all page resources loaded
public void onPageFinished(WebView view, String url) {
try {
// Close progressDialog
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
i'm developing an Android Social app in Android Studio
Can anyone know How to filter bad words / offensive words when posting a new status.
For Example i post something bad words and offensive it will turn to like this "****" also when i post many words it will turn like this "i will hit your ***** right now"
please if you know how to i really need it
Thank you in Advance.
This is my PublishingActivity.java Code
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.iscooldev.socialnetwork.R;
import com.iscooldev.socialnetwork.api.APIService;
import com.iscooldev.socialnetwork.api.GlobalAPI;
import com.iscooldev.socialnetwork.api.PostsAPI;
import com.iscooldev.socialnetwork.api.UsersAPI;
import com.iscooldev.socialnetwork.app.AppConst;
import com.iscooldev.socialnetwork.data.LocationModel;
import com.iscooldev.socialnetwork.data.ResponseModel;
import com.iscooldev.socialnetwork.data.userItem;
import com.iscooldev.socialnetwork.helpers.CacheManager;
import com.iscooldev.socialnetwork.helpers.CropSquareTransformation;
import com.iscooldev.socialnetwork.helpers.FilePath;
import com.iscooldev.socialnetwork.helpers.GPSHelper;
import com.iscooldev.socialnetwork.helpers.M;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;
import com.thin.downloadmanager.DownloadRequest;
import com.thin.downloadmanager.ThinDownloadManager;
import java.io.File;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;
public class PublishActivity extends AppCompatActivity implements OnClickListener, DialogInterface.OnClickListener {
public Intent mIntent;
public LinearLayoutManager layoutManager;
EditText insertedLink;
private ImageView mImagePreview;
private ImageButton addPhoto;
private ImageButton sendStatus;
private ImageButton changePrivacy;
private EditText statusInput;
private TextView profileName, postPrivacy;
private ImageView profilePicture;
private String privacy = "public";
private String statusValue = null;
private String linkValue = null;
private Uri imageUriValue = null;
private LinearLayout urlPreviewLayout;
private TextView urlValuePreview;
private TextView placeValuePreview;
private LinearLayout placePreviewLayout;
private String placeValue = null;
private ThinDownloadManager downloadManager;
private CacheManager mCacheManager;
private Gson mGson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (M.getToken(this) == null) {
Intent mIntent = new Intent(this, LoginActivity.class);
startActivity(mIntent);
finish();
} else {
mCacheManager = CacheManager.getInstance(this);
mGson = new Gson();
setContentView(R.layout.activity_publish);
initializeView();
if (getIntent().hasExtra(Intent.EXTRA_SUBJECT)) {
setStatusValue(getIntent().getExtras().get(Intent.EXTRA_SUBJECT).toString());
}
if (getIntent().hasExtra(Intent.EXTRA_TEXT)) {
String text = getIntent().getExtras().get(Intent.EXTRA_TEXT).toString();
if (M.isValidUrl(text)) {
setLinkValue(text);
} else {
setStatusValue(text);
}
}
if (getIntent().hasExtra(Intent.EXTRA_STREAM)) {
setImageUriValue((Uri) getIntent().getExtras().get(Intent.EXTRA_STREAM));
M.L(getIntent().getType());
}
getUser();
}
}
public void initializeView() {
downloadManager = new ThinDownloadManager(AppConst.DOWNLOAD_THREAD_POOL_SIZE);
addPhoto = (ImageButton) findViewById(R.id.addPhoto);
sendStatus = (ImageButton) findViewById(R.id.sendStatus);
changePrivacy = (ImageButton) findViewById(R.id.changePrivacy);
mImagePreview = (ImageView) findViewById(R.id.imagePreview);
statusInput = (EditText) findViewById(R.id.statusEdittext);
profilePicture = (ImageView) findViewById(R.id.postOwnerImage);
profileName = (TextView) findViewById(R.id.postOwnerName);
postPrivacy = (TextView) findViewById(R.id.postPrivacy);
TextView removeLink = (TextView) findViewById(R.id.removeLink);
TextView removePlace = (TextView) findViewById(R.id.removePlace);
ImageButton addPlace = (ImageButton) findViewById(R.id.addPlace);
ImageButton addLink = (ImageButton) findViewById(R.id.addLink);
placePreviewLayout = (LinearLayout) findViewById(R.id.placePreviewLayout);
placeValuePreview = (TextView) findViewById(R.id.placeValuePreview);
urlPreviewLayout = (LinearLayout) findViewById(R.id.urlPreviewLayout);
urlValuePreview = (TextView) findViewById(R.id.urlValuePreview);
sendStatus.setOnClickListener(this);
addPhoto.setOnClickListener(this);
changePrivacy.setOnClickListener(this);
addPlace.setOnClickListener(this);
addLink.setOnClickListener(this);
removePlace.setOnClickListener(this);
removeLink.setOnClickListener(this);
//including toolbar and enabling the home button
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(getString(R.string.title_publish));
}
private void getUser() {
if (M.isNetworkAvailable(this)) {
UsersAPI mUsersAPI = APIService.createService(UsersAPI.class, M.getToken(this));
mUsersAPI.getUser(0, new Callback<userItem>() {
#Override
public void success(userItem user, retrofit.client.Response response) {
try {
mCacheManager.write(mGson.toJson(user), "Profile-0.json");
updateView(user);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void failure(RetrofitError error) {
}
});
} else {
try {
updateView((userItem) mGson.fromJson(mCacheManager.readString("Profile-0.json"), new TypeToken<userItem>() {
}.getType()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void updateView(userItem user) {
if (user.getName() != null) {
profileName.setText(user.getName());
} else {
profileName.setText(user.getUsername());
}
if (getFilePath(user.getPicture()) != null) {
Picasso.with(getApplicationContext())
.load(getFilePath(user.getPicture()))
.transform(new CropSquareTransformation())
.placeholder(R.drawable.image_holder)
.error(R.drawable.image_holder)
.into(profilePicture);
} else {
Picasso.with(getApplicationContext())
.load(AppConst.IMAGE_PROFILE_URL + user.getPicture())
.transform(new CropSquareTransformation())
.placeholder(R.drawable.image_holder)
.error(R.drawable.image_holder)
.into(profilePicture);
downloadFile(AppConst.IMAGE_PROFILE_URL + user.getPicture(), user.getPicture());
}
}
private void downloadFile(String url, String hash) {
if (getFilePath(hash) == null) {
Uri downloadUri = Uri.parse(url);
Uri destinationUri = Uri.parse(M.getFilePath(getApplicationContext(), hash));
DownloadRequest downloadRequest = new DownloadRequest(downloadUri)
.setDestinationURI(destinationUri);
downloadManager.add(downloadRequest);
}
}
private String getFilePath(String hash) {
return M.filePath(getApplicationContext(), hash);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == AppConst.SELECT_PICTURE) {
setImageUriValue(data.getData());
}
}
}
#Override
public void onClick(final View v) {
if (v.getId() == R.id.removePlace) {
setPlaceValue(null);
} else if (v.getId() == R.id.removeLink) {
setLinkValue(null);
} else if (v.getId() == R.id.addPlace) {
final GPSHelper mGpsHelper = new GPSHelper(this);
if (mGpsHelper.canGetLocation()) {
GlobalAPI mGlobalAPI = APIService.createService(GlobalAPI.class, M.getToken(this));
mGlobalAPI.getCurrentPlace(mGpsHelper.getLatitude(), mGpsHelper.getLongitude(), new Callback<LocationModel>() {
#Override
public void success(LocationModel location, retrofit.client.Response response) {
if (location.isStatus()) {
setPlaceValue(location.getAddress());
} else {
mGpsHelper.showSettingsAlert();
}
}
#Override
public void failure(RetrofitError error) {
mGpsHelper.showSettingsAlert();
}
});
} else {
mGpsHelper.showSettingsAlert();
}
} else if (v.getId() == R.id.addLink) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(getString(R.string.Insert_a_link));
insertedLink = new EditText(this);
insertedLink.setText("http://");
alert.setView(insertedLink);
alert.setPositiveButton(getString(R.string.ok), this);
alert.setNegativeButton(getString(R.string.cancel), this);
alert.show();
} else if (v.getId() == addPhoto.getId()) {
launchImageChooser();
} else if (v.getId() == sendStatus.getId()) {
String statusText = statusInput.getText().toString().trim();
if (!statusText.isEmpty()) {
setStatusValue(statusText);
}
if (getStatusValue() == null && getImageUriValue() == null && getLinkValue() == null) {
M.T(v,
getString(R.string.Error_empty_post));
} else {
PostsAPI mPostsAPI = APIService.createService(PostsAPI.class, M.getToken(this));
TypedFile image = null;
if (getImageUriValue() != null) {
image = new TypedFile("image/jpg", new File(FilePath.getPath(this, getImageUriValue())));
}
M.showLoadingDialog(this);
mPostsAPI.publishPost(image, getStatusValue(), getLinkValue(), getPlaceValue(), privacy, new Callback<ResponseModel>() {
#Override
public void success(ResponseModel responseModel, Response response) {
M.hideLoadingDialog();
M.T(v, responseModel.getMessage());
if (responseModel.isDone()) {
startActivity(new Intent(PublishActivity.this, MainActivity.class));
finish();
}
}
#Override
public void failure(RetrofitError error) {
M.hideLoadingDialog();
M.T(v, getString(R.string.ServerError));
}
});
}
} else if (v.getId() == changePrivacy.getId()) {
if (privacy.equals("public")) {
postPrivacy.setText(R.string.privatePrivacy);
privacy = "private";
M.T(v, getString(R.string.changed_to_private));
} else {
postPrivacy.setText(R.string.publicPrivacy);
privacy = "public";
M.T(v, getString(R.string.changed_to_public));
}
}
}
private void launchImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Choose An Image"),
AppConst.SELECT_PICTURE);
}
#Override
public void onClick(DialogInterface dialog, int which) {
String Link = insertedLink.getText().toString();
if (!Link.equals("http://") && !Link.equals("")) {
setLinkValue(Link);
}
}
public String getPlaceValue() {
return placeValue;
}
public void setPlaceValue(String placeValue) {
if (placeValue != null) {
if (placePreviewLayout.getVisibility() != View.VISIBLE) {
placePreviewLayout.setVisibility(View.VISIBLE);
placeValuePreview.setText(placeValue);
}
} else {
if (placePreviewLayout.getVisibility() != View.GONE) {
placePreviewLayout.setVisibility(View.GONE);
placeValuePreview.setText("");
}
}
this.placeValue = placeValue;
}
public Uri getImageUriValue() {
return imageUriValue;
}
public void setImageUriValue(Uri imageUriValue) {
this.imageUriValue = imageUriValue;
mImagePreview.setImageURI(imageUriValue);
if (mImagePreview.getVisibility() != View.VISIBLE) {
mImagePreview.setVisibility(View.VISIBLE);
}
}
public String getLinkValue() {
return linkValue;
}
public void setLinkValue(String linkValue) {
if (linkValue != null) {
if (urlPreviewLayout.getVisibility() != View.VISIBLE) {
urlPreviewLayout.setVisibility(View.VISIBLE);
urlValuePreview.setText(linkValue);
}
} else {
if (urlPreviewLayout.getVisibility() != View.GONE) {
urlPreviewLayout.setVisibility(View.GONE);
urlValuePreview.setText("");
}
}
this.linkValue = linkValue;
}
public String getStatusValue() {
return statusValue;
}
public void setStatusValue(String statusValue) {
String statusInputValue = statusInput.getText().toString().trim();
if (!statusValue.equals(statusInputValue)) {
String finalStatus;
if (TextUtils.isEmpty(statusInputValue)) {
finalStatus = statusValue;
} else {
finalStatus = statusInputValue + " " + statusValue;
}
statusInput.setText(finalStatus);
this.statusValue = finalStatus;
} else {
this.statusValue = statusValue;
}
}
}
Suppose you have an input string s and the list of words you want to replace by asterisks:
String s = "i will hit your head right now";
List<String> words = Arrays.asList("head", "now"); // suppose these words are offensive
You just iterate over list of offensive words, looking if input string contains one, and perform a replacement. The simplest way to do this is by using regex:
for (String word : words) {
Pattern rx = Pattern.compile("\\b" + word + "\\b", Pattern.CASE_INSENSITIVE);
s = rx.matcher(s).replaceAll(new String(new char[word.length()]).replace('\0', '*'));
}
// s: i will hit your **** right ***
I've added \\b at the front and end of regex pattern to match just whole words (i. e. "head" will be processed, "header" will not). And this piece:
new String(new char[n]).replace('\0', c)
constructs a new string of n chars c.
After that, use resulting s wherever you need.
It is a basic about java, not android related. A way to do this is you make a list of your bad words and replace it from the string that user input. Refer to example below
String userInput = "this is an example of some bad words";
ArrayList<String> badWords = new ArrayList<>();
badWords.add("some");
badWords.add("bad");
badWords.add("words");
for (int i = 0; i < badWords.size(); i++) {
String badWord = badWords.get(i);
if(userInput.toLowerCase().contains(badWord)){
userInput = userInput.replace(badWord, "*****");
}
}