Realtime data exchange between Android Wearable and Handheld - wear-os

I am working on a simple app which will run on both wearable(Samsung Gear Live) and handheld(Moto G). I want to display the data from the wearable's heart rate sensor, accelerometer and gyroscope on the handheld. Which is the best way to achieve this.
Now I am using DataApi, but since I am updating data each second, it is allocating too much memory, and then killed by OS.
Here is my service which runs on the wearable
public class SensorDataListener extends Service implements SensorEventListener,
ConnectionCallbacks, OnConnectionFailedListener {
private static final String TAG = SensorDataListener.class.getSimpleName();
private static final int TIMEOUT_HEART_RATE = 1000000;
private static final int TIMEOUT_ACCELEROMETER = 1000000;
private static final int TIMEOUT_GYROSCOPE = 1000000;
private static final String PATH_SENSOR_DATA = "/sensor_data";
private static final String KEY_HEART_RATE = "heart_rate";
private static final String KEY_ACC_X = "acc_x";
private static final String KEY_ACC_Y = "acc_y";
private static final String KEY_ACC_Z = "acc_z";
private static final String KEY_GYRO_X = "gyro_x";
private static final String KEY_GYRO_Y = "gyro_y";
private static final String KEY_GYRO_Z = "gyro_z";
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private Sensor mGyroscope;
private Sensor mHeartRate;
private int mCurHeartRateVal;
private float[] mCurAccelerometerVal = new float[3];
private float[] mCurGyroscopeVal = new float[3];
private GoogleApiClient mGoogleApiClient;
ScheduledExecutorService mUpdateScheduler;
ScheduledExecutorService scheduler;
#Override
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(com.google.android.gms.wearable.Wearable.API)
.build();
mGoogleApiClient.connect();
mSensorManager = ((SensorManager)getSystemService(SENSOR_SERVICE));
mHeartRate = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mGyroscope = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
startDataUpdated();
}
private void startDataUpdated() {
scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate
(new Runnable() {
public void run() {
updateData();
}
}, 5, 3, TimeUnit.SECONDS);
}
private void updateData() {
PutDataMapRequest dataMap = PutDataMapRequest.create(PATH_SENSOR_DATA);
dataMap.getDataMap().putInt(KEY_HEART_RATE, mCurHeartRateVal);
dataMap.getDataMap().putFloat(KEY_ACC_X, mCurAccelerometerVal[0]);
dataMap.getDataMap().putFloat(KEY_ACC_Y, mCurAccelerometerVal[1]);
dataMap.getDataMap().putFloat(KEY_ACC_Z, mCurAccelerometerVal[2]);
dataMap.getDataMap().putFloat(KEY_GYRO_X, mCurGyroscopeVal[0]);
dataMap.getDataMap().putFloat(KEY_GYRO_Y, mCurGyroscopeVal[1]);
dataMap.getDataMap().putFloat(KEY_GYRO_Z, mCurGyroscopeVal[2]);
PutDataRequest request = dataMap.asPutDataRequest();
Wearable.DataApi.putDataItem(mGoogleApiClient, request);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mSensorManager.registerListener(this, mHeartRate, TIMEOUT_HEART_RATE);
mSensorManager.registerListener(this, mAccelerometer, TIMEOUT_ACCELEROMETER);
mSensorManager.registerListener(this, mGyroscope, TIMEOUT_GYROSCOPE);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
mGoogleApiClient.disconnect();
scheduler.shutdown();
mSensorManager.unregisterListener(this);
//mUpdateScheduler.shutdownNow();
super.onDestroy();
}
#Override
public void onSensorChanged(SensorEvent event) {
switch(event.sensor.getType()) {
case Sensor.TYPE_HEART_RATE:
if(event.values[0] <= 0) // HR sensor is being initialized
return;
mCurHeartRateVal = Float.valueOf(event.values[0]).intValue();
break;
case Sensor.TYPE_ACCELEROMETER:
mCurAccelerometerVal[0] = event.values[0];
mCurAccelerometerVal[1] = event.values[1];
mCurAccelerometerVal[2] = event.values[2];
break;
case Sensor.TYPE_GYROSCOPE: {
mCurGyroscopeVal[0] = event.values[0];
mCurGyroscopeVal[1] = event.values[1];
mCurGyroscopeVal[2] = event.values[2];
break;
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {}
#Override
public void onConnected(Bundle bundle) { Log.d(TAG, "onConnected"); }
#Override
public void onConnectionSuspended(int i) { Log.d(TAG, "onConnectionSuspended"); }
#Override
public void onConnectionFailed(ConnectionResult connectionResult) { Log.d(TAG, "onConnectionFailed"); }
#Override
public IBinder onBind(Intent intent) {
return null;
}
}

Try using the Message API instead of the Data API. Simply create a message containing your data and send it over to your other device : http://developer.android.com/reference/com/google/android/gms/wearable/MessageApi.html

Have you try with Teleport (data sync & messaging lib) by Mario Viviani

Related

Why is my recyclerview only displaying the content of the first item?

I am having a problem with my recyclerview, It only displays the content of the first item like this:
I have no idea what caused this, I'm really confused because I have never encountered something like this before. As you can see on the toast, the response return 3 data but I don't understand why the others are not being displayed.
Playlist.java
public class Playlist extends AppCompatActivity {
// inisiasi toolbar
private Toolbar toolbar;
// navigation drawer
public DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
RecyclerView recyclerView;
String[] id,title,dir, artists;
ArrayList<String> artist;
String navTitles[];
TypedArray navIcons;
RecyclerView.Adapter recyclerViewAdapter;
TextView textView;
String video;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playlist);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(getResources().getColor(R.color.colorIcons), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
Intent intent = getIntent();
video = intent.getStringExtra("songs");
//textView = (TextView) findViewById(R.id.text);
//textView.setText(video);
getPlaylist();
// dir = PlaylistJson.dirs;
//artist = new ArrayList<String>(Arrays.asList(title));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
private void getPlaylist(){
final ProgressDialog loading = ProgressDialog.show(this,"Fetching Data","Please wait...",false,false);
//Creating a string request
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://musicmania.hol.es/playlist/getSongsFromPlaylist",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//If we are getting success from server
Toast.makeText(Playlist.this, response, Toast.LENGTH_LONG).show();
loading.dismiss();
showPlaylistJSON(response);
id = PlaylistJson.ids;
title = PlaylistJson.titles;
artists = PlaylistJson.artists;
recyclerView= (RecyclerView) findViewById(R.id.my_recycler_view);
RecyclerViewAdapter adapter=new RecyclerViewAdapter(id, title,artists, Playlist.this);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(Playlist.this));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//You can handle error here if you want
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
//Adding parameters to request
params.put("playlist", video);
//returning parameter
return params;
}
};
//Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showPlaylistJSON(String json){
PlaylistJson pj = new PlaylistJson(json);
pj.parseJSON();
}
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> {
LayoutInflater inflater;
Context context;
String[] id,title, artists;
public RecyclerViewAdapter(String[] id, String[] titles, String[] artists, Context context){
this.id = id;
this.title = titles;
this.artists = artists;
this.context = context;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = null;
RecyclerViewHolder viewHolder = null;
if(Integer.parseInt(id[0]) != 0){
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list, parent, false);
viewHolder = new RecyclerViewHolder(view, context);
}else{
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.empty_list, parent, false);
viewHolder = new RecyclerViewHolder(view, context);
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
if(Integer.parseInt(id[0]) != 0) {
holder.item2.setText(title[position]);
holder.imageView2.setTag(holder);
holder.artist.setText(artists[position]);
}else{
holder.item2.setText(title[position]);
}
}
#Override
public int getItemCount() {
return title.length;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView item;
ImageView imageView;
TextView item2;
TextView artist;
ImageView imageView2;
ImageButton addtoplaylist;
Context context;
public RecyclerViewHolder(final View itemView, final Context context) {
super(itemView);
this.context = context;
item = (TextView) itemView.findViewById(R.id.tv_NavTitle);
imageView = (ImageView) itemView.findViewById(R.id.iv_NavIcon);
item2 = (TextView) itemView.findViewById(R.id.list_title);
imageView2 = (ImageView) itemView.findViewById(R.id.list_avatar);
artist = (TextView) itemView.findViewById(R.id.list_artist);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), Video.class);
intent.putExtra("video", ParseJson.dirs[getAdapterPosition()]);
v.getContext().startActivity(intent);
}
});
}
}
}
PlaylistJson.java
package com.example.rendell.musicmaniajukebox.json_model;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class PlaylistJson {
public static String[] ids;
public static String[] titles;
public static String[] artists;
public static String[] dirs;
public static final String JSON_ARRAY = "result";
public static final String KEY_ID = "id";
public static final String KEY_TITLE = "title";
public static final String KEY_ARTIST = "artist";
public static final String KEY_DIR = "dir";
private JSONArray users = null;
private String json;
public PlaylistJson(String json){
this.json = json;
}
public void parseJSON(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
ids = new String[users.length()];
titles = new String[users.length()];
artists = new String[users.length()];
dirs = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
ids[i] = jo.getString(KEY_ID);
titles[i] = jo.getString(KEY_TITLE);
artists[i] = jo.getString(KEY_ARTIST);
dirs[i] = jo.getString(KEY_DIR);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
So the problem was in my PlaylistJson.java file. My volley response only returns 3 items per set e.g. {"id":1, "title": "song", "artist":"artist"} but I am also initialing for the dir which doesn't receive any json so maybe the bug came from that. Anyway, removed that and it worked.

getting a 401 error on connecting to linkedin rest api with volley

I am trying to get email address of a user through linkedin's rest api. I am using volley for the request. But it shows 401 error. Can anyone help me through this. Below is the code. Access token is for r_basicprofile and r_emailaddress permissions
private static final String PROFILE_URL = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address)";
private static final String OAUTH_ACCESS_TOKEN_PARAM ="oauth2_access_token";
private static final String QUESTION_MARK = "?";
private static final String EQUALS = "=";
private static final String HEADER_CONTENT_TYPE = "Content-Type";
private static final String HEADER_AUTHORIZATION = "Authorization";
private static final String HEADER_SRC = "x-li-src";
private static final String HEADER_LI_FORMAT = "x-li-format";
private static final String HEADER_LI_VER = "x-li-msdk-ver";
private static final String CONTENT_VALUE = "application/json";
private static final String HEADER_SRC_VALUE = "msdk";
private static final String HEADER_LI_FORMAT_VALUE = "json";
private TextView welcomeText;
private ProgressDialog pd;
String accessToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fflifind_friends);
welcomeText = (TextView) findViewById(R.id.activity_profile_welcome_text);
//Request basic profile of the user
SharedPreferences preferences = this.getSharedPreferences("user_info", 0);
accessToken = preferences.getString("accessToken", null);
if(accessToken!=null){
String profileUrl = getProfileUrl(accessToken);
Log.d("profile url", profileUrl);
// new GetProfileRequestAsyncTask().execute(profileUrl);
doServer(profileUrl);
}
}
private Map<String, String> getLiHeaders(String accessToken) {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put(HEADER_CONTENT_TYPE, CONTENT_VALUE);
headers.put(HEADER_AUTHORIZATION, "Bearer " + accessToken);
headers.put(HEADER_SRC, HEADER_SRC_VALUE);
headers.put(HEADER_LI_FORMAT, HEADER_LI_FORMAT_VALUE);
//headers.put(HEADER_LI_VER, BuildConfig.MSDK_VERSION);
return headers;
}
private static final String getProfileUrl(String accessToken){
String url = PROFILE_URL
+ QUESTION_MARK
+ OAUTH_ACCESS_TOKEN_PARAM + EQUALS + accessToken;
return url;
}
public void doServer(String url)
{
final ProgressDialog dialog = ProgressDialog.show(this, null, "Loading data ");
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
dialog.dismiss();
Log.d("Jsonres-", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
// TODO Auto-generated method stub
Log.d("error ","err");
Toast.makeText(getApplicationContext(), error.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return getLiHeaders(accessToken);
}
};
NetworkRequestQueue.getInstance(this).addToRequestQueue(jsObjRequest);
}
Use this method to get the profile information of linkedin account and define what you want from profile in PROFILE_LINK string mention below it's working fine for me.I hope its solved your problem.
public static final String HOST="https://api.linkedin.com/";
public static final String PROFILE_LINK=HOST+"v1/people/~:(id,firstName,lastName,picture-url)?oauth2_access_token=";
public static final String JSON_FORMAT=AMPERSAND+"format=json";
private void profileRequestAsyncTask(final String accessToken) {
showProgressDialog();
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(activity);
String url=PROFILE_LINK+accessToken+JSON_FORMAT;
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Log.e(TAG, "onResponse: "+response );
JSONObject dataAsJson= null;
try {
dataAsJson = new JSONObject(response);
String id=dataAsJson.getString("id");
String firstName=dataAsJson.getString("firstName");
String lastName=dataAsJson.getString("lastName");
String pictureUrl=dataAsJson.getString("pictureUrl");
Log.e(TAG, "onResponse: "+id+"="+firstName+"-"+lastName+"-"+pictureUrl );
String username=firstName+" "+lastName;
insertLinkedinAccount(id,username,pictureUrl,accessToken,expires);
editor.clear();
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
//Log.e(TAG, "onApiSuccess:profileData- "+firstName+"-"+lastName+"-"+profileId);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: "+error );
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}

WearableListenerService doesn't receive data

I'm trying to send sensor data from my wear device to the handheld. The problem is that the onMessageReceived function of my WearableListenerService is never called, even though it gets created.
The package names of the wear and mobile apps are the same, also here's the entry for the service in the manifest file:
<service
android:name=".WatchDataReceiver"
android:enabled="true"
android:exported="true" >
</service>
On my handheld in the MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(this, WatchDataReceiver.class));
setContentView(R.layout.activity_fullscreen);
...
}
On my handheld, the service:
public class WatchDataReceiver extends WearableListenerService {
#Override
public void onCreate() {
super.onCreate();
Log.i(WatchDataReceiver.class.getSimpleName(), "WEAR create");
}
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
Log.i(WatchDataReceiver.class.getSimpleName(), "WEAR Data changed " );
}
#Override
public void onMessageReceived(MessageEvent messageEvent) {
Log.i(WatchDataReceiver.class.getSimpleName(), "WEAR Message " + messageEvent.getPath());
}
}
On the watch/wear:
public class MainActivity extends Activity implements SensorEventListener {
private static final String LOG_TAG = "Watch: ";
private SensorManager sensorManager;
private Sensor accelerometer;
private GoogleApiClient mGoogleApiClient;
private String msg = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mTextView = (TextView) stub.findViewById(R.id.text);
}
});
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_FASTEST);
if (accelerometer != null) {
Log.v(LOG_TAG, "Accelerometer registered!");
}
else {
Log.v(LOG_TAG, "Accelerometer _not_ registered!");
}
mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Wearable.API).build();
mGoogleApiClient.connect();
}
#Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER && event.values.length > 0) {
double value_x = event.values[0];
double value_y = event.values[1];
double value_z = event.values[2];
msg = Double.toString(value_x) + ";" + Double.toString(value_y) + ";" + Double.toString(value_z);
sendMessageToHandheld(msg);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
//TODO
}
private void sendMessageToHandheld(String msg) {
if (mGoogleApiClient == null)
return;
final String message = msg;
Log.d(LOG_TAG,"sending a message to handheld: "+message);
// use the api client to send the heartbeat value to our handheld
final PendingResult<NodeApi.GetConnectedNodesResult> nodes = Wearable.NodeApi.getConnectedNodes(mGoogleApiClient);
nodes.setResultCallback(new ResultCallback<NodeApi.GetConnectedNodesResult>() {
#Override
public void onResult(NodeApi.GetConnectedNodesResult result) {
final List<Node> nodes = result.getNodes();
if (nodes != null) {
for (int i=0; i<nodes.size(); i++) {
final Node node = nodes.get(i);
Wearable.MessageApi.sendMessage(mGoogleApiClient, node.getId(), message, null);
}
}
}
});
}
}
According to LogCat the correct handheld is found because in sendMessageToHandheld right after the actual sendMessage it do a Log.d with the name of the node.
What am I missing?
You have to add this IntentFilter to your service:
<intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
</intent-filter>
It tells the system to take care of the Service lifecycle (ie starting it if needed).

