Help with ViewPager and Fragments - Java for Android App Development

Hi all!
I've been developing an app that uses various things from my college and centralizes them in one app. I've made the app with two tabs - one for current students and one for prospective students. I would like to add the functionality of swiping between the two activities, and I saw that to do that, I want to convert my currentStudents and prospectiveStudents activities into fragments.
I have a couple of questions.
First, I don't quite understand how to accomplish converting the activities into fragments.
Second, I don't quite understand how to implement the viewPager effect.
If anyone can assist me in doing this, that'd be great. I've read through a lot of guides, but those guides are written to reflect other apps and it's pretty confusing.
Here is my MainActivity:
Code:
package com.andrew.obu;
import android.app.TabActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
public class MainActivity extends TabActivity {
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabHost tabHost = getTabHost();
TabSpec cstudents = tabHost.newTabSpec("Current Students");
cstudents.setIndicator("Students");
Intent cstudentsIntent = new Intent(this, CurrentStudents.class);
cstudents.setContent(cstudentsIntent);
TabSpec prospects = tabHost.newTabSpec("Prospectives");
prospects.setIndicator("Prospectives");
Intent prospectsIntent = new Intent(this, ProspectiveStudents.class);
prospects.setContent(prospectsIntent);
tabHost.addTab(cstudents);
tabHost.addTab(prospects);
tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.BLACK);
tabHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.BLACK);
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
@Override
public void onTabChanged(String arg0) {
TabHost tabHost = getTabHost();
setTabColor(tabHost);
}
});
setTabColor(tabHost);
}
public void setTabColor(TabHost tabhost) {
for(int i=0;i<tabhost.getTabWidget().getChildCount();i++)
tabhost.getTabWidget().getChildAt(i).setBackgroundColor(Color.BLACK); //unselected
if(tabhost.getCurrentTab()==0)
tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).setBackgroundColor(Color.rgb(34, 34, 34)); //1st tab selected
else
tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).setBackgroundColor(Color.rgb(34, 34, 34)); //2nd tab selected
}
}
And my code for the CurrentStudents Activity
Code:
package com.andrew.obu;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
public class CurrentStudents extends ListActivity {
private static final int MENU_ABOUT = 0;
private static final int MENU_CONTACT = 1;
int counter;
Button banner, email, moodle, jupiter, staff, calendar, athletics, news, prosp;
TextView display;
Drawable drawable;
@Override
public boolean onCreateOptionsMenu(android.view.Menu menu)
{
menu.add(0, MENU_ABOUT, 0, "About");
menu.add(0, MENU_CONTACT, 0, "Contact Me");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case MENU_ABOUT:
doSomething();
return true;
case MENU_CONTACT:
doSomethingElse();
return true;
}
return super.onOptionsItemSelected(item);
}
private void doSomethingElse() {
Intent intent = new Intent(getBaseContext(), Contact.class);
startActivity(intent);
}
private void doSomething() {
Intent intent = new Intent(getBaseContext(), About.class);
startActivity(intent);}
/*@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cstudents);*/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] choose = getResources().getStringArray(R.array.cstudents_array);
ListView lv = getListView();
LayoutInflater lf;
View headerView;
lf = this.getLayoutInflater();
headerView = (View)lf.inflate(R.layout.cstudents, null, false);
lv.addHeaderView(headerView, null, false);
lv.setTextFilterEnabled(true);
lv.setBackgroundColor(Color.WHITE);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_content, choose));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent intent;
switch(position) {
default:
case 0 :
intent = new Intent(this, Bannerdisclaimer.class);
break;
case 2 :
intent = new Intent(this, Emailwebview.class);
break;
case 3 :
intent = new Intent(this, Moodlewebview.class);
break;
case 4 :
intent = new Intent(this, Jupiterwebview.class);
break;
case 5 :
intent = new Intent(this, Staffwebview.class);
break;
case 6 :
intent = new Intent(this, Calendar.class);
break;
case 7 :
intent = new Intent(this, Athleticswebview.class);
break;
case 8 :
intent = new Intent(this, Newswebview.class);
//intent7.putExtra("KEY_SELECTED_INDEX", position);
//startActivity(intent7);
break;
}
startActivity(intent);
};
}
//Resources res = getResources();
//drawable = res.getDrawable(R.drawable.bannera);
/*final Context context1 = this;
banner = (Button) findViewById(R.id.BannerButton);
banner.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
banner.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myWebView = new Intent(context1, Bannerwebview.class);
startActivity(myWebView);
}
});
final Context context2 = this;
email = (Button) findViewById(R.id.EmailButton);
email.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
email.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myWebView = new Intent(context2, Emailwebview.class);
startActivity(myWebView);
}
});
final Context context3 = this;
moodle = (Button) findViewById(R.id.MoodleButton);
moodle.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
moodle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myWebView = new Intent(context3, Moodlewebview.class);
startActivity(myWebView);
}
});
final Context context4 = this;
jupiter = (Button) findViewById(R.id.JupiterButton);
jupiter.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
jupiter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myWebView = new Intent(context4, Jupiterwebview.class);
startActivity(myWebView);
}
});
final Context context5 = this;
staff = (Button) findViewById(R.id.StaffButton);
staff.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
staff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myWebView = new Intent(context5, Staffwebview.class);
startActivity(myWebView);
}
});
final Context context = this;
calendar = (Button) findViewById(R.id.CalendarButton);
calendar.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
calendar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, Calendar.class);
startActivity(intent);
}
});
final Context context6 = this;
athletics = (Button) findViewById(R.id.AthleticsButton);
athletics.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
athletics.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context6, Athleticswebview.class);
startActivity(intent);
}
});
final Context context7 = this;
news = (Button) findViewById(R.id.NewsButton);
news.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
news.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context7, Newswebview.class);
startActivity(intent);
}
});*/
And my code for the ProspectiveStudents activity
Code:
package com.andrew.obu;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
public class ProspectiveStudents extends ListActivity
{
private static final int MENU_ABOUT = 0;
private static final int MENU_CONTACT = 1;
int counter;
Button banner, email, moodle, jupiter, staff, calendar, athletics, news, prosp;
TextView display;
Drawable drawable;
@Override
public boolean onCreateOptionsMenu(android.view.Menu menu)
{
menu.add(0, MENU_ABOUT, 0, "About");
menu.add(0, MENU_CONTACT, 0, "Contact Me");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case MENU_ABOUT:
doSomething();
return true;
case MENU_CONTACT:
doSomethingElse();
return true;
}
return super.onOptionsItemSelected(item);
}
private void doSomethingElse() {
Intent intent = new Intent(getBaseContext(), Contact.class);
startActivity(intent);
}
private void doSomething() {
Intent intent = new Intent(getBaseContext(), About.class);
startActivity(intent);}
/*@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cstudents);*/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] choose = getResources().getStringArray(R.array.pstudents_array);
ListView lv = getListView();
LayoutInflater lf;
View headerView;
lf = this.getLayoutInflater();
headerView = (View)lf.inflate(R.layout.cstudents, null, false);
lv.addHeaderView(headerView, null, false);
lv.setTextFilterEnabled(true);
lv.setBackgroundColor(Color.WHITE);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_content, choose));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent intent;
switch(position) {
default:
case 0 :
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.okbu.edu/admissions/onlineapp.html"));
break;
case 2 :
intent = new Intent(this, Majors.class);
break;
case 3 :
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.okbu.edu/admissions/moreinfo.html"));
break;
case 4 :
intent = new Intent(this, Visitwebview.class);
break;
/*case 5 :
intent = new Intent(this, Getinvolved.class);
break;*/
}
startActivity(intent);
};
}

