I'm using recycleview in google cloud speech api.
And I would like to put the strings in the recycleview into a single edit text.
How do I move a string from a recycleview into a single text?
enter code here
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.android.speech;
import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.icu.util.ValueIterator;
import android.os.Bundle;
import android.os.IBinder;
import android.sax.Element;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements
MessageDialogFragment.Listener {
static EditText edit1;
static EditText edit2;
static EditText edit3;
static String a1,a2;
static String[] b1,b2;
static int count=0;
Button btn;
private static final String FRAGMENT_MESSAGE_DIALOG = "message_dialog";
private static final String STATE_RESULTS = "results";
private static final int REQUEST_RECORD_AUDIO_PERMISSION = 1;
private SpeechService mSpeechService;
private VoiceRecorder mVoiceRecorder;
private final VoiceRecorder.Callback mVoiceCallback = new
VoiceRecorder.Callback() {
#Override
public void onVoiceStart() {
showStatus(true);
if (mSpeechService != null) {
mSpeechService.startRecognizing(mVoiceRecorder.getSampleRate());
}
}
#Override
public void onVoice(byte[] data, int size) {
if (mSpeechService != null) {
mSpeechService.recognize(data, size);
}
}
#Override
public void onVoiceEnd() {
showStatus(false);
if (mSpeechService != null) {
mSpeechService.finishRecognizing();
}
}
};
// Resource caches
private int mColorHearing;
private int mColorNotHearing;
// View references
private TextView mStatus;
private TextView mText;
private ResultAdapter mAdapter;
private RecyclerView mRecyclerView;
private final ServiceConnection mServiceConnection = new
ServiceConnection()
{
#Override
public void onServiceConnected(ComponentName componentName, IBinder
binder) {
mSpeechService = SpeechService.from(binder);
mSpeechService.addListener(mSpeechServiceListener);
mStatus.setVisibility(View.VISIBLE);
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mSpeechService = null;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit1=(EditText) findViewById(R.id.edit1);
edit2=(EditText) findViewById(R.id.edit2);
edit3=(EditText) findViewById(R.id.edit3);
btn=(Button)findViewById(R.id.button);
final Resources resources = getResources();
final Resources.Theme theme = getTheme();
mColorHearing = ResourcesCompat.getColor(resources,
R.color.status_hearing, theme);
mColorNotHearing = ResourcesCompat.getColor(resources,
R.color.status_not_hearing, theme);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
mStatus = (TextView) findViewById(R.id.status);
mText = (TextView) findViewById(R.id.text);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
final ArrayList<String> results = savedInstanceState == null ? null :
savedInstanceState.getStringArrayList(STATE_RESULTS);
mAdapter = new ResultAdapter(results);
mRecyclerView.setAdapter(mAdapter);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
#Override
protected void onStart() {
super.onStart();
// Prepare Cloud Speech API
bindService(new Intent(this, SpeechService.class), mServiceConnection,
BIND_AUTO_CREATE);
// Start listening to voices
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO)
== PackageManager.PERMISSION_GRANTED) {
startVoiceRecorder();
} else if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.RECORD_AUDIO)) {
showPermissionMessageDialog();
} else {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.RECORD_AUDIO},
REQUEST_RECORD_AUDIO_PERMISSION);
}
}
#Override
protected void onStop() {
// Stop listening to voice
stopVoiceRecorder();
// Stop Cloud Speech API
mSpeechService.removeListener(mSpeechServiceListener);
unbindService(mServiceConnection);
mSpeechService = null;
super.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mAdapter != null) {
outState.putStringArrayList(STATE_RESULTS, mAdapter.getResults());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[]
permissions,
#NonNull int[] grantResults) {
if (requestCode == REQUEST_RECORD_AUDIO_PERMISSION) {
if (permissions.length == 1 && grantResults.length == 1
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startVoiceRecorder();
} else {
showPermissionMessageDialog();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions,
grantResults);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_file:
mSpeechService.recognizeInputStream
(getResources().openRawResource(R.raw.audio));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void startVoiceRecorder() {
if (mVoiceRecorder != null) {
mVoiceRecorder.stop();
}
mVoiceRecorder = new VoiceRecorder(mVoiceCallback);
mVoiceRecorder.start();
}
private void stopVoiceRecorder() {
if (mVoiceRecorder != null) {
mVoiceRecorder.stop();
mVoiceRecorder = null;
}
}
private void showPermissionMessageDialog() {
MessageDialogFragment
.newInstance(getString(R.string.permission_message))
.show(getSupportFragmentManager(), FRAGMENT_MESSAGE_DIALOG);
}
private void showStatus(final boolean hearingVoice) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mStatus.setTextColor(hearingVoice ? mColorHearing :
mColorNotHearing);
}
});
}
#Override
public void onMessageDialogDismissed() {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.RECORD_AUDIO},
REQUEST_RECORD_AUDIO_PERMISSION);
}
private final SpeechService.Listener mSpeechServiceListener =
new SpeechService.Listener() {
#Override
public void onSpeechRecognized(final String text, final boolean
isFinal) {
if (isFinal) {
mVoiceRecorder.dismiss();
}
if (mText != null && !TextUtils.isEmpty(text)) {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (isFinal) {
mText.setText(null);
mAdapter.addResult(text);
mRecyclerView.smoothScrollToPosition(0);
} else {
mText.setText(text);
}
}
});
}
}
};
private static class ViewHolder extends RecyclerView.ViewHolder {
TextView text;
ViewHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.item_result, parent, false));
text = (TextView) itemView.findViewById(R.id.text);
}
}
private static class ResultAdapter extends
RecyclerView.Adapter<ViewHolder> {
private final ArrayList<String> mResults = new ArrayList<>();
ResultAdapter(ArrayList<String> results) {
if (results != null) {
mResults.addAll(results);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()),
parent);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.text.setText(mResults.get(position));
}
#Override
public int getItemCount() {
return mResults.size();
}
void addResult(String result) {
mResults.add(0, result);
notifyItemInserted(0);
}
public ArrayList<String> getResults() {
return mResults;
}
}
}
here is java code.
if you know the answer, let me know..
I tried but it doesn't work. The editview doesn't show all of texts in reclycleview...
Create a TextView element outside of that recycle view. Then initialize it onCreate() method.
You need to extract text from that recycle view. I have no idea about that u hold data. Anyhow get a text from that.
Then updateText using textView.setText(...) when that recycleText updated
Define TextView like this in mainActivity and initalize it in onCreate
static TextView recyText;
in
oncreate(){
....
recyText=(TextView) findViewById(R.id.recyText);
}
the update it in below code segment
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.text.setText(mResults.get(position));
recyText.setText(recyText.getText()+ " " +mResults.get(position))
}
Related
I am searching Exoplayer using with ViewPager in java but can not find the full tutorial.
I have issue for stopping and pausing exoplayer while swiping another video.
Is there any tutorial please suggest me.
Adapter.java
package com.daasuu.gpuvideoandroid.Adapter;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.daasuu.gpuvideoandroid.Activity.OtherUser.OtherUserProfileActivity;
import com.daasuu.gpuvideoandroid.Model.MainVideoDataModel;
import com.daasuu.gpuvideoandroid.R;
import com.daasuu.gpuvideoandroid.Utils.VideoCache;
import com.daasuu.gpuvideoandroid.databinding.ItemMainVideoBinding;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.ui.StyledPlayerView;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource;
import com.google.android.exoplayer2.upstream.cache.CacheDataSource;
import java.util.List;
public class MainVideoAdapter2 extends RecyclerView.Adapter<MainVideoAdapter2.MyViewHolder> {
private Context context;
private List<MainVideoDataModel> data;
private boolean likeFlag = false;
private boolean followFlag = false;
private boolean isPlaying = false;
ExoPlayer exoplayer;
StyledPlayerView styledPlayerView;
public MainVideoAdapter2(Context context, List<MainVideoDataModel> data) {
this.context = context;
this.data = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ItemMainVideoBinding binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.item_main_video, parent, false);
return new MyViewHolder(binding);
}
#Override
public void onBindViewHolder(MainVideoAdapter2.MyViewHolder holder, int position) {
MainVideoDataModel model = data.get(position);
holder.setExoplayerStyled(model.getVideo_url());
}
#Override
public int getItemCount() {
return data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ItemMainVideoBinding binding;
public MyViewHolder(ItemMainVideoBinding binding) {
super(binding.getRoot());
this.binding = binding;
binding.imageUserMainVideo.setOnClickListener(this);
binding.videoView.setOnClickListener(this);
}
// styled exoplayer with cache
void setExoplayerStyled(String video_url){
binding.progressCircular.setVisibility(View.VISIBLE);
exoplayer = new ExoPlayer.Builder(context).build();
styledPlayerView = binding.videoStyledPlayerView;
styledPlayerView.hideController();
styledPlayerView.setUseController(false);
ProgressiveMediaSource mediaSource = new ProgressiveMediaSource.Factory(
new CacheDataSource.Factory()
.setCache(VideoCache.getInstance2(context))
.setUpstreamDataSourceFactory(new DefaultHttpDataSource.Factory()
.setUserAgent("rgcache"))
.setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR)
).createMediaSource(MediaItem.fromUri(video_url));
exoplayer.seekTo(0);
exoplayer.prepare();
exoplayer.pause();
styledPlayerView.setPlayer(exoplayer);
exoplayer.setPlayWhenReady(false);
binding.videoStyledPlayerView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
#Override
public void onViewAttachedToWindow(View view) {
styledPlayerView.setKeepScreenOn(true);
exoplayer.addMediaSource(mediaSource);
exoplayer.prepare();
exoplayer.setPlayWhenReady(true);
exoplayer.setRepeatMode(exoplayer.REPEAT_MODE_ONE);
if(binding.videoStyledPlayerView.getPlayer() != null) {
binding.videoStyledPlayerView.getPlayer().play();
}
}
#Override
public void onViewDetachedFromWindow(View view) {
binding.videoStyledPlayerView.getPlayer().stop();
binding.videoStyledPlayerView.getPlayer().clearMediaItems();
exoplayer.seekTo(0);
exoplayer.setPlayWhenReady(false);
exoplayer.stop();
if(binding.videoStyledPlayerView.getPlayer() != null) {
binding.videoStyledPlayerView.getPlayer().pause();
}
}
});
//buffering
exoplayer.addListener(new Player.Listener() {
#Override
public void onIsLoadingChanged(boolean isLoading) {
Player.Listener.super.onIsLoadingChanged(isLoading);
// Log.e("onIsLoadingChanged", String.valueOf(isLoading));
}
#Override
public void onPlaybackStateChanged(int playbackState) {
Player.Listener.super.onPlaybackStateChanged(playbackState);
Log.e("onPlaybackStateChanged", String.valueOf(playbackState));
binding.imgVideoStop.setVisibility(View.GONE);
if (playbackState == 3){
binding.progressCircular.setVisibility(View.GONE);
}
}
#Override
public void onPlayWhenReadyChanged(boolean playWhenReady, int reason) {
Player.Listener.super.onPlayWhenReadyChanged(playWhenReady, reason);
}
});
// touch listener play & pause
binding.videoStyledPlayerView.getVideoSurfaceView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isPlaying == false){
binding.imgVideoStop.setVisibility(View.VISIBLE);
isPlaying = true;
exoplayer.setPlayWhenReady(false);
}else{
binding.imgVideoStop.setVisibility(View.GONE);
isPlaying = false;
styledPlayerView.setKeepScreenOn(true);
styledPlayerView.setPlayer(exoplayer);
exoplayer.addMediaSource(mediaSource);
exoplayer.prepare();
exoplayer.setPlayWhenReady(true);
exoplayer.setRepeatMode(exoplayer.REPEAT_MODE_ONE);
}
}
});
}
//on click event
#Override
public void onClick(View v) {
if (v == binding.imageUserMainVideo) {
context.startActivity(new Intent(context, OtherUserProfileActivity.class));
}
if (v == binding.videoView) {
Log.e("isPlaying = " , String.valueOf(isPlaying));
if (isPlaying) {
binding.videoView.pause();
// binding.imgVideoStop.setVisibility(View.VISIBLE);
isPlaying = false;
} else {
binding.videoView.start();
// binding.imgVideoStop.setVisibility(View.GONE);
isPlaying = true;
}
}
}
}
}
item.xml
<com.google.android.exoplayer2.ui.StyledPlayerView
android:id="#+id/videoStyledPlayerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible"
app:animation_enabled="true"/>
Issues:
After a specific position, it plays previous videos when swipe to next video.
Plays multiple videos on swipe
On swipe back(previous videos) don't stops previous video.
How to stop when to redirect another activity.
Please suggest the solution.
You can use addOnPageChangeListener for getting the user interaction for the view pager. add this code snippet in the onCreate method.In my project ,I handle it like this ::
binding!!.mediaViewPager.addOnPageChangeListener(object : OnPageChangeListener {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
if (exoPlayer.isPlaying) {
exoPlayer.pause()
}
}
override fun onPageSelected(position: Int) {
if (exoPlayer.isPlaying) {
exoPlayer.pause()
}
}
override fun onPageScrollStateChanged(state: Int) {
exoPlayer.pause()
}
})
Play Exo Player With PageViwer
Link:
https://github.com/google/ExoPlayer/issues/7947
Example:
https://github.com/kakajika/PlayerPagerExample
I'm trying to connect to an ble device, so I've implemented a bluetooth ble scan activity for this, but this does not work on my tablet (Archos 70 3G with android 7.0) but works in my phone (Xiaomi Note 8 Pro). I allowed location and bluetooth both devices. What is the problem? The code of the activity:
package myapp
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import myapp.R;
public class BluetoothListActivity extends Activity {
private BluetoothAdapter mBluetoothAdapter;
// private BluetoothAdapter mBtAdapter;
private TextView mEmptyList;
public static final String TAG = "DeviceListActivity";
List<BluetoothDevice> deviceList;
private DeviceAdapter deviceAdapter;
private ServiceConnection onService = null;
Map<String, Integer> devRssiValues;
private static final long SCAN_PERIOD = 10000; //scanning for 10 seconds
private Handler mHandler;
private boolean mScanning;
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] Results) {
if (requestCode == 1) {
Toast.makeText(this, "Git gud", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
Toast.makeText(this, "git gud", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
setContentView(R.layout.activity_device_list);
android.view.WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.gravity = Gravity.TOP;
layoutParams.y = 200;
mHandler = new Handler();
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "Ble not supported", Toast.LENGTH_SHORT).show();
finish();
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// Checks if Bluetooth is supported on the device.
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Not supported", Toast.LENGTH_SHORT).show();
finish();
return;
}
populateList();
mEmptyList = (TextView) findViewById(R.id.empty);
Button cancelButton = (Button) findViewById(R.id.btn_cancel);
cancelButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mScanning == false) scanLeDevice(true);
else finish();
}
});
}
private void populateList() {
/* Initialize device list container */
Log.d(TAG, "populateList");
deviceList = new ArrayList<BluetoothDevice>();
deviceAdapter = new DeviceAdapter(this, deviceList);
devRssiValues = new HashMap<String, Integer>();
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(deviceAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
scanLeDevice(true);
}
private void scanLeDevice(final boolean enable) {
final Button cancelButton = (Button) findViewById(R.id.btn_cancel);
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
cancelButton.setText(R.string.scan);
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
cancelButton.setText(R.string.cancel);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
cancelButton.setText(R.string.scan);
}
}
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run() {
addDevice(device, rssi);
}
});
}
};
private void addDevice(BluetoothDevice device, int rssi) {
boolean deviceFound = false;
for (BluetoothDevice listDev : deviceList) {
if (listDev.getAddress().equals(device.getAddress())) {
deviceFound = true;
break;
}
}
devRssiValues.put(device.getAddress(), rssi);
if (!deviceFound) {
deviceList.add(device);
mEmptyList.setVisibility(View.GONE);
deviceAdapter.notifyDataSetChanged();
}
}
#Override
public void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
}
#Override
public void onStop() {
super.onStop();
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
#Override
public void onDestroy() {
super.onDestroy();
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
BluetoothDevice device = deviceList.get(position);
mBluetoothAdapter.stopLeScan(mLeScanCallback);
Bundle b = new Bundle();
b.putString(BluetoothDevice.EXTRA_DEVICE, deviceList.get(position).getAddress());
Intent result = new Intent();
result.putExtras(b);
setResult(Activity.RESULT_OK, result);
Toast.makeText(getApplicationContext(), "Connected to " + deviceList.get(position).getName(), Toast.LENGTH_SHORT).show();
finish();
}
};
public void onPause() {
super.onPause();
scanLeDevice(false);
}
class DeviceAdapter extends BaseAdapter {
Context context;
List<BluetoothDevice> devices;
LayoutInflater inflater;
public DeviceAdapter(Context context, List<BluetoothDevice> devices) {
this.context = context;
inflater = LayoutInflater.from(context);
this.devices = devices;
}
#Override
public int getCount() {
return devices.size();
}
#Override
public Object getItem(int position) {
return devices.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewGroup vg;
if (convertView != null) {
vg = (ViewGroup) convertView;
} else {
vg = (ViewGroup) inflater.inflate(R.layout.device_list_element, null);
}
BluetoothDevice device = devices.get(position);
final TextView tvadd = ((TextView) vg.findViewById(R.id.address));
final TextView tvname = ((TextView) vg.findViewById(R.id.name));
final TextView tvpaired = (TextView) vg.findViewById(R.id.paired);
final TextView tvrssi = (TextView) vg.findViewById(R.id.rssi);
tvrssi.setVisibility(View.VISIBLE);
byte rssival = (byte) devRssiValues.get(device.getAddress()).intValue();
if (rssival != 0) {
tvrssi.setText("Rssi = " + String.valueOf(rssival));
}
tvname.setText(device.getName());
tvadd.setText(device.getAddress());
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
Log.i(TAG, "device::" + device.getName());
tvname.setTextColor(Color.BLACK);
tvadd.setTextColor(Color.BLACK);
tvpaired.setTextColor(Color.GRAY);
tvpaired.setVisibility(View.VISIBLE);
tvpaired.setText(R.string.paired);
tvrssi.setVisibility(View.VISIBLE);
tvrssi.setTextColor(Color.BLACK);
} else {
tvname.setTextColor(Color.BLACK);
tvadd.setTextColor(Color.BLACK);
tvpaired.setVisibility(View.GONE);
tvrssi.setVisibility(View.VISIBLE);
tvrssi.setTextColor(Color.BLACK);
}
return vg;
}
}
private void showMessage(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
I want to display a bunch of custom markers(IconGenerator from com.google.maps.android:android-maps-utils:0.5) in a google map. But the data to build the markers, the LatLong location are in a firebase database, each child has its own location values, how can I read the location of each child and pass it to the class that will display the markers?
package com.realty.drake.kunuk;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Keep;
import com.google.android.gms.maps.model.LatLng;
/**
* Created by drake on 5/1/18.
* This class is the model class
*/
#Keep
public class Property implements Parcelable {
private int price;
private String address;
private int numberOfBed;
private int numberOfBath;
private int numberOfCar;
private String propertyImage;
private float lotDim;
private String propertyDesc;
private float propertyDim;
private String lotTerrainType;
private String lotTerrainDimExt;
private String lotTerrainSteepness;
private LatLng location;
public Property() { } //Needed for Firebase's auto data mapping
public Property(int price, String address, int numberOfBed, int numberOfBath,
int numberOfCar, String propertyImage, float lotDim,
String propertyDesc, float propertyDim, String lotTerrainType,
String lotTerrainDimExt, String lotTerrainSteepness,
LatLng location) {
this.price = price;
this.address = address;
this.numberOfBed = numberOfBed;
this.numberOfBath = numberOfBath;
this.numberOfCar = numberOfCar;
this.propertyImage = propertyImage;
this.lotDim = lotDim;
this.propertyDesc = propertyDesc;
this.propertyDim = propertyDim;
this.lotTerrainType = lotTerrainType;
this.lotTerrainDimExt = lotTerrainDimExt;
this.lotTerrainSteepness = lotTerrainSteepness;
this.location = location;
}
protected Property(Parcel in) {
price = in.readInt();
address = in.readString();
numberOfBed=in.readInt();
numberOfBath = in.readInt();
numberOfCar = in.readInt();
propertyImage = in.readString();
lotDim = in.readFloat();
propertyDesc = in.readString();
propertyDim = in.readFloat();
lotTerrainType = in.readString();
lotTerrainDimExt = in.readString();
lotTerrainSteepness = in.readString();
location = in.readParcelable(getClass().getClassLoader());
}
public static final Creator<Property> CREATOR = new Creator<Property>() {
#Override
public Property createFromParcel(Parcel in) {
return new Property(in);
}
#Override
public Property[] newArray(int i) {
return new Property[i];
}
};
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getNumberOfBed() {
return numberOfBed;
}
public void setNumberOfBed(int numberOfBed) {
this.numberOfBed = numberOfBed;
}
public int getNumberOfBath() {
return numberOfBath;
}
public void setNumberOfBath(int numberOfBath) {
this.numberOfBath = numberOfBath;
}
public int getNumberOfCar() {
return numberOfCar;
}
public void setNumberOfCar(int numberOfCar) {
this.numberOfCar = numberOfCar;
}
public String getPropertyImage() {
return propertyImage;
}
public void setPropertyImage(String propertyImage) {
this.propertyImage = propertyImage;
}
public float getLotDim() {
return lotDim;
}
public void setLotDim(float lotDim) {
this.lotDim = lotDim;
}
public String getPropertyDesc() {
return propertyDesc;
}
public void setPropertyDesc(String propertyDesc) {
this.propertyDesc = propertyDesc;
}
public float getPropertyDim() {
return propertyDim;
}
public void setPropertyDim(float propertyDim) {
this.propertyDim = propertyDim;
}
public String getLotTerrainType() {
return lotTerrainType;
}
public void setLotTerrainType(String lotTerrainType) {
this.lotTerrainType = lotTerrainType;
}
public String getLotTerrainDimExt() {
return lotTerrainDimExt;
}
public void setLotTerrainDimExt(String lotTerrainDimExt) {
this.lotTerrainDimExt = lotTerrainDimExt;
}
public String getLotTerrainSteepness() {
return lotTerrainSteepness;
}
public void setLotTerrainSteepness(String lotTerrainSteepness) {
this.lotTerrainSteepness = lotTerrainSteepness;
}
public LatLng getLocation() {
return location;
}
public void setLocation(LatLng location) {
this.location = location;
}
#Override
public int describeContents(){
return 0;
}
#Override
public void writeToParcel( Parcel dest, int flags){
dest.writeInt(price);
dest.writeString(address);
dest.writeInt(numberOfBed);
dest.writeInt(numberOfBath);
dest.writeInt(numberOfCar);
dest.writeString(propertyImage);
dest.writeFloat(lotDim);
dest.writeString(propertyDesc);
dest.writeFloat(propertyDim);
dest.writeString(lotTerrainType);
dest.writeString(lotTerrainDimExt);
dest.writeString(lotTerrainSteepness);
dest.writeParcelable(location,flags);
}
}
The Fragment that use the model class, it takes data from firebase database, and also has anintent to a detailed view
package com.realty.drake.kunuk;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.CircularProgressDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.text.NumberFormat;
import java.util.Locale;
/**
* Created by drake on 4/11/18
*/
public class Tab1Buy extends Fragment {
private DatabaseReference propertyRef;
private RecyclerView mPropertyRecyclerView;
FirebaseRecyclerAdapter<Property, PropertyViewHolder> mPropertyAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.property_tab, container, false);
mPropertyRecyclerView = rootView.findViewById(R.id.property_recyclerView);
return rootView;
}
//TODO Check internet and display error msg if internet down
#Override
public void onViewCreated(final View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mPropertyRecyclerView.hasFixedSize();
mPropertyRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
final ProgressBar progressBar = view.findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
propertyRef = FirebaseDatabase.getInstance()
.getReference()
.child("Buy");
propertyRef.keepSynced(true);
// keyQuery - the Firebase location containing the list of keys to be found in dataRef
//Query personQuery = propertyRef.orderByKey();
FirebaseRecyclerOptions<Property> options =
new FirebaseRecyclerOptions.Builder<Property>()
.setQuery(propertyRef, Property.class)
.build();
mPropertyAdapter = new FirebaseRecyclerAdapter<Property, PropertyViewHolder>(options) {
#Override
// Bind the Property object to the ViewHolder PropertyHolder
public void onBindViewHolder(#NonNull PropertyViewHolder holder,
final int position, #NonNull final Property model) {
holder.setPrice(model.getPrice());
holder.setAddress(model.getAddress());
holder.setNumberOfBed(model.getNumberOfBed());
holder.setNumberOfBath(model.getNumberOfBath());
holder.setNumberOfCar(model.getNumberOfCar());
holder.setPropertyImage(model.getPropertyImage());
//This Intent send Parcelable from Property to PropertyDetail
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().startActivity(new Intent(getActivity(), PropertyDetail.class)
.putExtra("Property", model));
}
});
}
#Override
public PropertyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.property_card for each item
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.property_card, parent, false);
return new PropertyViewHolder(view);
}
#Override
public void onDataChanged() {
// Called each time there is a new data snapshot. You may want to use this method
// to hide a loading spinner or check for the "no documents" state and update your UI.
// ...
progressBar.setVisibility(View.GONE);
}
//TODO Implement onError
#Override
public void onError(#NonNull DatabaseError e) {
// Called when there is an error getting data. You may want to update
// your UI to display an error message to the user.
// ...
progressBar.setVisibility(View.GONE);
Toast.makeText(getActivity(), "DatabaseError", Toast.LENGTH_SHORT).show();
}
};
mPropertyRecyclerView.setAdapter(mPropertyAdapter);
}
#Override
public void onStart() {
super.onStart();
mPropertyAdapter.startListening();
}
#Override
public void onStop() {
super.onStop();
mPropertyAdapter.stopListening();
}
public class PropertyViewHolder extends RecyclerView.ViewHolder {
View mView;
public PropertyViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setPrice(int price) {
String currencyPrice = NumberFormat //Format the price variable in currency form
.getCurrencyInstance(Locale.US)
.format(price);
TextView Price = mView.findViewById(R.id.post_price);
Price.setText(currencyPrice);
}
public void setAddress(String address){
TextView Address = mView.findViewById(R.id.post_address);
Address.setText(String.valueOf(address));
}
public void setNumberOfBed(int numberOfBed){
TextView NumberOfBed = mView.findViewById(R.id.post_bedroom);
NumberOfBed.setText(String.valueOf(numberOfBed));
}
public void setNumberOfBath(int numberOfBath){
TextView NumberOfBath = mView.findViewById(R.id.post_bathroom);
NumberOfBath.setText(String.valueOf(numberOfBath));
}
public void setNumberOfCar(int numberOfCar) {
TextView NumberOfCar = mView.findViewById(R.id.post_garage);
NumberOfCar.setText(String.valueOf(numberOfCar));
}
public void setPropertyImage(String propertyImage){
ImageView imageView = mView.findViewById(R.id.post_propertyImage);
//take one long string containing multiple url in and parse it
String propertyImageArray[] = propertyImage.split(",");
//Loading circle for placeholder, ColorAccent has been used
CircularProgressDrawable progressDrawable =
new CircularProgressDrawable(getContext());
progressDrawable.setStrokeWidth(5f);
progressDrawable.setCenterRadius(30f);
progressDrawable.setColorSchemeColors(Color.argb(1,255,145,0));
progressDrawable.start();
// Download directly from StorageReference using Glide
// (See MyAppGlideModule for Loader registration)
GlideApp.with(getContext())
.load(propertyImageArray[0])
.placeholder(progressDrawable)
.fitCenter()
.into(imageView);
}
}
}
The detailed activity which is called by an intent from Tab1Buy
package com.realty.drake.kunuk;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.view.MenuItem;
import android.widget.Toast;
import java.text.NumberFormat;
import java.util.Locale;
public class PropertyDetail extends AppCompatActivity implements Toolbar.OnMenuItemClickListener {
#Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.property_detail);
Toolbar myToolbar = (Toolbar) findViewById(R.id.kunuk_toolbar);
myToolbar.inflateMenu(R.menu.menu_detail);
setSupportActionBar(myToolbar);
myToolbar.setOnMenuItemClickListener(this);
//collect our intent
Intent intent = getIntent();
Property property = intent.getParcelableExtra("Property");
boolean isRent = getIntent().getBooleanExtra("isRent", false);
//collect all property values from Parcelable
int price = property.getPrice();
String address = property.getAddress();
int numberOfBed = property.getNumberOfBed();
int numberOfBath = property.getNumberOfBath();
int numberOfCar = property.getNumberOfCar();
String propertyImage = property.getPropertyImage();
float propertyDim = property.getPropertyDim();
String propertyDesc = property.getPropertyDesc();
// Get a support ActionBar corresponding to this toolbar
ActionBar ab = getSupportActionBar();
// Enable the Up button
ab.setDisplayHomeAsUpEnabled(true);
BottomNavigationView bottomNavigationView = (BottomNavigationView)
findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_call:
Uri callNumberUri = Uri.parse("tel:+50937438713");
Intent callIntent = new Intent(Intent.ACTION_DIAL, callNumberUri);
startActivity(callIntent);
break;
case R.id.action_sms:
Uri smsNumberUri = Uri.parse("sms:+50937438713");
Intent smsIntent = new Intent(Intent.ACTION_SENDTO, smsNumberUri);
startActivity(smsIntent);
break;
case R.id.action_email:
//TODO get a property id to use in subject email field
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("message/rfc822");
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Kunuk Request");
emailIntent.putExtra(Intent.EXTRA_EMAIL,
new String[] {"drakecolinj#gmail.com"});
startActivity(emailIntent);
}
return false;
}
});
//Bind the data from the Parcelable to the Views
TextView addressDetail = findViewById(R.id.post_address);
addressDetail.setText(String.valueOf(address));
String currencyPrice = NumberFormat //Format the price variable in currency form
.getCurrencyInstance(Locale.US)
.format(price);
TextView priceDetail = findViewById(R.id.post_price);
priceDetail.setText(currencyPrice);
ImageView imageView = findViewById(R.id.post_propertyImage);
//take one long string containing multiple url and parse it
String propertyImageArray[] = propertyImage.split(",");
//TODO add loading icon for placeholder
// Download directly from StorageReference using Glide
// (See MyAppGlideModule for Loader registration)
GlideApp.with(getApplication())
.load(propertyImageArray[0])
.fitCenter()
.into(imageView);
TextView bathroomDetail = findViewById(R.id.post_bathroom);
bathroomDetail.setText(String.valueOf(numberOfBath));
TextView bedroomDetail = findViewById(R.id.post_bedroom);
bedroomDetail.setText(String.valueOf(numberOfBed));
TextView garageDetail = findViewById(R.id.post_garage);
garageDetail.setText(String.valueOf(numberOfCar));
TextView propertyDimDetail = findViewById(R.id.property_dim);
propertyDimDetail.setText(String.valueOf(propertyDim));
TextView propertyDescDetail = findViewById(R.id.property_desc);
propertyDescDetail.setText(String.valueOf(propertyDesc));
if (isRent) {
final TextView rentUnit = findViewById(R.id.rent_unit_detail);
rentUnit.setVisibility(View.VISIBLE);
}
}
#Override
public boolean onMenuItemClick(MenuItem item){
switch (item.getItemId()) {
case R.id.action_share:
Toast.makeText(this, "Shared", Toast.LENGTH_SHORT).show();
return true;
}
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.menu_detail, menu);
return true;
}
}
In Child "Buy", each of its child has its own location key and the same for Rent and Lot.
Please help, conceptual explanation and code please
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Buy");
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// Let us retrieve value of location
Log.i("Price", dataSnapshot.child("location").getValue().toString());
// In this way you can retrieve all the fileds.
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Similarly for Rent & Lot you can pass as -
DatabaseReference dbRent = FirebaseDatabase.getInstance().getReference("Rent");
DatabaseReference dbLot = FirebaseDatabase.getInstance().getReference("Lot");
I hope this will helps!
I am trying to create a BLE android app, and I've been having a lot of trouble with null pointers that I can't figure out even when using androids sample apps of android-BluetoothAdvertisements and android-BluetoothLEGatt.
This is my code:
import android.app.Activity;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.NavigationView;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v4.widget.DrawerLayout;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import java.util.List;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter;
private LeDeviceListAdapter mLeDeviceListAdapter;
private BluetoothLeScanner mBluetoothLeScanner;
private boolean mScanning;
private ScanCallback mScanCallback;
private Handler mHandler;
private BluetoothDevice mBluetoothGatt;
private String mDeviceName;
private String mDeviceAddress;
private ScanResultAdapter mAdapter;
private BluetoothGattDescriptor mDescriptor;
private BluetoothGattCharacteristic mBluetoothCharacteristic;
private BluetoothDevice device;
private int mConnectionState = STATE_DISCONNECTED;
private BluetoothLeScanner btScanner;
private BluetoothDevice mbluetoothDevice;
Button button;
DrawerLayout dLayout;
private Button ble_scan;
private final static int REQUEST_ENABLE_BT = 1;
private static final int STATE_DISCONNECTED = 0;
private static final int STATE_CONNECTING = 1;
private static final int STATE_CONNECTED = 2;
private final String LIST_NAME = "NAME";
private final String LIST_UUID = "UUID";
public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
public final static String ACTION_GATT_CONNECTED =
"com.example.bluetooth.le.ACTION_GATT_CONNECTED";
public final static String ACTION_GATT_DISCONNECTED =
"com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
public final static String ACTION_GATT_SERVICES_DISCOVERED =
"com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
public final static String ACTION_DATA_AVAILABLE =
"com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
public final static String EXTRA_DATA =
"com.example.bluetooth.le.EXTRA_DATA";
// Stops scanning after 5 seconds.
private static final long SCAN_PERIOD = 5000;
//On entering app protocols
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = getIntent();
mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
//Set View and new Handler
setContentView(R.layout.activity_main);
mHandler = new Handler();
mAdapter = new ScanResultAdapter(this.getApplicationContext(),
LayoutInflater.from(this));
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
//sets up variables to initialize Bluetooth Manager and our Adapter settings
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
//Initializes Navigation Drawer
setNavigationDrawer();
//Checks if Bluetooth adapter is enabled and requests to enable it
if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
//Initializes Scan Button
//addListenerOnButton();
//startScanning();
TextView txtView = (TextView) findViewById(R.id.ScanOut);
txtView.setText(BluetoothDevice.EXTRA_NAME);
//Initializing floating action button
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLeDeviceListAdapter.addDevice(device);
mLeDeviceListAdapter.notifyDataSetChanged();
}
});
}
};
/**
* Custom ScanCallback object - adds to adapter on success, displays error on failure.
*/
private class SampleScanCallback extends ScanCallback {
#Override
public void onBatchScanResults(List<ScanResult> results) {
super.onBatchScanResults(results);
for (ScanResult result : results) {
mAdapter.add(result);
}
mAdapter.notifyDataSetChanged();
}
#Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
mAdapter.add(result);
mAdapter.notifyDataSetChanged();
}
#Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
Toast.makeText(MainActivity.this, "Scan failed with error: " + errorCode, Toast.LENGTH_LONG)
.show();
}
}
/**
* Start scanning for BLE Advertisements (& set it up to stop after a set period of time).
*/
public void startScanning() {
if (mScanCallback == null) {
// Will stop the scanning after a set time.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
stopScanning();
}
}, SCAN_PERIOD);
// Kick off a new scan.
mScanCallback = new SampleScanCallback();
mBluetoothLeScanner.startScan(mScanCallback);
Toast.makeText(MainActivity.this, "Started Scan", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Already Scanning", Toast.LENGTH_SHORT);
}
}
/**
* Stop scanning for BLE Advertisements.
*/
public void stopScanning() {
// Stop the scan, wipe the callback.
mBluetoothLeScanner.stopScan(mScanCallback);
mScanCallback = null;
// Even if no new results, update 'last seen' times.
mAdapter.notifyDataSetChanged();
}
/* private void scanLeDevice(final boolean enable) {
//mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
mBluetoothLeScanner.stopScan(mScanCallback);
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothLeScanner.startScan(mScanCallback);
} else {
mScanning = false;
mBluetoothLeScanner.stopScan(mScanCallback);
}
}*/
private void GattConnect() {
BluetoothGatt mBluetoothGatt = mbluetoothDevice.connectGatt(this, false, mGattCallback);
mBluetoothGatt.discoverServices();
List<BluetoothGattService> services = mBluetoothGatt.getServices();
for (BluetoothGattService service : services) {
List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
}
}
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
#Override
public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
// this will get called anytime you perform a read or write characteristic operation
}
#Override
public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
// this will get called when a device connects or disconnects
}
#Override
public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
// this will get called after the client initiates a BluetoothGatt.discoverServices() call
}
};
// Adapter for holding devices found through scanning.
private class LeDeviceListAdapter extends BaseAdapter {
private ArrayList<BluetoothDevice> mLeDevices;
private LayoutInflater mInflator;
public LeDeviceListAdapter() {
super();
mLeDevices = new ArrayList<BluetoothDevice>();
mInflator = MainActivity.this.getLayoutInflater();
}
public void addDevice(BluetoothDevice device) {
if(!mLeDevices.contains(device)) {
mLeDevices.add(device);
}
}
public BluetoothDevice getDevice(int position) {
return mLeDevices.get(position);
}
public void clear() {
mLeDevices.clear();
}
#Override
public int getCount() {
return mLeDevices.size();
}
#Override
public Object getItem(int i) {
return mLeDevices.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
// General ListView optimization code.
if (view == null) {
view = mInflator.inflate(R.layout.listitem_device, null);
viewHolder = new ViewHolder();
viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
BluetoothDevice device = mLeDevices.get(i);
final String deviceName = device.getName();
if (deviceName != null && deviceName.length() > 0)
viewHolder.deviceName.setText(deviceName);
else
viewHolder.deviceName.setText("Unknown Device");
viewHolder.deviceAddress.setText(device.getAddress());
return view;
}
}
/*
Setting up Navigational Drawer that creates other fragments
*/
private void setNavigationDrawer() {
Intent intent = null;
dLayout = (DrawerLayout) findViewById(R.id.drawer_layout); // initiate a DrawerLayout
NavigationView navView = (NavigationView) findViewById(R.id.navigation); // initiate a Navigation View
// implement setNavigationItemSelectedListener event on NavigationView
navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
Fragment frag = null; // create a Fragment Object
int itemId = menuItem.getItemId(); // get selected menu item's id
// check selected menu item's id and replace a Fragment Accordingly
if (itemId == R.id.nav_home){
frag = new HomeFragment();
} else if (itemId == R.id.nav_alarms) {
frag = new AlarmFragment();
} else if (itemId == R.id.nav_cues) {
frag = new CueFragment();
} else if (itemId == R.id.nav_data) {
frag = new DataFragment();
} else if (itemId == R.id.nav_settings){
frag = new SettingFragment();
} else if (itemId == R.id.nav_help){
frag = new HelpFragment();
}
// display a toast message with menu item's title
Toast.makeText(getApplicationContext(), menuItem.getTitle(), Toast.LENGTH_SHORT).show();
if (frag != null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame, frag); // replace a Fragment with Frame Layout
transaction.commit(); // commit the changes
dLayout.closeDrawers(); // close the all open Drawer Views
return true;
}
return false;
}
});
}
public void addListenerOnButton() {
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//scanLeDevice(true);
}
});
}
static class ViewHolder {
TextView deviceName;
TextView deviceAddress;
}
//What happens on resuming the app
#Override
protected void onResume() {
super.onResume();
// Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled,
// fire an intent to display a dialog asking the user to grant permission to enable it.
if (!mBluetoothAdapter.isEnabled()) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
// Initializes list view adapter.
mLeDeviceListAdapter = new LeDeviceListAdapter();
//setListAdapter(mLeDeviceListAdapter);
//scanLeDevice(true);
}
#Override
protected void onPause() {
super.onPause();
//scanLeDevice(false);
mLeDeviceListAdapter.clear();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// User chose not to enable Bluetooth.
if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
finish();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
I am using the BluetoothLeService class from the Gatt example. Right now I am trying to get my scanning to work so I can find my BLE device to attempt to set up a Gatt connection with it.
I have tried implementing many parts of the examples, and since startLeScan() and stopLeScan() are depreciated, I am attempting to merge the BLE scanning from the bluetooth advertisements example with the BLE Gatt example. The apps examples work fine, but I get a bunch of null pointers when I try to do it myself.
On my onResume function I will get this error: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
Which is weird because I invoke the same method during onCreate without problems.
The thing that hasn't been working at all no matter how I try to invoke it is my startScanning method. I always get this error: 'java.lang.NullPointerException: Attempt to invoke virtual method void android.bluetooth.le.BluetoothLeScanner.startScan(android.bluetooth.le.ScanCallback)' on a null object reference because it seems like the startScan method never actually works. Maybe I am just doing something horribly wrong.
It's called in a fragment in the example, but I don't think that should affect it and I should be able to use it in my main activity for a base level connection for debugging if I'm not mistaken.
Does anyone have any advice on what I'm doing glaringly wrong?
I am using Sugar ORM to implement Data Persistence in my app. I am displaying my database contents in a RecyclerView. The problem is SugarORM doesn't have loaders so there is no way to refresh the RecyclerView with fresh data after adding/deleting an entry to the database. I have worked around the issue for phones by reinitializing my Adapter in OnResume() and displaying it in the Recycler View. But for Tablets, the logic isn't working because the Fragment never goes to OnPause.
I need to update my the RecyclerView in my FavouritesFragment when I remove an entry in my DetailsFragment
Here's the Github link https://github.com/Hackertronix/Project-Motion/tree/Stage_2
Here's the code for both fragments
FavoritesFragment.java
package com.execube.genesis.views.fragments;
import android.app.ActivityOptions;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.execube.genesis.R;
import com.execube.genesis.model.Movie;
import com.execube.genesis.utils.API;
import com.orm.SugarRecord;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Prateek Phoenix on 6/7/2016.
*/
public class FavouritesFragment extends Fragment {
public static final String TAG= "FAVOURITES";
private static final String FAVOURITE_MOVIES_ARRAY = "favourite_movies";
private List<Movie> mMovies=new ArrayList<>();
private RecyclerView mFavouritesRecyclerView;
ArrayList<Movie> moviesArrayList;
private FavouritesAdapter mAdapter;
private TabLayout mTabLayout;
public FavouritesFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
Log.v(TAG,"In OnCreate()");
super.onCreate(savedInstanceState);
}
#Override
public void onPause() {
Log.v(TAG,"OnPause() Called");
super.onPause();
}
#Override
public void onResume() {
/* Sugar ORM does not have a Loader
so to refresh the recyclerview adapter I am reinitializing it*/
Log.v(TAG,"OnResume() Called");
mMovies=Movie.listAll(Movie.class);
mAdapter=new FavouritesAdapter();
mFavouritesRecyclerView.setAdapter(mAdapter);
mFavouritesRecyclerView.invalidate();
super.onResume();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.v(TAG,"In OnCreateView()");
View view = inflater.inflate(R.layout.fragment_favourites,container,false);
mFavouritesRecyclerView=(RecyclerView)view.findViewById(R.id.favourites_recyclerview);
if(savedInstanceState!=null&&savedInstanceState.containsKey(FAVOURITE_MOVIES_ARRAY))
{
Log.v(TAG,"Restoring State");
mMovies=savedInstanceState.getParcelableArrayList(FAVOURITE_MOVIES_ARRAY);
}
else {
mMovies= Movie.listAll(Movie.class);
}
if(getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
mFavouritesRecyclerView.setLayoutManager(new
GridLayoutManager(getActivity(), 2));
}
else{
mFavouritesRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
}
mAdapter= new FavouritesAdapter();
mFavouritesRecyclerView.setAdapter(mAdapter);
mFavouritesRecyclerView.invalidate();
return view;
}
private class FavouritesHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
private ImageView mPosterImageView;
private Movie mMovie;
public FavouritesHolder(View itemView) {
super(itemView);
mPosterImageView=(ImageView)itemView.findViewById(R.id.poster);
itemView.setOnClickListener(this);
}
public void bind(Movie movie)
{
mMovie=movie;
Picasso mPicasso= Picasso.with(getActivity());
mPicasso.setIndicatorsEnabled(true);
mPicasso.load(API.IMAGE_URL+API.IMAGE_SIZE_500+mMovie.getPosterPath())
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.into(mPosterImageView);
}
#Override
public void onClick(View v) {
ActivityOptions options=ActivityOptions.makeSceneTransitionAnimation(getActivity(),mPosterImageView,"posterImage");
((openDetailsListener)getActivity()).openDetails(mMovie,options);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
moviesArrayList=new ArrayList<>(mMovies);
Log.v(TAG,"Saving State");
outState.putParcelableArrayList(FAVOURITE_MOVIES_ARRAY,moviesArrayList);
super.onSaveInstanceState(outState);
}
private class FavouritesAdapter extends RecyclerView.Adapter<FavouritesHolder>
{
#Override
public FavouritesHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(getActivity()).inflate(R.layout.movie_item,parent,false);
return new FavouritesHolder(view);
}
#Override
public void onBindViewHolder(FavouritesHolder holder, int position) {
Movie movie= mMovies.get(position);
holder.bind(movie);
}
#Override
public int getItemCount() {
return mMovies.size();
}
}
public interface openDetailsListener{
void openDetails(Movie movie,ActivityOptions options);
}
}
DetailsFragment.java
package com.execube.genesis.views.fragments;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.execube.genesis.R;
import com.execube.genesis.model.Movie;
import com.execube.genesis.model.Review;
import com.execube.genesis.model.Trailer;
import com.execube.genesis.utils.API;
import com.execube.genesis.utils.JSONParser;
import com.execube.genesis.utils.OkHttpHandler;
import com.orm.SugarRecord;
import com.squareup.picasso.Picasso;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Response;
import static com.execube.genesis.R.drawable.ic_favorite_black_24dp;
/**
* Created by Prateek Phoenix on 4/30/2016.
*/
public class DetailsFragment extends Fragment {
private static final String TAG = "DETAILS";
private static final int DEFAULT_NUM_COLORS = 5;
private Movie mMovie;
private Movie entry,tempMovie;
private List<Movie> movie;
public Intent intent;
private TextView mDetailTitle;
private TextView mReleaseDate;
private TextView mOverview;
private TextView mOverviewHeader;
private TextView mReviesHeader;
private TextView mTrailersHeader;
private ImageView mBackdrop;
private Toolbar mToolbar;
private RatingBar mRatingBar;
private ArrayList<Review> mReviews=new ArrayList<>();
private ArrayList<Trailer> mTrailers=new ArrayList<>();
public static final String MOVIE_REVIEWS_ARRAY ="movie_details";
private static final String MOVIE_TRAILERS_ARRAY = "movie_reviews";
private Typeface fontBold;
private Typeface fontMediumLight;
private Typeface fontMedium;
private RecyclerView mReviewRecyclerView;
private RecyclerView mTrailerRecyclerView;
private ProgressBar mReviewsProgressbar;
private ProgressBar mTrailersProgressbar;
private CoordinatorLayout mCoordinatorLayout;
private CardView mReviewsCardView;
private FloatingActionButton mFloatingActionButton;
private ReviewsAdapter mReviewAdapter;
private int NumOfReviews;
private TrailersAdapter mTrailerAdapter;
private String id;
private boolean isFav;
public DetailsFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.v(TAG,"Saving state in onSaveInstanceState");
outState.putParcelableArrayList(MOVIE_REVIEWS_ARRAY,mReviews);
outState.putParcelableArrayList(MOVIE_TRAILERS_ARRAY,mTrailers);
super.onSaveInstanceState(outState);
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_detail, container, false);
mBackdrop = (ImageView) view.findViewById(R.id.details_poster);
mDetailTitle = (TextView) view.findViewById(R.id.detail_title_text);
mReleaseDate = (TextView) view.findViewById(R.id.release_date);
mOverview = (TextView) view.findViewById(R.id.overview);
mOverviewHeader = (TextView) view.findViewById(R.id.overview_header);
mReviesHeader=(TextView)view.findViewById(R.id.review_header);
mTrailersHeader=(TextView)view.findViewById(R.id.trailer_header);
mRatingBar = (RatingBar) view.findViewById(R.id.movie_rating);
mCoordinatorLayout=(CoordinatorLayout)view.findViewById(R.id.coordinator_layout);
mReviewRecyclerView= (RecyclerView)view.findViewById(R.id.review_recycler_view);
mTrailerRecyclerView=(RecyclerView)view.findViewById(R.id.trailer_recycler_view);
mReviewsProgressbar=(ProgressBar)view.findViewById(R.id.reviews_progressbar);
mTrailersProgressbar=(ProgressBar)view.findViewById(R.id.trailers_progressbar);
mFloatingActionButton=(FloatingActionButton)view.findViewById(R.id.fab);
mReviewsCardView= (CardView) view.findViewById(R.id.reviews_card);
intent = getActivity().getIntent();
Bundle bundle=getArguments();
mMovie=bundle.getParcelable("PARCEL");
tempMovie=mMovie;
id = String.valueOf(mMovie.getMovieId());
checkFav();
mFloatingActionButton.show();
assert mMovie != null;
//PREPPING THE URL FOR QUERY
String reviewQueryUrl = API.MOVIES_BASE_URL + id + "/reviews" + API.API_KEY;
String trailerQueryUrl = API.MOVIES_BASE_URL + id + "/videos" + API.API_KEY;
mDetailTitle.setText(mMovie.getTitle());
mReleaseDate.setText(mMovie.getReleaseDate());
mRatingBar.setProgress((int) mMovie.getVoteAverage());
mOverview.setText(mMovie.getOverview());
if (Build.VERSION.SDK_INT != 21) {
fontBold = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Gotham-Rounded-Bold.ttf");
fontMedium = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Gotham-Rounded-Medium.ttf");
fontMediumLight = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Gotham-Rounded-Book_.ttf");
mDetailTitle.setTypeface(fontBold);
mReleaseDate.setTypeface(fontMedium);
mOverview.setTypeface(fontMediumLight);
mOverviewHeader.setTypeface(fontBold);
mReviesHeader.setTypeface(fontBold);
mTrailersHeader.setTypeface(fontBold);
}
//FETCHING JSON HERE
if(savedInstanceState!=null&&savedInstanceState.containsKey(MOVIE_REVIEWS_ARRAY))
{
Log.v(TAG,"Restoring from bundle");
mReviews=savedInstanceState.getParcelableArrayList(MOVIE_REVIEWS_ARRAY);
mTrailers=savedInstanceState.getParcelableArrayList(MOVIE_TRAILERS_ARRAY);
mReviewsProgressbar.setVisibility(View.GONE);
mTrailersProgressbar.setVisibility(View.GONE);
}
else {
OkHttpHandler reviewsHandler = new OkHttpHandler(reviewQueryUrl, reviewsCallback);
reviewsHandler.fetchData();
OkHttpHandler trailersHandler= new OkHttpHandler(trailerQueryUrl, trailersCallback);
trailersHandler.fetchData();
}
Picasso.with(getActivity()).load(API.IMAGE_URL + API.IMAGE_SIZE_500 + mMovie.getPosterPath())
.placeholder(R.drawable.placeholder)
.error(R.drawable.error)
.into(mBackdrop);
getActivity().startPostponedEnterTransition();
mReviewRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mReviewAdapter= new ReviewsAdapter();
mReviewRecyclerView.setAdapter(mReviewAdapter);
LinearLayoutManager layoutmanager= new LinearLayoutManager(getActivity(),LinearLayoutManager.HORIZONTAL,false);
mTrailerRecyclerView.setLayoutManager(layoutmanager);
mTrailerAdapter= new TrailersAdapter();
mTrailerRecyclerView.setAdapter(mTrailerAdapter);
return view;
}
private void checkFav() {
movie=new ArrayList<>();
movie=SugarRecord.find(Movie.class,"m_id=?",id);
if(movie.size()==0)
{
Log.v(TAG,"Null");
mFloatingActionButton.setImageResource(R.drawable.ic_favorite_border_black_24dp);
}
else {
Log.v(TAG,"NOT Null");
mFloatingActionButton.setImageResource(R.drawable.ic_favorite_black_24dp);
}
mFloatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
movie=SugarRecord.find(Movie.class,"m_id=?",id);
if(movie.size()>0)
{
entry = movie.get(0);
entry.delete();
mFloatingActionButton.setImageResource(R.drawable.ic_favorite_border_black_24dp);
Snackbar snackbar = Snackbar.make(mCoordinatorLayout,"Movie removed from Favourites!!",Snackbar.LENGTH_SHORT);
View view= snackbar.getView();
TextView textView = (TextView)view.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
else
{
entry = tempMovie;
entry.save();
mFloatingActionButton.setImageResource(R.drawable.ic_favorite_black_24dp);
Snackbar snackbar = Snackbar.make(mCoordinatorLayout,"Movie added to Favourites!!",Snackbar.LENGTH_SHORT);
View view= snackbar.getView();
TextView textView = (TextView)view.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
});
}
//OKHTTP CALLBACK FOR NETWORK CALL
private okhttp3.Callback reviewsCallback = new okhttp3.Callback() {
#Override
public void onFailure(Call call, IOException e) {
//TODO handle failure on UI thread
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
String JSONData= response.body().string();
JSONObject jsonObject = new JSONObject(JSONData);
NumOfReviews = jsonObject.getInt("total_results");
JSONParser parser = new JSONParser();
Log.v(TAG,JSONData);
mReviews=parser.parseReviews(JSONData);
} catch (JSONException e) {}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if(mReviewAdapter!=null)
{
mReviewsProgressbar.setVisibility(View.GONE);
mReviewAdapter.notifyDataSetChanged();
}
}
});
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (NumOfReviews==0)
{
mReviewsCardView.setVisibility(View.INVISIBLE);
}
}
});
}
};
private okhttp3.Callback trailersCallback = new okhttp3.Callback() {
#Override
public void onFailure(Call call, IOException e) {
//TODO handle failure on UI thread
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
String json1= response.body().string();
JSONParser parser= new JSONParser();
Log.v(TAG, json1);
mTrailers = parser.parseTrailers(json1);
} catch (JSONException e) {}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if(mTrailerAdapter!=null)
{
mTrailersProgressbar.setVisibility(View.GONE);
mTrailerAdapter.notifyDataSetChanged();
}
}
});
}
};
private class ReviewViewHolder extends RecyclerView.ViewHolder{
private TextView mAuthorText;
private TextView mReviewText;
private Review mReview;
public ReviewViewHolder(View itemView) {
super(itemView);
mAuthorText= (TextView) itemView.findViewById(R.id.author_textview);
mReviewText= (TextView) itemView.findViewById(R.id.review_textview);
}
public void bind(Review review)
{
mReview= review;
mAuthorText.setText(mReview.getAuthor());
mReviewText.setText(mReview.getContent());
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP)
{
mAuthorText.setTypeface(fontBold);
mReviewText.setTypeface(fontMediumLight);
}
}
}
private class ReviewsAdapter extends RecyclerView.Adapter<ReviewViewHolder>{
#Override
public ReviewViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(getActivity()).inflate(R.layout.review_item,parent,false);
return new ReviewViewHolder(view);
}
#Override
public void onBindViewHolder(ReviewViewHolder holder, int position) {
Review review= mReviews.get(position);
holder.bind(review);
}
#Override
public int getItemCount() {
if(mReviews==null)
{ return 0;}
else
{return mReviews.size();}
}
}
private class TrailerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView mTrailerThumbnail;
private Trailer mTrailer;
public TrailerViewHolder(View itemView) {
super(itemView);
mTrailerThumbnail=(ImageView)itemView.findViewById(R.id.trailer_thumbnail);
itemView.setOnClickListener(this);
}
public void bind(Trailer trailer)
{
mTrailer=trailer;
Picasso picasso =Picasso.with(getActivity());
picasso.setIndicatorsEnabled(true);
picasso.load(API.YOUTUBE_THUMBNAIL_URL+mTrailer.getKey()+API.THUMBNAIL_QUALITY)
.into(mTrailerThumbnail);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(API.YOUTUBE_TRAILER_URL+mTrailer.getKey()));
startActivity(intent);
}
}
private class TrailersAdapter extends RecyclerView.Adapter<TrailerViewHolder>
{
#Override
public TrailerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(getActivity()).inflate(R.layout.trailer_item,parent,false);
return new TrailerViewHolder(view);
}
#Override
public void onBindViewHolder(TrailerViewHolder holder, int position) {
Trailer trailer= mTrailers.get(position);
holder.bind(trailer);
}
#Override
public int getItemCount() {
return mTrailers.size();
}
}
}
You can use an Interface to communicate between Fragments (Here's a question I asked an year ago and the accepted answer was really easy to understand).
Then, you need to call mAdapter.notifyDataSetChanged() in your callBack method.
I propose one way to solve this.
class TabletActivity extends Activity implements DetailFragment.Callback {
public void onCreate(Bundle savedInstanceState){
//Initialise fragments
}
void onItemDelete(){
// find the Master Fragment using FragmentManager;
MasterFragment f = (MasterFragment) getFragmentManager().findFragmentById();
if (f != null){
f.somethingHasChanged();
}
}
}
class DetailFragment extends Fragment {
private Callback callback;
public onAttach(Context context){
this.callback = (Context) context;
}
public void onViewCreated(View v, Bundle b){
Button b;
b.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
callback.onItemDelete();
}
)
}
public interface Callback {
void onItemDelete();
}
}
class MasterFragment extends Fragment {
public void somethingHasChanged(){
adapter.notifyDatasetChanged();
}
}
DetailFragment is where we initiate the changes, MasterFragment is consuming the changes. That communication is don't via the Activity. I personally don't recommend notifyAdapterChanges in OnResume() as you proposed because there is no guarantee that onResume will be call right after the changes in you data has been made.
Read more at:
https://developer.android.com/training/basics/fragments/communicating.html