Volley library throws application exception

I am adding my two separate android activities in one application, one of my activity having volley library but it gives me an exception that appcontroller(volley library) its an application not an activity please help me out
Ya, you have mention in your manifest file appcontroller class as Application. This solves the exception.
Main Acitivity:
public class MainActivity extends FragmentActivity implements OnTabChangeListener, OnPageChangeListener {
MyPageAdapter pageAdapter;
private ViewPager mViewPager;
private TabHost mTabHost;
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
// Tab Initialization
initialiseTabHost();
// Fragments and ViewPager Initialization
List<Fragment> fragments = getFragments();
pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
mViewPager.setAdapter(pageAdapter);
mViewPager.setOnPageChangeListener(MainActivity.this);
}
// Method to add a TabHost
private static void AddTab(MainActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec,String message,int picture,Context x)
{
tabSpec.setContent(new MyTabFactory(activity));
View tabIndicator = LayoutInflater.from(x).inflate(R.layout.tab_indicator, tabHost.getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(message);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
icon.setBackgroundDrawable(x.getResources().getDrawable(picture));
icon.setScaleType(ImageView.ScaleType.FIT_CENTER);
tabSpec.setIndicator(tabIndicator);
tabHost.addTab(tabSpec);
}
// Manages the Tab changes, synchronizing it with Pages
public void onTabChanged(String tag) {
int pos = this.mTabHost.getCurrentTab();
this.mViewPager.setCurrentItem(pos);
for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
{
mTabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.BLUE);
//mTabHost.getTabWidget().setDividerDrawable(R.Color.transperant);
}
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.CYAN);// selected
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
public void destroyItem(View collection, int position, Object view){
((ViewPager) collection).removeView((ImageView) view);
}
// Manages the Page changes, synchronizing it with Tabs
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
int pos = this.mViewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
#Override
public void onPageSelected(int arg0) {
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
// TODO Put here your Fragments
NewSampleFragment f1 = NewSampleFragment.newInstance(getApplicationContext(),R.layout.newfragment_a);
MySampleFragment f2 = MySampleFragment.newInstance("Sample Fragment 2");
MySampleFragment f3 = MySampleFragment.newInstance("Sample Fragment 3");
MySampleFragment f4 = MySampleFragment.newInstance("Sample Fragment 4");
MySampleFragment f5 = MySampleFragment.newInstance("Sample Fragment 5");
fList.add(f1);
fList.add(f2);
fList.add(f3);
fList.add(f4);
fList.add(f5);
return fList;
}
// Tabs Creation
private void initialiseTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
// TODO Put here your Tabs
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab1").setIndicator("Tab1"),"Grocery",R.drawable.movies,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab2").setIndicator("Tab2"),"Crockery",R.drawable.artist,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab3"),"Foods",R.drawable.song,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab4"),"Drinks",R.drawable.shopping,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab5"),"Toys",R.drawable.play,getApplicationContext());
mTabHost.setOnTabChangedListener(this);
}
}
OfferActivity (This should be open when button pressed)
public class OfferActivity extends Activity
{
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private ProgressDialog pDialog;
private String URL_FEED = "http://nusdtech.com/public_html/checking2.php";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
//getActionBar().setIcon(
// new ColorDrawable(getResources().getColor(android.R.color.transparent)));
JsonArrayRequest movieReq = new JsonArrayRequest(URL_FEED,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
FeedItem movie = new FeedItem();
movie.setId(obj.getInt("id"));
movie.setName(obj.getString("name"));
// Image might be null sometimes
String image = obj.isNull("image") ? null : obj
.getString("image");
movie.setImge(image);
movie.setStatus(obj.getString("status"));
movie.setProfilePic(obj.getString("profilePic"));
//movie.setTimeStamp(obj.getString("price"));
movie.setPrice(obj.getString("price"));
movie.setDate(obj.getString("dates"));
feedItems.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
listAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
AppController:
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
LruBitmapCache mLruBitmapCache;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
getLruBitmapCache();
mImageLoader = new ImageLoader(this.mRequestQueue, mLruBitmapCache);
}
return this.mImageLoader;
}
public LruBitmapCache getLruBitmapCache() {
if (mLruBitmapCache == null)
mLruBitmapCache = new LruBitmapCache();
return this.mLruBitmapCache;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Activity that contain fragment buttons
public class NewSampleFragment extends Fragment {
private static View mView;
private Context con;
public static final NewSampleFragment newInstance(Context con,int layout) {
NewSampleFragment f = new NewSampleFragment();
con=con;
Bundle b = new Bundle();
b.putInt("mylayout",layout);
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int layout = getArguments().getInt("mylayout");
mView = inflater.inflate(R.layout.newfragment_a, container, false);
Button button = (Button) mView.findViewById(R.id.bactivity);
Button offer=(Button) mView.findViewById(R.id.aactivity);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent myIntent = new Intent(getActivity(), ListViewDemo.class);
//Optional parameters
getActivity().startActivity(myIntent);
Log.e("Error","Kashif");
}
});
offer.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
startApplication("uzair.sabir.app.OfferActivity");
}
});
return mView;
}
public void startApplication(String application_name){
try{
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
List<ResolveInfo> resolveinfo_list = getActivity().getPackageManager().queryIntentActivities(intent, 0);
for(ResolveInfo info:resolveinfo_list){
if(info.activityInfo.packageName.equalsIgnoreCase(application_name)){
launchComponent("uzair.sabir.app", "OfferActivity");
break;
}
}
}
catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), "There was a problem loading the application: "+application_name,Toast.LENGTH_SHORT).show();
Log.e("Error",e.getMessage());
}
}
private void launchComponent(String packageName, String name){
Intent launch_intent = new Intent("android.intent.action.MAIN");
launch_intent.addCategory("android.intent.category.LAUNCHER");
launch_intent.setComponent(new ComponentName(packageName, name));
launch_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().startActivity(launch_intent);
}
}