I recommend you to use ActionBarSherlock library: http://actionbarsherlock.com
Take a look at the samples and it will be easy to do what you ask for. At first, it may take a while to learn how to use this library, but you will not regret it since you will use it several times in the future for sure.
The coolest thing about this library is that it is compatible with older Android versions. I.e. The swipe effect will be available for Ice Cream users while for Froyo users will see two clickable tabs :good:

First of all, you can't swipe between activities. You can only swipe between fragments. Think of the activity as a container which holds your two fragments.
This is an example of a ListFragment:
Code:
public static class TitlesFragment extends ListFragment {
boolean mDualPane;
int mCurCheckPosition = 0;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Populate list with our static array of titles.
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));
// Check to see if we have a frame in which to embed the details
// fragment directly in the containing UI.
View detailsFrame = getActivity().findViewById(R.id.details);
mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
if (savedInstanceState != null) {
// Restore last state for checked position.
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
if (mDualPane) {
// In dual-pane mode, the list view highlights the selected item.
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// Make sure our UI is in the correct state.
showDetails(mCurCheckPosition);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}
/**
* Helper function to show the details of a selected item, either by
* displaying a fragment in-place in the current UI, or starting a
* whole new activity in which it is displayed.
*/
void showDetails(int index) {
mCurCheckPosition = index;
if (mDualPane) {
// We can display everything in-place with fragments, so update
// the list to highlight the selected item and show the data.
getListView().setItemChecked(index, true);
// Check what fragment is currently shown, replace if needed.
DetailsFragment details = (DetailsFragment)
getFragmentManager().findFragmentById(R.id.details);
if (details == null || details.getShownIndex() != index) {
// Make new fragment to show this selection.
details = DetailsFragment.newInstance(index);
// Execute a transaction, replacing any existing fragment
// with this one inside the frame.
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (index == 0) {
ft.replace(R.id.details, details);
} else {
ft.replace(R.id.a_item, details);
}
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else {
// Otherwise we need to launch a new activity to display
// the dialog fragment with selected text.
Intent intent = new Intent();
intent.setClass(getActivity(), DetailsActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
}
}
I can't help you there because I've never worked with lists.
As for the swiping effect, build your project with a minimum SDK of 14 (ICS) and choose swipe-able tabs navigation. The ADT will do the job for you. Later, in order to maintain compatibility, use ABS library as patedit suggested.
Good luck

To implement a ViewPager, just add ViewPager to XML layout, and set a FragmentPageAdapter to it.
You must use support package from Android SDK and FragmentActivity instead of Activitiy.
You can examine source code of API Demos package to know more.

Related

[Q] problem in getting the selected items of checkbox android

how to get list of selected items in the new list and then when click on any item in the new list the app launch,please check out my code
public class AppListAdapter extends BaseAdapter implements OnCheckedChangeListener
{
SparseBooleanArray mCheckStates;
Context context;
private List<ResolveInfo> mApps;
PackageManager pm;
public AppListAdapter(Context context,PackageManager pm,List<ResolveInfo> mApps)
{
this.context=context;
this.pm=pm;
this.mApps=mApps;
mCheckStates = new SparseBooleanArray(mApps.size());
}
@override
public int getCount() {
// TODO Auto-generated method stub
return mApps.size();
}
@override
public ResolveInfo getItem(int index) {
// TODO Auto-generated method stub
return mApps.get(index);
}
@override
public long getItemId(int index) {
// TODO Auto-generated method stub
return index;
}
@override
public View getView(int index, View v, ViewGroup parent)
{
ViewHandler handler;
// LayoutInflater inflater=null;
// ApplicationInfo mApplicationInfo=(ApplicationInfo) appitems.get(index);
if(v==null)
{
LayoutInflater inflater=LayoutInflater.from(context);
v=inflater.inflate(R.layout.mycustom_list,null);
handler=new ViewHandler();
handler.iconImage=(ImageView)v.findViewById(R.id.appsimages);
handler.textlable=(TextView)v.findViewById(R.id.appstitle);
handler.checkbox=(CheckBox)v.findViewById(R.id.appscheckBox);
v.setTag(handler);
}
else
{
handler=(ViewHandler)v.getTag();
}
ResolveInfo info = this.mApps.get(index);
handler.iconImage.setImageDrawable(info.loadIcon(pm));
handler.textlable.setText(info.loadLabel(pm).toString());
handler.checkbox.setTag(index);
handler.checkbox.setChecked(mCheckStates.get(index));
handler.checkbox.setOnCheckedChangeListener(this);
return v;
}
public boolean isChecked(int position) {
return mCheckStates.get(position);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
@override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
class ViewHandler{
TextView textlable;
ImageView iconImage;
CheckBox checkbox;
}
}
package com.example.mylauncher;
import java.util.ArrayList;
import java.util.List;
import android.nfc.Tag;
import android.os.Bundle;
import android.app.Activity;
import android.app.admin.DeviceAdminReceiver;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private ListView mListView ;
String TAG;
AppListAdapter adapter;
List appitem;
List<ResolveInfo> list;
private ArrayList results;
// static final int ACTIVATION_REQUEST =47;
@override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView=(ListView) findViewById(R.id.appslist);
Button button=(Button)findViewById(R.id.save);
button.setOnClickListener(this);
PackageManager pm = this.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
list = pm.queryIntentActivities(intent,PackageManager.PERMISSION_GRANTED);
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
adapter=new AppListAdapter(getApplicationContext(),pm,list);
mListView.setAdapter(adapter);
// mListView.setOnItemClickListener(this);
}
public void onClick(View view)
{
// SparseBooleanArray checked = mListView.getCheckedItemPositions();
// ArrayList<ResolveInfo> selectedItems = new ArrayList<ResolveInfo>();
// for (int i = 0; i < checked.size(); i++) {
// // Item position in adapter
// int position = checked.keyAt(i);
// // Add sport if it is checked i.e.) == TRUE!
// if (checked.valueAt(i))
// selectedItems.add(adapter.getItem(position));
// }
//
// String[] outputStrArr = new String[selectedItems.size()];
//
// for (int i = 0; i < selectedItems.size(); i++) {
// outputStrArr = selectedItems.get(i).loadLabel(getPackageManager()).toString();
// }
//
// Intent intent = new Intent(getApplicationContext(),
// ResultActivity.class);
//
// // Create a bundle object
// Bundle b = new Bundle();
// b.putStringArray("selectedItems", outputStrArr);
//
// // Add the bundle to the intent.
// intent.putExtras(b);
//
// // start the ResultActivity
// startActivity(intent);
//
// Toast.makeText(MainActivity.this, outputStrArr.toString(), 1000).show();
SparseBooleanArray checked = mListView.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++)
{
if(checked.valueAt(i) == true)
{
System.out.println("hello");
Tag tag = (Tag) mListView.getItemAtPosition(checked.keyAt(i));
Log.d("XXXX", i + " hellllllllllllpoo" + tag);
}
}
// Toast.makeText(MainActivity.this, item, 1000).show();
}
}
please help
Does this help? http://www.vogella.com/articles/AndroidListView/article.html#listviewselection
And please put your code into
Code:
tags. It's not readable without it. So nobody will read it. ;)

How to make the buttons in a fragment manipulate integer variables in seperate activi

This is a rudimentary android application that serves as an umpires strike/ball/out counter. There is a settings icon in the action bar of the MainActivity. When this icon is 'clicked on', a new Activity is started consisting of a PreferenceFragment, which consists of a checkboxpreference, and a Fragment that consists of 3 buttons. These buttons reset the stike_count, ball_count and total_outs_count to zero. I have spent a day on this and am having trouble figuring out how to manipulate integer variables in my MainActivity from button clicks in a seperate Activity's Fragment. Please point me in the right direction.
package edu.umkc.baldwin;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "UmpireActivity";
// Constant variables declared/initialized to keep track of values
// across lifecycle states
@SuppressWarnings("unused")
private static final String STRIKES = "0";
@SuppressWarnings("unused")
private static final String BALLS = "0";
@SuppressWarnings("unused")
private static final String OUTS = "0";
TextView strikeCounterTV;
TextView ballCounterTV;
TextView totalOutCounterTV;
private Button strikeCounterButton;
private Button ballCounterButton;
private int strike_count;
private int ball_count;
private int out_count;
private void updateViews(){
strikeCounterTV.setText(String.valueOf(strike_count));
ballCounterTV.setText(String.valueOf(ball_count));
totalOutCounterTV.setText(String.valueOf(out_count));
}
private void displayToast(boolean x){
int messageId = 0;
if (x == true){
messageId = R.string.strike_toast_view;
} else {
messageId = R.string.ball_toast_view;
}
Toast toast = Toast.makeText(MainActivity.this, messageId,
Toast.LENGTH_SHORT);
LinearLayout toastLayout = (LinearLayout) toast.getView();
TextView toastTV = (TextView) toastLayout.getChildAt(0);
toast.setGravity(Gravity.CENTER|Gravity.CENTER, 0, -150);
toastTV.setTextSize(42);
toast.show();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "OnCreate(Bundle) called");
setContentView(R.layout.main_page_layout);
//Declare TextView objects and Button objects
strikeCounterTV = (TextView) findViewById(R.id.strikeCountTextView);
ballCounterTV = (TextView) findViewById(R.id.ballCountTextView);
totalOutCounterTV = (TextView) findViewById(R.id.totalOutsTextViewCounter);
strikeCounterButton = (Button) findViewById(R.id.strikeCountButton);
ballCounterButton = (Button) findViewById(R.id.ballCountButton);
strikeCounterButton.setOnClickListener(new OnClickListener(){
@override
public void onClick(View v) {
if (strike_count < 2){
strike_count++;
updateViews();
} else {
// batter has reached strike limit
displayToast(true);
out_count++;
strike_count = 0;
ball_count = 0;
updateViews();
}
}
});
ballCounterButton.setOnClickListener(new OnClickListener(){
@override
public void onClick(View v) {
if (ball_count < 3){
ball_count++;
updateViews();
} else {
// batter has reached ball limit
displayToast(false);
strike_count = 0;
ball_count = 0;
updateViews();
}
}
});
// Check for screen rotation
if (savedInstanceState == null){
strike_count = 0;
ball_count = 0;
} else {
strike_count = savedInstanceState.getInt("STRIKES");
ball_count = savedInstanceState.getInt("BALLS");
}
// Save 'totalOuts' variable through application exit
SharedPreferences savedObject = getPreferences(Context.MODE_PRIVATE);
out_count = savedObject.getInt(getString(R.string.total_outs_key), 0);
updateViews();
}
@override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.d(TAG, "onSaveInstanceState() called");
savedInstanceState.putInt("STRIKES", strike_count);
savedInstanceState.putInt("BALLS", ball_count);
savedInstanceState.putInt("OUTS", out_count);
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
//Displays actionbar items in app actionbar
getMenuInflater().inflate(R.menu.actionbar_layout, menu);
return super.onCreateOptionsMenu(menu);
}
@override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch (item.getItemId()){
case (R.id.reset_option):
strike_count = 0;
ball_count = 0;
updateViews();
return true;
case (R.id.about_menu_option):
Intent i = new Intent(this, About.class);
startActivity(i);
return true;
case (R.id.settings_menu_option):
Intent j = new Intent(this, SettingsActivity.class);
startActivity(j);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
@override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
@override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
@override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
SharedPreferences out_file = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = out_file.edit();
editor.putInt(getString(R.string.total_outs_key), out_count);
editor.commit();
}
@override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called");
}
}
package edu.umkc.baldwin;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
public class SettingsActivity extends Activity {
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_layout);
FragmentManager ttsFragmentManager = getFragmentManager();
FragmentTransaction ttsFragmentTransaction = ttsFragmentManager.beginTransaction();
EnableTTSPreferenceFragment ttsFragment = new EnableTTSPreferenceFragment();
ttsFragmentTransaction.add(R.id.tts_fragment, ttsFragment);
ttsFragmentTransaction.commit();
FragmentManager resetFragmentManager = getFragmentManager();
FragmentTransaction resetFragmentTransaction = resetFragmentManager.beginTransaction();
ResetFragment resetFragment = new ResetFragment();
resetFragmentTransaction.add(R.id.reset_fragment, resetFragment);
resetFragmentTransaction.commit();
}
}
package edu.umkc.baldwin;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ResetFragment extends Fragment {
@override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View resetFragment = inflater.inflate(R.layout.reset_layout, container, false);
return resetFragment;
}
}
package edu.umkc.baldwin;
import android.os.Bundle;
import android.preference.PreferenceFragment;
public class EnableTTSPreferenceFragment extends PreferenceFragment {
@override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.tts_preference_fragment);
}
@override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
}
To modify anything in your activity from one of its child Fragments you would typically create an interface in the Fragment and have the activity implement that. That interface would either contain one method setting all three vars or multiple ones, one for each variable. To call the methods in the interface call getActivity() and typecast it to the interface.

