Android app - using AsyncTask - stops opening a URL in WebView, it is opened by the default browser if I call another URL - browser

I'm beginning to develop in android using the material from http://developer.android.com.
I took one of their examples and modified it, so that my application can connect to a webpage. It works well when it is opened but if I click on an actionBar item which should open another page the new page isn't opened in the WebView, but it's launched the default browser.
I tried in many way to understand how to avoid that, but my little experience didn't allow me to fixe the problem.
Can you help me?
Many thanks.
Nino
public class MainActivity extends Activity {
public static final String WIFI = "Wi-Fi";
public static final String ANY = "Any";
public static String PAGINA ="http://www.kibao.org/simu/wap.php?lng=";
public static String BASE ="http://www.kibao.org";
public static String ATTUALE ="";
public static String lng = "";
final Context context = this;
private static boolean wifiConnected = false;
private static boolean mobileConnected = false;
public static boolean refreshDisplay = true;
public static String sPref = null;
public static String pagina = "";
private NetworkReceiver receiver = new NetworkReceiver();
#Override
public void onCreate(Bundle savedInstanceState) {
lng = getResources().getString(R.string.lng);
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new NetworkReceiver();
this.registerReceiver(receiver, filter);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public void onStart() {
super.onStart();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
sPref = sharedPrefs.getString("listPref", "Wi-Fi");
updateConnectedFlags();
if (refreshDisplay) {
ATTUALE=PAGINA.concat(lng);
loadPage(ATTUALE);
}
}
#Override
public void onDestroy() {
super.onStop();
String ciao = getResources().getString(R.string.ciao);
show_toast(ciao);
if (receiver != null) {
this.unregisterReceiver(receiver);
}
}
private void updateConnectedFlags() {
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
if (activeInfo != null && activeInfo.isConnected()) {
wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
} else {
wifiConnected = false;
mobileConnected = false;
}
}
private void loadPage(String pgUrl) {
if (((sPref.equals(ANY)) && (wifiConnected || mobileConnected))
|| ((sPref.equals(WIFI)) && (wifiConnected))) {
new DownloadWebpageTask().execute(pgUrl);
} else {
showErrorPage();
}
}
// Displays an error if the app is unable to load content.
private void showErrorPage() {
....
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.items, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu1:
if (refreshDisplay) {
ATTUALE=BASE.concat("/partite.php?lng=");
ATTUALE=ATTUALE.concat(lng);
loadPage(ATTUALE);
}
return true;
....
default:
return super.onOptionsItemSelected(item);
}
}
private InputStream downloadUrl(String urlString) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
InputStream stream = conn.getInputStream();
return stream;
}
public class NetworkReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connMgr =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (WIFI.equals(sPref) && networkInfo != null
&& networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
refreshDisplay = true;
Toast.makeText(context, R.string.wifi_connected, Toast.LENGTH_SHORT).show();
} else if (ANY.equals(sPref) && networkInfo != null) {
refreshDisplay = true;
} else {
refreshDisplay = false;
Toast.makeText(context, R.string.lost_connection, Toast.LENGTH_SHORT).show();
}
}
}
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
return loadWebpageFromNetwork(urls[0]);
} catch (IOException e) {
return getResources().getString(R.string.connection_error);
}
}
#Override
protected void onPostExecute(String result) {
setContentView(R.layout.main);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl(ATTUALE);
}
}
private String loadWebpageFromNetwork(String urlString) throws IOException {
InputStream stream = null;
try {
stream = downloadUrl(urlString);
pagina = getStringFromInputStream(stream);
} finally {
if (stream != null) {
stream.close();
}
}
return pagina;
}
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
........
}

This DownloadWebpageTask tries to "download" a webpage into a string, using a webview. This is not the correct way to do it. You are using the wrong tutorial. Don't use AsyncTasks for this. Start all over, using this:
http://developer.android.com/reference/android/webkit/WebView.html
or
http://www.mkyong.com/android/android-webview-example/
Simply call webview.loadUrl(url) again with a different url if you want to load a different page. It's as simple as that.

I've found another solution that works. I added the line
myWebView.setWebViewClient(new WebViewClient());
in the onPostExecute:
protected void onPostExecute(String result) {
setContentView(R.layout.main);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl(ATTUALE);
}
Thanks, Frank.
PS I've tried to add a comment to the last Frank's post, but I didn't succeed!

Related

how to connect uvc camera with agora video call