GWT application crashes in latest Firefox versions 21 and above

We have a GWT application which crashes in Firefox versions 21 and above, including in the latest version 23.0.1. In earlier versions of Firefox and IE 9, it works fine. This is in deployed mode and not because of the GWT plugin. The situation it crashes is when there are huge number of RPC calls, may be around 300 to 400.
As the application in which it happens is fairly complex, I tried to simulate this issue with a simple prototype. I observed that my prototype crashes when the number of RPC calls reach 100000. But this scenario is very unlikely in my application where RPC calls are around 300-400 as observed using Firebug.
I am trying to find out what else I am missing in my prototype so that it also crashes with 300-400 RPC calls.
GWT version - 2.4
GXT version - 2.2.5
package com.ganesh.check.firefox.client;
public class FirefoxCrash implements EntryPoint {
private static final String SERVER_ERROR = "An error occurred while "
+ "attempting to contact the server. Please check your network "
+ "connection and try again.";
private final GreetingServiceAsync greetingService = GWT
.create(GreetingService.class);
public native static void consoleLog(String text)/*-{
$wnd.console.log(text);
}-*/;
public void onModuleLoad() {
final Button sendButton = new Button("Send");
final TextBox nameField = new TextBox();
nameField.setText("GWT User");
final Label errorLabel = new Label();
final Label countLabel = new Label();
// We can add style names to widgets
sendButton.addStyleName("sendButton");
// Add the nameField and sendButton to the RootPanel
// Use RootPanel.get() to get the entire body element
RootPanel.get("nameFieldContainer").add(nameField);
RootPanel.get("sendButtonContainer").add(sendButton);
RootPanel.get("errorLabelContainer").add(errorLabel);
RootPanel.get("count").add(countLabel);
// Focus the cursor on the name field when the app loads
nameField.setFocus(true);
nameField.selectAll();
// Create the popup dialog box
final DialogBox dialogBox = new DialogBox();
dialogBox.setText("Remote Procedure Call");
dialogBox.setAnimationEnabled(true);
final Button closeButton = new Button("Close");
// We can set the id of a widget by accessing its Element
closeButton.getElement().setId("closeButton");
final Label textToServerLabel = new Label();
final HTML serverResponseLabel = new HTML();
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.addStyleName("dialogVPanel");
dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
dialogVPanel.add(textToServerLabel);
dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
dialogVPanel.add(serverResponseLabel);
dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
dialogVPanel.add(closeButton);
dialogBox.setWidget(dialogVPanel);
// Add a handler to close the DialogBox
closeButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
dialogBox.hide();
sendButton.setEnabled(true);
sendButton.setFocus(true);
}
});
class MyHandler implements ClickHandler, KeyUpHandler {
private int resultCount = 0;
/**
* Fired when the user clicks on the sendButton.
*/
public void onClick(ClickEvent event) {
sendNameToServer();
}
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
sendNameToServer();
}
}
private void sendNameToServer() {
// First, we validate the input.
errorLabel.setText("");
String textToServer = nameField.getText();
// Then, we send the input to the server.
textToServerLabel.setText(textToServer);
serverResponseLabel.setText("");
final int loopCount = Integer.parseInt(textToServer);
resultCount=0;
for (int i = 0; i < loopCount; i++) {
greetingService.getResult(textToServer,
new AsyncCallback<ResultBean>() {
public void onFailure(Throwable caught) {
consoleLog(caught.getMessage());
}
public void onSuccess(ResultBean result) {
//countLabel.setText(++resultCount + "");
resultCount++;
if(resultCount==loopCount){
countLabel.setText(resultCount + "");
}
consoleLog("Result returned for "+resultCount);
}
});
}
}
}
// Add a handler to send the name to the server
MyHandler handler = new MyHandler();
sendButton.addClickHandler(handler);
nameField.addKeyUpHandler(handler);
}
}
public class GreetingServiceImpl extends RemoteServiceServlet implements
GreetingService {
public ResultBean getResult(String name) {
ResultBean result = new ResultBean();
Random random = new Random();
int suffix = random.nextInt();
result.setName("Name "+suffix);
result.setAddress("Address "+suffix);
result.setZipCode(suffix);
result.setDoorNumber("Door "+suffix);
return result;
}
public class ResultBean implements Serializable {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getZipCode() {
return zipCode;
}
public void setZipCode(int zipCode) {
this.zipCode = zipCode;
}
public String getDoorNumber() {
return doorNumber;
}
public void setDoorNumber(String doorNumber) {
this.doorNumber = doorNumber;
}
private String name;
private String address;
private int zipCode;
private String doorNumber;
}

Resources