[Q] Socket code throws NullPointerException in OnsensorChanged

Hi frends im working on my android final year project based on sockets..im using ssynctask to connect socket etc..Everything works fine, since I'm using AsyncTask to create a Socket connection ... the socket works fine in the doInBackground() method, but when I try to send Sensor data from theonSensorChanged() method, I get null pointer exception. I don't know what went wrong. in short Socket returns NULL outside asyncTask Class...can some 1 help me ?..
here is my code
Code:
package com.example.sensorsmart;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener{
private static final int SERVERPORT = 8222;
private static final String SERVER_IP = "192.168.0.101";
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private TextView tv ;
public ServerSocket serverSocket=null;
public Socket socket = null;
public BufferedReader in ;
public BufferedWriter out;
public PrintWriter pw ;
public FileWriter writer=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyTask().execute();
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
mAccelerometer mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer,SensorManager.SENSOR_DELAY_NORMAL);
}
public void onStopClick(View view) {
mSensorManager.unregisterListener(this);}
private class MyTask extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... arg0) {
try {
serverSocket = new ServerSocket(8222);
} catch (IOException e) {
e.printStackTrace();
}
try {
socket=serverSocket.accept();
Log.i("TcpServer", "CONNECTED");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
if(!in.ready())
{
Log.i("TcpServer", "READER IS NOT READY");
}
final String g;
final String c;
String b = null;
Log.i("TcpServer", "GOING");
g=in.readLine();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
String response = e.getCause().toString();
Log.i("TCP",response);
}
return null;
}
}
@Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
pw.write("g"); //NULL POINT EXCEPTION THROWS HERE
}
}
LOGCAT:
Code:
02-06 11:31:54.250: E/AndroidRuntime(4108): FATAL EXCEPTION: main
02-06 11:31:54.250: E/AndroidRuntime(4108): java.lang.NullPointerException
02-06 11:31:54.250: E/AndroidRuntime(4108): at com.example.sensorsmart.MainActivity.onSensorChanged(MainActivity.java:196)
02-06 11:31:54.250: E/AndroidRuntime(4108): at android.hardware.SystemSensorManager$ListenerDelegate$1.handleMessage(SystemSensorManager.java:204)
02-06 11:31:54.250: E/AndroidRuntime(4108): at android.os.Handler.dispatchMessage(Handler.java:99)
02-06 11:31:54.250: E/AndroidRuntime(4108): at android.os.Looper.loop(Looper.java:137)
02-06 11:31:54.250: E/AndroidRuntime(4108): at android.app.ActivityThread.main(ActivityThread.java:4759)
02-06 11:31:54.250: E/AndroidRuntime(4108): at java.lang.reflect.Method.invokeNative(Native Method)
02-06 11:31:54.250: E/AndroidRuntime(4108): at java.lang.reflect.Method.invoke(Method.java:511)
02-06 11:31:54.250: E/AndroidRuntime(4108): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
02-06 11:31:54.250: E/AndroidRuntime(4108): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
02-06 11:31:54.250: E/AndroidRuntime(4108): at dalvik.system.NativeStart.main(Native Method)
you have to set the variable in onpostexecute() and also use
Code:
new MyTask().execute().get()
so you make sure the async task has finished for sure
Can u gv example ?
warlock9_0 said:
you have to set the variable in onpostexecute() and also use
Code:
new mytask().execute().get()
so you make sure the async task has finished for sure
Click to expand...
Click to collapse
frend can u give me an example ?
forget the execute().get() for now, maybe it is not needed
read the documents for asynctask and change your result type from void, to whatever you want to set
for example if you want only the PrintWriter to be set you can do this
Code:
package com.example.sensorsmart;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener{
private static final int SERVERPORT = 8222;
private static final String SERVER_IP = "192.168.0.101";
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private TextView tv ;
public ServerSocket serverSocket=null;
public Socket socket = null;
public BufferedReader in ;
public BufferedWriter out;
public PrintWriter pw ;
public FileWriter writer=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyTask().execute();
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
mAccelerometer mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer,SensorManager.SENSOR_DELAY_NORMAL);
}
public void onStopClick(View view) {
mSensorManager.unregisterListener(this);}
private class MyTask extends AsyncTask<Void, Void, PrintWriter>
{
@Override
protected PrintWriter doInBackground(Void... arg0) {
try {
serverSocket = new ServerSocket(8222);
} catch (IOException e) {
e.printStackTrace();
}
try {
socket=serverSocket.accept();
Log.i("TcpServer", "CONNECTED");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
if(!in.ready())
{
Log.i("TcpServer", "READER IS NOT READY");
}
final String g;
final String c;
String b = null;
Log.i("TcpServer", "GOING");
g=in.readLine();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
String response = e.getCause().toString();
Log.i("TCP",response);
}
return pw;
}
protected void onPostExecute(PrintWriter result) {
pw = result;
}
}
@Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
if(pw!=null) pw.write("g"); //NULL POINT EXCEPTION THROWS HERE
}
}
if you want other variables to be returned too, you can make a custom object as the type of the result
is it possible to pass socket instead mof printwriter?
hi friend thank u for ur reply...is it possible to pass socket in onpostexecute () ?
i tried with below code still socket is null in ONsensor Changed
Code:
private class MyTask extends AsyncTask<Void, Void,Socket>
{
@Override
protected Socket doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
serverSocket = new ServerSocket(8222);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket=serverSocket.accept();
Log.i("TcpServer", "CONNECTED");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
//out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
if(!in.ready())
{
Log.i("TcpServer", "READER IS NOT READY");
}
final String g;
final String c;
String b = null;
Log.i("TcpServer", "GOING");
g=in.readLine();
//Log.i("TcpServer", in.readLine());
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
Log.i("TcpServer", "RECEIVED");
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
String response = e.getCause().toString();
Log.i("TCP",response);
}
return socket;
}
protected void onPostExecute(Socket result) {
socket = result;
}
yes, you can pass the socket like you do
but in the onsensorchanged function you are using the printwriter (pw) you created in the doinbackground function which is null because you haven't passed it to the main thread
so, you either have to make a new object that will pass all the things to the main threat (socket, printwriter, bufferedreader) if you want them all, or pass the printwriter only, or you will initialize them on the post execute function
for example, you can return the socket and then do
Code:
protected void onPostExecute(Socket result) {
socket = result;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
}
still null
here is my entire code..i have done exactly what u said...still socket null in OnsensorChanged()
Code:
package com.example.sensorsmart;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener{
private static final int SERVERPORT = 8222;
private static final String SERVER_IP = "192.168.0.101";
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private TextView tv ;
public ServerSocket serverSocket=null;
public Socket socket = null;
public BufferedReader in ;
public BufferedWriter out;
public PrintWriter pw ;
public FileWriter writer=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyTask().execute();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
public void onStopClick(View view) {
mSensorManager.unregisterListener(this);
}
protected void onResume() {
super.onResume();
}
protected void onStop(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSensorManager.unregisterListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class MyTask extends AsyncTask<Void, Void,Socket>
{
@Override
protected Socket doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
serverSocket = new ServerSocket(8222);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket=serverSocket.accept();
Log.i("TcpServer", "CONNECTED");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
//out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
if(!in.ready())
{
Log.i("TcpServer", "READER IS NOT READY");
}
final String g;
final String c;
String b = null;
Log.i("TcpServer", "GOING");
g=in.readLine();
//Log.i("TcpServer", in.readLine());
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
Log.i("TcpServer", "RECEIVED");
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
String response = e.getCause().toString();
Log.i("TCP",response);
}
return socket;
}
protected void onPostExecute(Socket result) {
socket = result;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
}
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
pw.println("egaga");
}
public void CloseConn() throws IOException //not used
{
pw.flush();
in.close();
socket.close();
serverSocket.close();
}
}
Code:
public class MainActivity extends Activity implements SensorEventListener{
private static final int SERVERPORT = 8222;
private static final String SERVER_IP = "192.168.0.101";
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private TextView tv ;
public ServerSocket serverSocket=null;
public Socket socket = null;
public BufferedReader in ;
public BufferedWriter out;
public PrintWriter pw ;
public FileWriter writer=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyTask().execute();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
public void onStopClick(View view) {
mSensorManager.unregisterListener(this);
}
protected void onResume() {
super.onResume();
}
protected void onStop(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSensorManager.unregisterListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class MyTask extends AsyncTask<Void, Void,AllInOne>
{
@Override
protected AllInOne doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
serverSocket = new ServerSocket(8222);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket=serverSocket.accept();
Log.i("TcpServer", "CONNECTED");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
//out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
if(!in.ready())
{
Log.i("TcpServer", "READER IS NOT READY");
}
final String g;
final String c;
String b = null;
Log.i("TcpServer", "GOING");
g=in.readLine();
//Log.i("TcpServer", in.readLine());
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
Log.i("TcpServer", "RECEIVED");
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
String response = e.getCause().toString();
Log.i("TCP",response);
}
return new AllInOne(socket,in,pw);
}
protected void onPostExecute(AllInOne result) {
socket = result.so;
in = result.re;
pw = result.pr;
}
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
if(pw!=null) pw.println("egaga");
else Log.e("PrintWriter", null);
}
public void CloseConn() throws IOException //not used
{
pw.flush();
in.close();
socket.close();
serverSocket.close();
}
private class AllInOne {
public Socket so;
public BufferedReader re;
public PrintWriter pr;
public AllInOne(Socket s, BufferedReader r, PrintWriter p ){
this.so = s;
this.re = r;
this.pr = p;
}
}
}
try this
since you are initializing in and pw inside the doinbackground, you have to pass them to the main thread
so i added another class to hold all these and i pass them on result
finally you also have to check in the onsensorchanged if the pw is null because the asynctask may have not finished yet when this is called
null
async task not completed because of socket not closed?
Thank u
bro..some how i managed to get it work..thanks a lot for ur time..and nice to meet u..