i am tried to stream video from uvc camera with agora video call api. but it doesn't work . but the uvc camera preview show proferly on '''''' .
public class VideoChatViewActivity extends AppCompatActivity implements CameraDialog.CameraDialogParent, CameraViewInterface.Callback{
private static final String TAG = VideoChatViewActivity.class.getSimpleName();
private static final int PERMISSION_REQ_ID = 22;
// Permission WRITE_EXTERNAL_STORAGE is not mandatory
// for Agora RTC SDK, just in case if you wanna save
// logs to external sdcard.
private static final String[] REQUESTED_PERMISSIONS = {
Manifest.permission.RECORD_AUDIO,
Manifest.permission.CAMERA
};
private RtcEngine mRtcEngine;
private boolean mCallEnd;
private boolean mMuted;
private FrameLayout mLocalContainer;
private RelativeLayout mRemoteContainer;
private VideoCanvas mLocalVideo;
private VideoCanvas mRemoteVideo;
private ImageView mCallBtn;
private ImageView mMuteBtn;
private ImageView mSwitchCameraBtn;
// Customized logger view
private LoggerRecyclerView mLogView;
private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() {
#Override
public void onJoinChannelSuccess(String channel, final int uid, int elapsed) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLogView.logI("Join channel success, uid: " + (uid & 0xFFFFFFFFL));
}
});
}
#Override
public void onUserJoined(final int uid, int elapsed) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLogView.logI("First remote video decoded, uid: " + (uid & 0xFFFFFFFFL));
setupRemoteVideo(uid);
}
});
}
#Override
public void onUserOffline(final int uid, int reason) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLogView.logI("User offline, uid: " + (uid & 0xFFFFFFFFL));
onRemoteUserLeft(uid);
}
});
}
};
private void setupRemoteVideo(int uid) {
ViewGroup parent = mRemoteContainer;
if (parent.indexOfChild(mLocalVideo.view) > -1) {
parent = mLocalContainer;
}
if (mRemoteVideo != null) {
return;
}
SurfaceView view = RtcEngine.CreateRendererView(getBaseContext());
view.setZOrderMediaOverlay(parent == mLocalContainer);
parent.addView(view);
mRemoteVideo = new VideoCanvas(view, VideoCanvas.RENDER_MODE_HIDDEN, uid);
// Initializes the video view of a remote user.
mRtcEngine.setupRemoteVideo(mRemoteVideo);
}
private void onRemoteUserLeft(int uid) {
if (mRemoteVideo != null && mRemoteVideo.uid == uid) {
removeFromParent(mRemoteVideo);
// Destroys remote view
mRemoteVideo = null;
}
}
//usb
private static final int DEFAULT_CAPTURE_WIDTH = 1280;
private static final int DEFAULT_CAPTURE_HEIGHT = 720;
#BindView(R.id.camer_view)
public View mTextureView;
private static final String TAG1 = "Debug";
private UVCCameraHelper mCameraHelper;
private CameraViewInterface mUVCCameraView;
private AlertDialog mDialog;
private boolean isRequest;
private boolean isPreview;
private UVCCameraHelper.OnMyDevConnectListener listener = new UVCCameraHelper.OnMyDevConnectListener() {
#Override
public void onAttachDev(UsbDevice device) {
// request open permission
if (!isRequest) {
isRequest = true;
if (mCameraHelper != null) {
mCameraHelper.requestPermission(0);
}
}
}
#Override
public void onDettachDev(UsbDevice device) {
// close camera
if (isRequest) {
isRequest = false;
mCameraHelper.closeCamera();
showShortMsg(device.getDeviceName() + " is out");
}
}
#Override
public void onConnectDev(UsbDevice device, boolean isConnected) {
if (!isConnected) {
showShortMsg("fail to connect,please check resolution params");
isPreview = false;
} else {
isPreview = true;
showShortMsg("connecting");
// initialize seekbar
// need to wait UVCCamera initialize over
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(2500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Looper.prepare();
if(mCameraHelper != null && mCameraHelper.isCameraOpened()) {
}
Looper.loop();
}
}).start();
}
}
#Override
public void onDisConnectDev(UsbDevice device) {
showShortMsg("disconnecting");
}
};
//usb
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_chat_view);
ButterKnife.bind(this);//uvc
initUI();
mUVCCameraView = (CameraViewInterface) mTextureView;
mUVCCameraView.setCallback(this);
//mLocalContainer.setCallback(this);
mCameraHelper = UVCCameraHelper.getInstance();
mCameraHelper.setDefaultPreviewSize(1280,720);
mCameraHelper.initUSBMonitor(this, mUVCCameraView, listener);
mCameraHelper.setOnPreviewFrameListener(new AbstractUVCCameraHandler.OnPreViewResultListener() {
#Override
public void onPreviewResult(byte[] bytes) {
try {
AgoraVideoFrame frame = new AgoraVideoFrame();
frame.buf = bytes;
frame.format = AgoraVideoFrame.FORMAT_NV21;
frame.stride = DEFAULT_CAPTURE_WIDTH;
frame.height = DEFAULT_CAPTURE_HEIGHT;
frame.timeStamp = System.currentTimeMillis();
mRtcEngine.pushExternalVideoFrame(frame);
}catch (Exception e){
e.printStackTrace();
}
}
});
// Ask for permissions at runtime.
// This is just an example set of permissions. Other permissions
// may be needed, and please refer to our online documents.
if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) &&
checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID)) {
initEngineAndJoinChannel();
}
}
private void initUI() {
mLocalContainer = findViewById(R.id.local_video_view_container);
mRemoteContainer = findViewById(R.id.remote_video_view_container);
mCallBtn = findViewById(R.id.btn_call);
mMuteBtn = findViewById(R.id.btn_mute);
mSwitchCameraBtn = findViewById(R.id.btn_switch_camera);
mLogView = findViewById(R.id.log_recycler_view);
// Sample logs are optional.
showSampleLogs();
}
private void showSampleLogs() {
mLogView.logI("Welcome to Agora 1v1 video call");
mLogView.logW("You will see custom logs here");
mLogView.logE("You can also use this to show errors");
}
private boolean checkSelfPermission(String permission, int requestCode) {
if (ContextCompat.checkSelfPermission(this, permission) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, REQUESTED_PERMISSIONS, requestCode);
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQ_ID) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED ||
grantResults[1] != PackageManager.PERMISSION_GRANTED ||
grantResults[2] != PackageManager.PERMISSION_GRANTED) {
showLongToast("Need permissions " + Manifest.permission.RECORD_AUDIO +
"/" + Manifest.permission.CAMERA);
finish();
return;
}
// Here we continue only if all permissions are granted.
// The permissions can also be granted in the system settings manually.
initEngineAndJoinChannel();
}
}
private void showLongToast(final String msg) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
private void initEngineAndJoinChannel() {
initializeEngine();
setupVideoConfig();
setupLocalVideo();
joinChannel();
}
private void initializeEngine() {
try {
mRtcEngine = RtcEngine.create(getBaseContext(), getString(R.string.agora_app_id), mRtcEventHandler);
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
}
}
private void setupVideoConfig() {
mRtcEngine.enableVideo();
mRtcEngine.setVideoEncoderConfiguration(new VideoEncoderConfiguration(
VideoEncoderConfiguration.VD_640x360,
VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15,
VideoEncoderConfiguration.STANDARD_BITRATE,
VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_PORTRAIT));
}
private void setupLocalVideo() {
.
SurfaceView view = RtcEngine.CreateRendererView(getBaseContext());
view.setZOrderMediaOverlay(true);
mLocalContainer.addView(view);
mLocalVideo = new VideoCanvas(view, VideoCanvas.RENDER_MODE_HIDDEN, 0);
mRtcEngine.setupLocalVideo(mLocalVideo);
}
private void joinChannel() {
String token = getString(R.string.agora_access_token);
if (TextUtils.isEmpty(token) || TextUtils.equals(token, "#YOUR ACCESS TOKEN#")) {
token = null; // default, no token
}
mRtcEngine.joinChannel(token, "streaming", "Extra Optional Data", 0);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (!mCallEnd) {
leaveChannel();
}
RtcEngine.destroy();
}
private void leaveChannel() {
mRtcEngine.leaveChannel();
}
public void onLocalAudioMuteClicked(View view) {
mMuted = !mMuted;
mRtcEngine.muteLocalAudioStream(mMuted);
int res = mMuted ? R.drawable.btn_mute : R.drawable.btn_unmute;
mMuteBtn.setImageResource(res);
}
public void onSwitchCameraClicked(View view) {
mRtcEngine.switchCamera();
}
public void onCallClicked(View view) {
if (mCallEnd) {
startCall();
mCallEnd = false;
mCallBtn.setImageResource(R.drawable.btn_endcall);
} else {
endCall();
mCallEnd = true;
mCallBtn.setImageResource(R.drawable.btn_startcall);
}
showButtons(!mCallEnd);
}
private void startCall() {
setupLocalVideo();
joinChannel();
}
private void endCall() {
removeFromParent(mLocalVideo);
mLocalVideo = null;
removeFromParent(mRemoteVideo);
mRemoteVideo = null;
leaveChannel();
}
private void showButtons(boolean show) {
int visibility = show ? View.VISIBLE : View. SurfaceView view .GONE;
mMuteBtn.setVisibility(visibility);
mSwitchCameraBtn.setVisibility(visibility);
}
private ViewGroup removeFromParent(VideoCanvas canvas) {
if (canvas != null) {
ViewParent parent = canvas.view.getParent();
if (parent != null) {
ViewGroup group = (ViewGroup) parent;
group.removeView(canvas.view);
return group;
}
}
return null;
}
private void switchView(VideoCanvas canvas) {
ViewGroup parent = removeFromParent(canvas);
if (parent == mLocalContainer) {
if (canvas.view instanceof SurfaceView) {
((SurfaceView) canvas.view).setZOrderMediaOverlay(false);
}
mRemoteContainer.addView(canvas.view);
} else if (parent == mRemoteContainer) {
if (canvas.view instanceof SurfaceView) {
((SurfaceView) canvas.view).setZOrderMediaOverlay(true);
}
mLocalContainer.addView(canvas.view);
}
}
public void onLocalContainerClick(View view) {
switchView(mLocalVideo);
switchView(mRemoteVideo);
}
///uvc
#Override
protected void onStart() {
super.onStart();
// step.2 register USB event broadcast
if (mCameraHelper != null) {
mCameraHelper.registerUSB();
}
}
#Override
protected void onStop() {
super.onStop();
// step.3 unregister USB event broadcast
if (mCameraHelper != null) {
mCameraHelper.unregisterUSB();
}
}
private void showShortMsg(String msg) {
//
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public USBMonitor getUSBMonitor(){ return mCameraHelper.getUSBMonitor();
}
#Override
public void onDialogResult(boolean canceled) {
if (canceled) {
showShortMsg("cancel");
}
}
#Override
public void onSurfaceCreated(CameraViewInterface cameraViewInterface, Surface surface) {
if (!isPreview && mCameraHelper.isCameraOpened()) {
mCameraHelper.startPreview(mUVCCameraView);
isPreview = true;
}
}
#Override
public void onSurfaceChanged(CameraViewInterface cameraViewInterface, Surface surface, int i, int i1) {
}
#Override
public void onSurfaceDestroy(CameraViewInterface cameraViewInterface, Surface surface) {
if (isPreview && mCameraHelper.isCameraOpened()) {
mCameraHelper.stopPreview();
isPreview = false;
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_chat_view);
initUI();
// Ask for permissions at runtime.
// This is just an example set of permissions. Other permissions
// may be needed, and please refer to our online documents.
if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) &&
checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID)) {
initEngineAndJoinChannel();
}
//xiaobing add
final View view = findViewById(R.id.camera_view);
mUVCCameraView = (CameraViewInterface)view;
mUSBMonitor = new USBMonitor(this, mOnDeviceConnectListener);
mUVCCameraView.setAspectRatio(previewWidth / (float)previewHeight);
mCameraHandler = UVCCameraHandler.createHandler(this,
mUVCCameraView, previewWidth,
previewHeight, BANDWIDTH_FACTORS[0],
firstDataCallBack);
}
//xiaobing add
private void startPreview() {
final SurfaceTexture st = mUVCCameraView.getSurfaceTexture();
mCameraHandler.startPreview(new Surface(st));
}
//xiaobing add
UvcCameraDataCallBack firstDataCallBack = new UvcCameraDataCallBack() {
#Override
public void getData(byte[] data) {
if (DEBUG) {
Log.v(TAG, "data callback:" + data.length);
}
AgoraVideoFrame frame = new AgoraVideoFrame();
frame.buf = data;
frame.format = AgoraVideoFrame.FORMAT_NV12;
frame.stride = previewWidth;
frame.height = previewHeight;
frame.timeStamp = System.currentTimeMillis();
mRtcEngine.pushExternalVideoFrame(frame);
}
};
//xiaobing add
#Override
protected void onStart() {
super.onStart();
if (DEBUG) Log.v(TAG, "onStart:");
mUSBMonitor.register();
if (mUVCCameraView != null)
mUVCCameraView.onResume();
if (!mCameraHandler.isOpened()) {
UsbManager um = (UsbManager) (getSystemService(Context.USB_SERVICE));
HashMap<String, UsbDevice> map = um.getDeviceList();
ArrayList<String> names = new ArrayList<>();
final ArrayList<UsbDevice> devices = new ArrayList<>();
for(Map.Entry<String, UsbDevice> item : map.entrySet()) {
String name = item.getValue().getProductName();
String vid = Integer.toHexString(item.getValue().getVendorId());
String pid = Integer.toHexString(item.getValue().getProductId());
String all = "" + name + " VID:" + vid
+ " PID:" + pid;
Log.v("xiaobing", "all:" + all);
names.add(all);
devices.add(item.getValue());
if(item.getValue().getProductId()==1383 && (item.getValue().getVendorId() == 3034)){
mDev = item.getValue();
mUSBMonitor.requestPermission(mDev);
//为了同时支持手机和眼镜,只有获得了眼镜的设备才选择本地视频
mRtcEngine.setExternalVideoSource(true, true, true);
mLogView.logI("使用USB摄像头!");
break;
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Android: Unable to pause activity ava.lang.IllegalArgumentException: Service not registered: NowPlayingFragmentBottom

I got these error when I pressed any song how to solve this!! I got these java.lang.IllegalArgumentException error. please anyone?
NowPlayingFragmentBottom
public class NowPlayingFragmentBottom extends Fragment implements ServiceConnection {
ImageView nextBtn, prevBtn, albumArt;
TextView artist, songName;
FloatingActionButton playPauseBtn;
View view;
MusicService musicService;
public static final String MUSIC_LAST_PLAYED = "LAST_PLAYED";
public static final String MUSIC_FILE = "STORED_MUSIC";
public static final String ARTIST_NAME = "ARTIST NAME";
public static final String SONG_NAME = "SONG NAME";
public NowPlayingFragmentBottom() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_now_playing_bottom, container, false);
artist = view.findViewById(R.id.song_artist_miniPlayer);
songName = view.findViewById(R.id.song_name_miniPlayer);
nextBtn = view.findViewById(R.id.skip_next_bottom);
prevBtn = view.findViewById(R.id.skip_prev_bottom);
albumArt = view.findViewById(R.id.bottom_album_art);
playPauseBtn = view.findViewById(R.id.play_pause_miniPlayer);
//prev , next , playpause
prevBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
if(musicService != null){
musicService.prevBtnClicked();
if(getActivity() != null) {
SharedPreferences.Editor editor = getActivity().getSharedPreferences(MUSIC_LAST_PLAYED, MODE_PRIVATE).edit();
editor.putString(MUSIC_FILE, musicService.musicFiles.get(musicService.position).getPath());
editor.putString(ARTIST_NAME, musicService.musicFiles.get(musicService.position).getArtist());
editor.putString(SONG_NAME, musicService.musicFiles.get(musicService.position).getTitle());
editor.apply();
SharedPreferences preferences = getActivity().getSharedPreferences(MUSIC_LAST_PLAYED,MODE_PRIVATE);
String path = preferences.getString(MUSIC_FILE,null);
String artistName = preferences.getString(ARTIST_NAME,null);
String song_name = preferences.getString(SONG_NAME,null);
if(path != null){
SHOW_MINI_PLAYER = true;
PATH_TO_FRAGMENT = path;
ARTIST_TO_FRAGMENT = artistName;
SONG_NAME_TO_FRAGMENT = song_name;
}
else{
SHOW_MINI_PLAYER = false;
PATH_TO_FRAGMENT = null;
ARTIST_TO_FRAGMENT = null;
SONG_NAME_TO_FRAGMENT = null;
}
if (SHOW_MINI_PLAYER ){
if(PATH_TO_FRAGMENT !=null) {
byte[] art = getAlbumArt(PATH_TO_FRAGMENT);
if(art != null) {
Glide.with(getContext())
.load(art)
.into(albumArt);
}
else {
Glide.with(getContext())
.load(R.drawable.m2)
.into(albumArt);
}
songName.setText(SONG_NAME_TO_FRAGMENT);
artist.setText(ARTIST_TO_FRAGMENT);
}
}
}
}}
});
I got these error when I pressed any song how to solve this!! I got these java.lang.IllegalArgumentException error. please anyone?
nextBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
if(musicService != null){
musicService.nextBtnClicked();
if(getActivity() != null) {
SharedPreferences.Editor editor = getActivity().getSharedPreferences(MUSIC_LAST_PLAYED, MODE_PRIVATE).edit();
editor.putString(MUSIC_FILE, musicService.musicFiles.get(musicService.position).getPath());
editor.putString(ARTIST_NAME, musicService.musicFiles.get(musicService.position).getArtist());
editor.putString(SONG_NAME, musicService.musicFiles.get(musicService.position).getTitle());
editor.apply();
SharedPreferences preferences = getActivity().getSharedPreferences(MUSIC_LAST_PLAYED,MODE_PRIVATE);
String path = preferences.getString(MUSIC_FILE,null);
String artistName = preferences.getString(ARTIST_NAME,null);
String song_name = preferences.getString(SONG_NAME,null);
if(path != null){
SHOW_MINI_PLAYER = true;
PATH_TO_FRAGMENT = path;
ARTIST_TO_FRAGMENT = artistName;
SONG_NAME_TO_FRAGMENT = song_name;
}
else{
SHOW_MINI_PLAYER = false;
PATH_TO_FRAGMENT = null;
ARTIST_TO_FRAGMENT = null;
SONG_NAME_TO_FRAGMENT = null;
}
if (SHOW_MINI_PLAYER){
if(PATH_TO_FRAGMENT !=null) {
byte[] art = getAlbumArt(PATH_TO_FRAGMENT);
if(art != null) {
Glide.with(getContext())
.load(art)
.into(albumArt);
}
else {
Glide.with(getContext())
.load(R.drawable.m2)
.into(albumArt);
}
songName.setText(SONG_NAME_TO_FRAGMENT);
artist.setText(ARTIST_TO_FRAGMENT);
}
}
}
}
}
});
playPauseBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
if(musicService != null){
musicService.playPauseBtnClicked();
if(musicService.isPlaying()){
playPauseBtn.setImageResource(R.drawable.ic_pause);
}
else{
playPauseBtn.setImageResource(R.drawable.ic_play);
}
}
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
if (SHOW_MINI_PLAYER){
if(PATH_TO_FRAGMENT !=null) {
byte[] art = getAlbumArt(PATH_TO_FRAGMENT);
if(art != null) {
Glide.with(getContext())
.load(art)
.into(albumArt);
}
else {
Glide.with(getContext())
.load(R.drawable.m2)
.into(albumArt);
}
songName.setText(SONG_NAME_TO_FRAGMENT);
artist.setText(ARTIST_TO_FRAGMENT);
Intent intent = new Intent(getContext(),MusicService.class);
if(getContext() != null){
getContext().bindService(intent,this, Context.BIND_AUTO_CREATE);
}
}
}
}
#Override
public void onPause() {
super.onPause();
if(getContext() != null ){
getContext().unbindService(this);
}
}
private byte[] getAlbumArt(String uri)
{
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(uri);
byte[] art = retriever.getEmbeddedPicture();
retriever.release();
return art;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.MyBinder myBinder = (MusicService.MyBinder) service;
musicService = myBinder.getService();
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicService = null;
}
}
logcat
java.lang.RuntimeException: Unable to pause activity {com.example.musicplayer/com.example.musicplayer.MainActivity}: java.lang.IllegalArgumentException: Service not registered: NowPlayingFragmentBottom{6943cbf} (57d50a80-8e02-4b9c-8455-ad91860cbc9d id=0xffffffff)
at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:4503)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:4454)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:4406)
at android.app.servertransaction.PauseActivityItem.execute(PauseActivityItem.java:46)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.IllegalArgumentException: Service not registered: NowPlayingFragmentBottom{6943cbf} (57d50a80-8e02-4b9c-8455-ad91860cbc9d id=0xffffffff)
at com.example.musicplayer.Fragments.NowPlayingFragmentBottom.onPause(NowPlayingFragmentBottom.java:259)
here , I post the logcat, where show service is not registered but I don't understand where the issue is happening. What is the issue?

Loading image from URL to ListView

I am trying to make a list view. I did it successfully without the photos loading from url without using a custom array adapter. However how can I implement loading images from url without using a custom array adapter?
I am trying to use the working codes from this thread but it is giving an error for holder.
Error Part
icon = new ImageDownloaderTask(holder.imageView).execute(doctorPhoto);
DoctorsActivity.java
public class DoctorsActivity extends AppCompatActivity {
private JSONArray arrayAdapter;
private static final String URL_FOR_BALANCE = "http://192.168.1.28/api2/doctors.php";
String cancel_req_tag = "login";
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
Bitmap icon = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctors);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.toolbar_doctors);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#003764")));
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
final String pid = sharedPreferences.getString(Config.UID_SHARED_PREF, null);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_BALANCE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
JSONArray contacts = jObj.getJSONArray("user");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String doctorTitle = c.getString("title");
String doctorName = c.getString("first_name");
String doctorSurname = c.getString("last_name");
String doctorPhoto = c.getString("photo"); //image URL
String doctorMobile = c.getString("mobile");
String doctorFullName = doctorTitle+" "+doctorName+" "+doctorSurname;
icon = new ImageDownloaderTask(holder.imageView).execute(doctorPhoto);
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("photo", icon);
contact.put("doctor", doctorFullName);
contact.put("mobile", doctorMobile);
// adding contact to contact list
contactList.add(contact);
}
ListAdapter adapter = new SimpleAdapter(
DoctorsActivity.this, contactList,
R.layout.activity_doctors_list_item, new String[]{"photo", "doctor",
"mobile"}, new int[]{R.id.photo,
R.id.doctor, R.id.mobile});
lv.setAdapter(adapter);
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to login url
Map<String, String> params = new HashMap<String, String>();
params.put("uid", pid);
params.put("lang", Locale.getDefault().getDisplayLanguage());
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq,cancel_req_tag);
}
class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = null;
imageView.setImageDrawable(placeholder);
}
}
}
}
private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
final int responseCode = urlConnection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.w("ImageDownloader", "Errore durante il download da " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
}
}
Why not use a 3rd party lib like https://github.com/bumptech/glide?
Relevant code:
// ...
new Glide
.with(convertView.getContext())
.load(url)
.centerCrop()
.placeholder(R.drawable.noimage)
.crossFade()
.into(bmImage);
holder.tvName.setText(doctorList.get(position).getName());
holder.tvMobile.setText(doctorList.get(position).getMobile());
// ...
For everyone who wants to have listView with images this my corrected working Custom Adapter:
public class DoctorAdapter extends ArrayAdapter<Doctors>{
ArrayList<Doctors> doctorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public DoctorAdapter(Context context, int resource, ArrayList<Doctors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
doctorList = objects;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.photo);
holder.tvName = (TextView) v.findViewById(R.id.doctor);
holder.tvMobile = (TextView) v.findViewById(R.id.mobile);
holder.callButton = (Button) v.findViewById(R.id.btnCall);
holder.callButton.setTag(holder);
holder.callButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewHolder viewHolder = (ViewHolder) view.getTag();
String message= viewHolder.tvMobile.getText().toString();
Toast.makeText(view.getContext(), message, Toast.LENGTH_SHORT).show();
}
});
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.noimage);
new DownloadImageTask(holder.imageview).execute(doctorList.get(position).getImage());
holder.tvName.setText(doctorList.get(position).getName());
holder.tvMobile.setText(doctorList.get(position).getMobile());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView tvName;
public TextView tvMobile;
public Button callButton;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}

How to load image from api into gridview using adapter in android studio?

public class MainActivityFragment extends Fragment {
static String[] str1;
GridView gridview;
public MainActivityFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.refresh_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if (id == R.id.action_refresh) {
updateWeather();
return true;
}
return super.onOptionsItemSelected(item);
}
private void updateWeather() {
fetchMovies movieTask=new fetchMovies();
movieTask.execute("hi");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview=inflater.inflate(R.layout.fragment_main, container, false);
gridview=(GridView)rootview.findViewById(R.id.gridview);
//gridview.setAdapter(new ImageAdapter(getActivity()));
return rootview;
}
public class fetchMovies extends AsyncTask<String,Void,String[]> {
private final String LOG_TAG = fetchMovies.class.getSimpleName();
private String[] getMovieDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
JSONObject movieJson = new JSONObject(forecastJsonStr);
JSONArray movieArray = movieJson.getJSONArray("results");
String[] resultStrs = new String[movieArray.length()];
for(int i = 0; i < movieArray.length(); i++) {
JSONObject getMovie = movieArray.getJSONObject(i);
String moviePosterPathImage=getMovie.getString("poster_path");
String movieOverview=getMovie.getString("overview");
String split_release_date=getMovie.getString("release_date");
String[] Segments = split_release_date.split("-");
String release_date=Segments[1]+"-"+Segments[2]+"-"+Segments[0];
String title=getMovie.getString("title");
Double vote_Average=getMovie.getDouble("vote_average");
resultStrs[i] = moviePosterPathImage + " - " + movieOverview + " - " + release_date + " - " + title + " - " + vote_Average;
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
return resultStrs;
}
#Override
protected String[] doInBackground(String... params) {
HttpURLConnection urlConnection=null;
BufferedReader reader=null;
//will contain the raw json response as a string
String forecastJsonStr=null;
int Format_Cnt_Value=7;
String Format_Api="api_key";
try {
String Format_Mode="sort_by";
String Format_Mode_Val="popularity.desc";
String OPEN_MOVIES_API_KEY="-----My Api Key------";
String baseUrl="http://api.themoviedb.org/3/discover/movie?";
Uri builtUri=Uri.parse(baseUrl).buildUpon()
.appendQueryParameter(Format_Mode,Format_Mode_Val)
.appendQueryParameter(Format_Api,OPEN_MOVIES_API_KEY)
.build();
URL url=new URL(builtUri.toString());
Log.v(LOG_TAG,"test_Uri= " + builtUri);
urlConnection= (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream=urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "Forecast JsonString:=" + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
};
try {
return getMovieDataFromJson(forecastJsonStr,Format_Cnt_Value);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] Strings) {
if (Strings != null) {
//adp.clear();
str1 = new String[Strings.length];
for (int i = 0; i < Strings.length; i++) {
String[] getImage=Strings[i].split("-");
str1[i] = "http://image.tmdb.org/t/p/w185/" + getImage[0];
}
adp=new ImageAdapter(getActivity(),str1);
gridview.setAdapter(adp); //error
}
}
}
}
what should I do now....
I also have ImageAdapter class
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private String[] mThumbIds;
public ImageAdapter(Context c,String[] str2) {
mContext = c;
mThumbIds=str2;
}
#Override
public int getCount() {
if(mThumbIds!=null)
{
return mThumbIds.length;
}
else
{
return 0;
}
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(500,500));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(4, 4, 4, 4);
} else {
imageView = (ImageView) convertView;
}
// imageView.setImageResource(Integer.parseInt(mThumbIds[position]));
imageView.setImageResource(Integer.parseInt(mThumbIds[position]));
return imageView;
}
}
Please help.
I have loaded data from api and want to fill the gridview.
I am getting images in string[]...how to populate gridview..
I need your help to populate gridview using adapter
billions of thanks in advance.
Use Picasso library to load url images in your grid view.Check out this link on how to use picasso.
In your adapter getView() method add this line:
Picasso.with(mContext).load(mThumbIds[position]).into(imageView);

spinner setOnItemSelectedListener doesn't work

I have a spinner that I put its items dynamically from my database but the problem is I can't know which item is selected by the method setOnItemSelectedListener
Here is my java code :
public class Choix extends Activity {
JSONArray ja1 = null;
List<String> list = new ArrayList<String>();
ArrayAdapter<String> dataAdapter;
Spinner spinner;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choix_espace);
spinner = (Spinner) findViewById(R.id.spinner);
liste_ecoles k = new liste_ecoles();
k.execute();
dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), ""+arg2, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
private class liste_ecoles extends AsyncTask<String, Integer, Object> {
String ch1="";
#Override
protected Object doInBackground(String... params) {
JSONArray ja = null;
try {
URL twitter = new URL("...");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
ja = new JSONArray(line);
}
} catch (Exception e) {
}
return ja;
}
#Override
protected void onPostExecute(Object resultat) {
JSONArray ja = (JSONArray) resultat;
if (resultat != null) {
try {
for (int i = 0; i < ja.length(); i++) {
JSONObject jo1 = null;
jo1 = ja.getJSONObject(i);
ch1 = jo1.getString("nom_ecole");
list.add(ch1);
}
}
catch (Exception e) {
}
}
}
}
}
so can someone helps me please ?
I solved my problem ; I've just added " dataAdapter.notifyDataSetChanged(); " after adding items on my spinner

Resources