Face Detection in Background Service

I am making an android app which requires to capture image using front camera using android service. Also we need to detect face in the image so obtained. But when calling the detectfaces() function, the app unfortuantely stops. I am posting the code for it here. Please help me find out where i am going wrong.
here is my code..!!!!
package com.android.camerarecorder;
import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class CameraRecorder extends Activity implements SurfaceHolder.Callback {
static final int MAX_FACES = 5;
//private static final String TAG = "Recorder";
public static SurfaceView mSurfaceView;
public static SurfaceHolder mSurfaceHolder;
public static Camera mCamera;
public static boolean mPreviewRunning;
public static TextView jpgName;
public static ImageView jpgView;
public static ImageView imageView;
/** Called when the activity is first created. */
@SuppressWarnings("deprecation")
 @override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView)findViewById(R.id.jpgview);
mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
jpgName = (TextView)findViewById(R.id.jpgname);
jpgView = (ImageView)findViewById(R.id.jpgview);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Button btnStart = (Button) findViewById(R.id.StartService);
btnStart.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(CameraRecorder.this,RecorderService.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(intent);
//finish();
}
});
Button btnStop = (Button) findViewById(R.id.StopService);
btnStop.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
stopService(new Intent(CameraRecorder.this, RecorderService.class));
}
});
}
@override
public void surfaceCreated(SurfaceHolder holder) {
}
@override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
The above code was the activity where the service is called. The service is as follows:
package com.android.camerarecorder;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.iutputStream;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.media.AudioManager;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class RecorderService extends Service
{
private SurfaceHolder sHolder;
private TextView mjpgname;
private ImageView mjpgview;
private ImageView mimageview;
Bitmap bm;
Bundle bundle = new Bundle();
String filename;
private int cameraId = 0;
//a variable to control the camera
private Camera mCamera;
final static String DEBUG_TAG = "Test";
Uri imageFileUri;
//the camera parameters
private Parameters parameters;
/** Called when the activity is first created. */
@override
public void onCreate()
{
super.onCreate();
sHolder=CameraRecorder.mSurfaceHolder;
mCamera = CameraRecorder.mCamera;
mjpgname= CameraRecorder.jpgName;
mjpgview = CameraRecorder.jpgView;
mimageview=CameraRecorder.imageView;
}
@SuppressWarnings("deprecation")
 @override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
// do we have a camera?
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG).show();
} else {
cameraId = findFrontFacingCamera();
if (cameraId < 0) {
Toast.makeText(this, "No front facing camera found.",Toast.LENGTH_LONG).show();
} else {
mCamera = Camera.open(cameraId);
}
}
//mCamera = Camera.open();
SurfaceView sv = new SurfaceView(getApplicationContext());
sv=CameraRecorder.mSurfaceView ;
try {
mCamera.setPreviewDisplay(sHolder);
parameters = mCamera.getParameters();
//set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
mCamera.takePicture(null, null, mCall);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Get a surface
sHolder = sv.getHolder();
//tells Android that this surface will have its data constantly replaced
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
private int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
Log.d(DEBUG_TAG, "Camera found");
cameraId = i;
break;
}
}
return cameraId;
// TODO Auto-generated method stub
}
Camera.PictureCallback mCall = new Camera.PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
//decode the data obtained by the camera into a Bitmap
// FileOutputStream outStream = null;
try{
imageFileUri = getContentResolver().insert(
Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS = getContentResolver().openOutputStream(
imageFileUri);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
filename = getRealPathFromURI(imageFileUri);
File imgFile = new File(filename);
if(imgFile.exists())
{
bm = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
mjpgview.setImageBitmap(bm);
}
detectFaces();
// mjpgname.setText("success");
/*
Intent i = new Intent(RecorderService.this, FaceDetect.class);
//Add your data to bundle
bundle.putString("Filepath", filename) ;
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);*/
/* final File images = Environment.getExternalStorageDirectory();
String filePath = "magic";
String final_path = images+"/"+filePath;
outStream = new FileOutputStream(final_path);
outStream.write(data);
outStream.close();*/
} catch (FileNotFoundException e){
Log.d("CAMERA", e.getMessage());
} catch (IOException e){
Log.d("CAMERA", e.getMessage());
}
}
};
private void detectFaces() {
if(null != bm){
int width = bm.getWidth();
int height = bm.getHeight();
FaceDetector detector = new FaceDetector(width, height,CameraRecorder.MAX_FACES);
Face[] faces = new Face[CameraRecorder.MAX_FACES];
Bitmap bitmap565 = Bitmap.createBitmap(width, height, Config.RGB_565);
Paint ditherPaint = new Paint();
Paint drawPaint = new Paint();
ditherPaint.setDither(true);
drawPaint.setColor(Color.RED);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeWidth(2);
Canvas canvas = new Canvas();
canvas.setBitmap(bitmap565);
//canvas.setBitmap(cameraBitmap);
canvas.drawBitmap(bm, 0, 0, ditherPaint);
int facesFound = detector.findFaces(bitmap565, faces);
// int facesFound = detector.findFaces(cameraBitmap, faces);
PointF midPoint = new PointF();
float eyeDistance = 0.0f;
float confidence = 0.0f;
Log.i("FaceDetector", "Number of faces found: " + facesFound);
if(facesFound > 0)
{
for(int index=0; index<facesFound; ++index){
faces[index].getMidPoint(midPoint);
eyeDistance = faces[index].eyesDistance();
confidence = faces[index].confidence();
Log.i("FaceDetector",
"Confidence: " + confidence +
", Eye distance: " + eyeDistance +
", Mid Point: (" + midPoint.x + ", " + midPoint.y + ")");
canvas.drawRect((int)midPoint.x - eyeDistance ,
(int)midPoint.y - eyeDistance ,
(int)midPoint.x + eyeDistance,
(int)midPoint.y + eyeDistance, drawPaint);
}
}
// Camera_timer.key = eyeDistance;
// tv.setText(eyeDistance+"");
String filepath = Environment.getExternalStorageDirectory()
+ "/facedetect" +System.currentTimeMillis() + ".jpg";
try {
FileOutputStream fos = new FileOutputStream(filepath);
bitmap565.compress(CompressFormat.JPEG, 90, fos);
// cameraBitmap.compress(CompressFormat.JPEG, 90, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mimageview.setImageBitmap(bitmap565);
// imageView.setImageBitmap(cameraBitmap);
}
}
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
//This method was deprecated in API level 11
//Cursor cursor = managedQuery(contentUri, proj, null, null, null);
CursorLoader cursorLoader = new CursorLoader((Context) mCall,contentUri, proj, null, null,null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
// TODO Auto-generated method stub
}
@override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}

My watch face is acting weird when selected.

I'm having some trouble. I just added watch view stub to my code so I can support both square and round devices. Everything still works but now when the watch face is selected it takes a few min to show the text. The background shows up right on both dim and awake screens right away. Its just the text that takes a while to appear.
It only does this when first selecting my watch face.
Am I doing something wrong?
Code:
import android.content.*;
import android.graphics.*;
import android.os.*;
import android.widget.*;
import java.text.*;
import java.util.*;
import android.view.*;
import android.support.wearable.view.WatchViewStub;
public class WearableActivity extends WatchFaceActivity
{
private final static IntentFilter intentFilter;
static {
intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_TIME_TICK);
intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
}
TextView time, battery, watchdate, weekday, watchface, phonebattery, time2, watchdate2;
ImageView image, image_dim;
private final String TIME_FORMAT_DISPLAYED = "h\nmm";
private final String DATE_FORMAT_DISPLAYED = "cccc\nMMM\nd\nyyyy";
private final String DAY_FORMAT_DISPLAYED = "cccc";
private final String TIME2_FORMAT_DISPLAYED = "h:mm a";
private final String DATE2_FORMAT_DISPLAYED = "MMM d, yyyy";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
@Override
public void onLayoutInflated(WatchViewStub stub){
time = (TextView) findViewById(R.id.watch_time);
battery = (TextView) findViewById(R.id.watch_battery);
watchdate = (TextView) findViewById(R.id.watch_date);
time2 = (TextView) findViewById(R.id.watch_time2);
watchdate2 = (TextView) findViewById(R.id.watch_date2);
weekday = (TextView) findViewById(R.id.weekday);
image = (ImageView) findViewById(R.id.backimage);
image_dim = (ImageView) findViewById(R.id.image_dim);
phonebattery = (TextView) findViewById(R.id.phone_battery);
registerReceiver(mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
registerReceiver(mTimeInfoReceiver, intentFilter);
}
});}
@Override
public void onScreenAwake()
{
RelativeLayout rl = (RelativeLayout)findViewById(R.id.watchface);
rl.setBackgroundColor(Color.BLACK);
image.setVisibility(View.VISIBLE);
weekday.setVisibility(View.GONE);
time.setVisibility(View.VISIBLE);
watchdate.setVisibility(View.VISIBLE);
time2.setVisibility(View.GONE);
watchdate2.setVisibility(View.GONE);
image_dim.setVisibility(View.GONE);
image_dim.setRotation(75);
time.setTextColor(Color.CYAN);
battery.setTextColor(Color.CYAN);
watchdate.setTextColor(Color.CYAN);
battery.setVisibility(View.VISIBLE);
}
@Override
public void onScreenDim()
{
RelativeLayout rl = (RelativeLayout)findViewById(R.id.watchface);
rl.setBackgroundColor(Color.BLACK);
image.setVisibility(View.GONE);
weekday.setVisibility(View.VISIBLE);
time.setVisibility(View.GONE);
watchdate.setVisibility(View.GONE);
time2.setVisibility(View.VISIBLE);
watchdate2.setVisibility(View.VISIBLE);
image_dim.setVisibility(View.VISIBLE);
time2.setTextColor(Color.GRAY);
watchdate2.setTextColor(Color.GRAY);
phonebattery.setTextColor(Color.BLACK);
weekday.setTextColor(Color.GRAY);
battery.setVisibility(View.GONE);
}
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent intent) {
battery.setText(String.valueOf(intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0) + "%"));
}
};
private BroadcastReceiver mTimeInfoReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent intent) {
Date date = new Date();
time.setText(new SimpleDateFormat(TIME_FORMAT_DISPLAYED).format(date));
watchdate.setText(new SimpleDateFormat(DATE_FORMAT_DISPLAYED).format(date));
weekday.setText(new SimpleDateFormat(DAY_FORMAT_DISPLAYED).format(date));
time2.setText(new SimpleDateFormat(TIME2_FORMAT_DISPLAYED).format(date));
watchdate2.setText(new SimpleDateFormat(DATE2_FORMAT_DISPLAYED).format(date));
}
};
@Override
public void onWatchFaceRemoved() {}
}
Sent from my LG-LS995 using XDA Free mobile app

Categories

Resources