[Q] remove proximityAlert after notification - Java for Android App Development

what I am trying to do is have a proximity alert service which triggers a notification ONLY ONCE when you step inside the radius (without stopping the service). my code triggers notifications every time you step inside the radius and every time you step outside the radius. i've been trying with booleans and with removeProximityAlert, but no success. can anyone help?
Code:
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class ProximityService extends Service {
private String PROX_ALERT_INTENT = "com.example.proximityalert";
private BroadcastReceiver locationReminderReceiver;
private LocationManager locationManager;
private PendingIntent proximityIntent;
[user=439709]@override[/user]
public void onCreate() {
locationReminderReceiver = new ProximityIntentReceiver();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
double lat = 55.586568;
double lng = 13.0459;
float radius = 1000;
long expiration = -1;
IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT);
registerReceiver(locationReminderReceiver, filter);
Intent intent = new Intent(PROX_ALERT_INTENT);
intent.putExtra("alert", "Test Zone");
proximityIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
locationManager.addProximityAlert(lat, lng, radius, expiration, proximityIntent);
}
[user=439709]@override[/user]
public void onDestroy() {
Toast.makeText(this, "Proximity Service Stopped", Toast.LENGTH_LONG).show();
try {
unregisterReceiver(locationReminderReceiver);
} catch (IllegalArgumentException e) {
Log.d("receiver", e.toString());
}
}
[user=439709]@override[/user]
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Proximity Service Started", Toast.LENGTH_LONG).show();
}
[user=439709]@override[/user]
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public class ProximityIntentReceiver extends BroadcastReceiver {
private static final int NOTIFICATION_ID = 1000;
[user=1299008]@supp[/user]ressWarnings("deprecation")
[user=439709]@override[/user]
public void onReceive(Context arg0, Intent arg1) {
String place = arg1.getExtras().getString("alert");
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent pendingIntent = PendingIntent.getActivity(arg0, 0, arg1, 0);
Notification notification = createNotification();
notification.setLatestEventInfo(arg0, "Entering Proximity!", "You are approaching a " + place + " marker.", pendingIntent);
notificationManager.notify(NOTIFICATION_ID, notification);
locationManager.removeProximityAlert(proximityIntent);
}
private Notification createNotification() {
Notification notification = new Notification();
notification.icon = R.drawable.ic_launcher;
notification.when = System.currentTimeMillis();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_SOUND;
return notification;
}
}
}

Related

Help with ViewPager and Fragments

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.

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.

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;
}
}

Updating tabs to new tab fragments

Hi all,
I had an app that was working about 3 years ago that I decided to update for the latest android sdk.I was using tabs but have decided to update to tab fragments with swipe.The problem I'm having is how to lay out the code.I have updated my app but have a few errors.Specifically the Book Now tab usually has a book now form so people can fill it out and upon clicking submit it sms's it to me.Below is the code for BookNowFragmnet.java.
I should mention that the tab and swipe part works flawlessly.I dont have a logcat because it wont build without removing the code
PHP:
package com.deano.dfw;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class BookNowFragment extends Fragment implements OnClickListener {
Button buttonSubmit;
EditText edittextPhone;
EditText editTextProblem;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_booknow, container, false);
buttonSubmit = (Button) rootView.findViewById(R.id.buttonSubmit);
edittextPhone = (EditText) rootView.findViewById(R.id.edittextPhone);
editTextProblem = (EditText) rootView.findViewById(R.id.editTextProblem);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String phoneNo = edittextPhone.getText().toString();
String message = editTextProblem.getText().toString();
if (phoneNo.length()>0 && message.length()>0)
sendSMS(phoneNo, message);
else
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
// ---sends a SMS message to another device---
private void sendSMS(String phoneNumber, String message) {
/*
* PendingIntent pi = PendingIntent.getActivity(this, 0, new
* Intent(this, test.class), 0); SmsManager sms =
* SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null,
* message, pi, null);
*/
String SENT = "SMS_SENT";
// String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
SENT), 0);
/*
* PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new
* Intent(DELIVERED), 0);
*/
// ---when the SMS has been sent---
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
The problem areas are as follows;
1. getBaseContext has the error "The method getBaseContext is undefined for the type new View.OnClickListener"
PHP:
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
2. getBroadcast has the error "The method getBroadcast(Context, int, Intent, int) in the type PendingIntent is not applicable for the arguments (BookNowFragment, int, Intent, int)"
PHP:
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
3.registerReceiver has the error "The method registerReceiver(new BroadcastReceiver(){}, IntentFilter) is undefined for the type BookNowFragment"
PHP:
// ---when the SMS has been sent---
registerReceiver(new BroadcastReceiver() {
4. all of the getBaseContext under the following have the error "The method getBaseContext() is undefined for the type new BroadcastReceiver"
PHP:
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
any help would be appreciated I have searched for the last two days trying different things.
dfwcomputer said:
1. getBaseContext has the error "The method getBaseContext is undefined for the type new View.OnClickListener"
PHP:
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
Click to expand...
Click to collapse
So you are asking for the method "getBaseContext" within an onClickListener... it does not have a method called that... like it's telling you it's undefined
It would probably be a better idea to use application context either by direct use of getApplicationContext or by a "final" reference maybe...
dfwcomputer said:
2. getBroadcast has the error "The method getBroadcast(Context, int, Intent, int) in the type PendingIntent is not applicable for the arguments (BookNowFragment, int, Intent, int)"
PHP:
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
Click to expand...
Click to collapse
BookNowFragment is not extended from the base type of Context that is expected in the arguments.
dfwcomputer said:
3.registerReceiver has the error "The method registerReceiver(new BroadcastReceiver(){}, IntentFilter) is undefined for the type BookNowFragment"
PHP:
// ---when the SMS has been sent---
registerReceiver(new BroadcastReceiver() {
Click to expand...
Click to collapse
dfwcomputer said:
4. all of the getBaseContext under the following have the error "The method getBaseContext() is undefined for the type new BroadcastReceiver"
PHP:
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
any help would be appreciated I have searched for the last two days trying different things.
Click to expand...
Click to collapse
Actually the last to are just repeats of the previous really... I'm guessing here but it seems you may have skipped ahead of where you should be in a learning sense.. cause it seems to be like your running without being knowing how to jog kinda thing. Not attempting to be condescending, just I'm a trainer and always attempt to point this stuff out when I see it
Maybe go back and do some of the basics again, and include fragments etc
thanks, Im well aware i'm running before im born but this is the only app I intend to write as it's specifically for my business.
dfwcomputer said:
thanks, Im well aware i'm running before im born but this is the only app I intend to write as it's specifically for my business.
Click to expand...
Click to collapse
hmmm, well if thats all thats wrong with it, all I could offer is for you to send me the packaged src+res and I will have a look... if it takes less than 20 min to fix and get running I have no problem fixing it for you. If it doesn't and maybe takes longer then I may have to leave it. Should be quick though, up to you
But with the info I gave you should be able to fix those 4 issues...if not hit me up on hangouts and will talk you though it
thanks m8.Ill play around today but if I cant figure it out I might get you to have a look if time permits.I develop in eclipse.Is it a matter of just zipping up the project folder?
dfwcomputer said:
thanks m8.Ill play around today but if I cant figure it out I might get you to have a look if time permits.I develop in eclipse.Is it a matter of just zipping up the project folder?
Click to expand...
Click to collapse
Yeah, just zip the project.
But like I say just get a reference to the activity to use as the "context" part of the argument, either where you need it or as a final reference or member variable
so getActivity()
or memberVar
Context mContext = null;
(in onCreate) mContext = getActivity();
or as final
final Context c = getActivity();
deanwray said:
Yeah, just zip the project.
But like I say just get a reference to the activity to use as the "context" part of the argument, either where you need it or as a final reference or member variable
so getActivity()
or memberVar
Context mContext = null;
(in onCreate) mContext = getActivity();
or as final
final Context c = getActivity();
Click to expand...
Click to collapse
lol now I have less faith ill be fixing it..... Ill let you know thanks again
sent you a private message m8, because there is some personal info in the app
dfwcomputer said:
sent you a private message m8, because there is some personal info in the app
Click to expand...
Click to collapse
fixed and sent private msg with class
Thanks again, I apreciate it.I have changed the personal info and posted the working code here incase someone else has a similar issue.
PHP:
package com.deano.dfw;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class BookNowFragment extends Fragment implements OnClickListener {
Button buttonSubmit;
EditText edittextPhone;
EditText editTextProblem;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_booknow, container, false);
buttonSubmit = (Button) rootView.findViewById(R.id.buttonSubmit);
//edittextPhone = (EditText) rootView.findViewById(R.id.edittextPhone);
//editTextProblem = (EditText) rootView.findViewById(R.id.editTextProblem);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String strPhoneNo = "0000000000";
TextView txtName = (TextView) rootView.findViewById(R.id.edittextName);
TextView txtPhone = (TextView) rootView.findViewById(R.id.edittextPhone);
TextView txtProblem = (TextView) rootView.findViewById(R.id.editTextProblem);
String strName = "Name: " + txtName.getText().toString();
String strPhone = "Phone: " + txtPhone.getText().toString();
String strProblem = "Problem: "
+ txtProblem.getText().toString();
String strMessage = strName + "\n" + strPhone + "\n"
+ strProblem;
BookNowSMS(strPhoneNo, strMessage);
}
});
return rootView;
}
// ---sends a SMS message to another device---
private void BookNowSMS(String phoneNumber, String message) {
/*
* PendingIntent pi = PendingIntent.getActivity(this, 0, new
* Intent(this, test.class), 0); SmsManager sms =
* SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null,
* message, pi, null);
*/
String SENT = "SMS_SENT";
// String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(getActivity(), 0, new Intent(
SENT), 0);
/*
* PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new
* Intent(DELIVERED), 0);
*/
// ---when the SMS has been sent---
getActivity().registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getActivity(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getActivity(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getActivity(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getActivity(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getActivity(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
I forgot the date and time picker arrrrrrrgh
I've added the following 2 classes which have no errors and seem to function fine.
DatePickerFragment.java
PHP:
package com.test.dfw;
import java.util.Calendar;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
import android.widget.TextView;
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
TextView txtDate;
public DatePickerFragment(TextView txtDate) {
super();
this.txtDate = txtDate;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
txtDate.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
}
TimePickerFragment.java
PHP:
package com.test.dfw;
import java.util.Calendar;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TextView;
import android.widget.TimePicker;
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener{
TextView txtTime;
public TimePickerFragment(TextView txtTime) {
super();
this.txtTime = txtTime;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
txtTime.setText(hourOfDay+":"+minute);
}
}
I then updated BookNowFragment.java
PHP:
package com.test.dfw;
import java.util.Calendar;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class BookNowFragment extends Fragment implements OnClickListener {
Button buttonSubmit;
EditText edittextPhone;
EditText editTextProblem;
Button btnChangeDate,btnChangeTime;
TextView txtDisplayDate,txtDisplayTime;
DatePicker datePicker;
TimePicker timePicker;
private int year;
private int month;
private int day;
private int hour;
private int minute;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_booknow,
container, false);
showCurrentDateOnView();
showCurrentTimeOnView();
buttonSubmit = (Button) rootView.findViewById(R.id.buttonSubmit);
// edittextPhone = (EditText) rootView.findViewById(R.id.edittextPhone);
// editTextProblem = (EditText)
// rootView.findViewById(R.id.editTextProblem);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String strPhoneNo = "00000000";
TextView txtName = (TextView) rootView
.findViewById(R.id.edittextName);
TextView txtPhone = (TextView) rootView
.findViewById(R.id.edittextPhone);
//TextView txtDate = (TextView) rootView.findViewById(R.id.date);
TextView txtProblem = (TextView) rootView
.findViewById(R.id.editTextProblem);
String strName = "Name: " + txtName.getText().toString();
String strPhone = "Phone: " + txtPhone.getText().toString();
//String strDate = "Date: " + txtDate.getText().toString();
String strProblem = "Problem: "
+ txtProblem.getText().toString();
String strMessage = strName + "\n" + strPhone + "\n" + strProblem;
BookNowSMS(strPhoneNo, strMessage);
}
});
return rootView;
}
// ---sends a SMS message to another device---
private void BookNowSMS(String phoneNumber, String message) {
/*
* PendingIntent pi = PendingIntent.getActivity(this, 0, new
* Intent(this, test.class), 0); SmsManager sms =
* SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null,
* message, pi, null);
*/
String SENT = "SMS_SENT";
// String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(getActivity(), 0,
new Intent(SENT), 0);
/*
* PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new
* Intent(DELIVERED), 0);
*/
// ---when the SMS has been sent---
getActivity().registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getActivity(), "Message Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getActivity(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getActivity(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getActivity(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getActivity(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
// display current date
public void showCurrentDateOnView() {
txtDisplayDate = (TextView) findViewById(R.id.txtDate);
datePicker = (DatePicker) findViewById(R.id.datePicker1);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
txtDisplayDate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
// set current date into datepicker
datePicker.init(year, month, day, null);
}
// display current time
public void showCurrentTimeOnView() {
txtDisplayTime = (TextView) findViewById(R.id.txtTime);
timePicker = (TimePicker) findViewById(R.id.timePicker1);
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
// set current time into textview
txtDisplayTime.setText(
new StringBuilder().append(hour)
.append(":").append(minute));
// set current time into timepicker
timePicker.setCurrentHour(hour);
timePicker.setCurrentMinute(minute);
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment(txtDisplayDate);
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment(txtDisplayTime);
newFragment.show(getSupportFragmentManager(), "timePicker");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
The problem areas are all under BookNowFragment.java;
1. Under "showCurrentDateOnView" the both findViewById says undefined for the type.I have tried adding rootView but didnt work.
2. Under "showCurrentTimeOnView" both findViewById says undefined for the type.I have tried adding rootView but didnt work.
3. under "showDatePickerDialog" and "showTimePickerDialog" both the getSupportFragmentManager methods show the error "The method getSupportFragmentManager() is undefined for the type BookNowFragment"
4. I also have errors with "onCreateOptionsMenu".I worked out some of them by adding getActivity (see new code below) but it still shows the error "The method onCreateOptionsMenu(Menu) of type BookNowFragment must override or implement a supertype method"
PHP:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getActivity().getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Think there simple issues although I'm simple as well so I could be understating it.

[Q] How to pass image from one intent to another

Hi friends,
Here is my code for displaying details and images from MySQL database,All i want to do is pass the detail with image to other inner page through intent.Please help me im new in android.
Activity 1
Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("NewApi") public class News_events extends Fragment {
private String jsonResult;
private String url = "<URL PHP FILES>";
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
ImageView img;
Bitmap bitmap;
ProgressDialog pDialog;
// alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Internet detector
ConnectionDetector cd;
InputStream is=null;
String result=null;
String line=null;
int code;
public News_events(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
pDialog = new ProgressDialog(getActivity());
View rootView = inflater.inflate(R.layout.fragment_news_events, container, false);
cd = new ConnectionDetector(rootView.getContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(getActivity(),
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
//return.rootView;
return rootView;
}
accessWebService();
return rootView;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
@Override
protected void onPostExecute(String result) {
display();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void display() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news_details");
LinearLayout MainLL= (LinearLayout)getActivity().findViewById(R.id.newslayout);
//LinearLayout headLN=(LinearLayout)findViewById(R.id.headsection);
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
final String head = jsonChildNode.optString("title");
final String details = jsonChildNode.optString("text");
final String date = jsonChildNode.optString("date");
final String image = jsonChildNode.optString("img");
//final String time = jsonChildNode.optString("time");
//img = new ImageView(this.getActivity());
//new LoadImage().execute("<URL IMAGE FOLDER>"+image);
img = new ImageView(this.getActivity());
LoadImage ldimg=new LoadImage();
ldimg.setImage(img);
ldimg.execute("<URL IMAGE FOLDER>"+image);
TextView headln = new TextView(this.getActivity());
headln.setText(head); // News Headlines
headln.setTextSize(16);
headln.setTextColor(Color.BLACK);
headln.setGravity(Gravity.CENTER);
headln.setBackgroundColor(Color.parseColor("#ffcd14"));
// headln.setBackgroundResource(R.drawable.menubg);
headln.setPadding(0, 20, 0, 0);
// headln.setHeight(50);
headln.setClickable(true);
TextView dateln = new TextView(this.getActivity());
dateln.setText(date); // News Headlines
dateln.setTextSize(12);
dateln.setTextColor(Color.BLACK);
dateln.setGravity(Gravity.RIGHT);
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
dateln.setBackgroundColor(0x00000000);
dateln.setPadding(0, 0, 10, 10);
dateln.setWidth(100);
dateln.setClickable(true);
View sep=new View(this.getActivity());
sep.setBackgroundColor(Color.parseColor("#252525"));
sep.setMinimumHeight(10);
TextView detailsln = new TextView(this.getActivity());
detailsln.setText(details); // News Details
detailsln.setTextSize(12);
detailsln.setTextColor(Color.BLACK);
detailsln.setGravity(Gravity.CENTER);
detailsln.setPadding(10, 10, 10, 10);
int width = LayoutParams.WRAP_CONTENT;
int height = 200;
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
img.setLayoutParams(parms);
parms.gravity = Gravity.CENTER;
img.setPaddingRelative (15, 15, 15, 15);
MainLL.addView(headln);
MainLL.addView(dateln);
// MainLL.addView(photo);
MainLL.addView(img);
MainLL.addView(detailsln);
MainLL.addView(sep);
img.setClickable(true);
headln.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), head, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("img",img.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
dateln.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("img",img.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
img.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("img",img.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
}
} catch (JSONException e) {
Toast.makeText(getActivity().getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
public void setImage(ImageView img ){
this.img=img;
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).openStream());
}
catch (Exception e) { e.printStackTrace(); }
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
pDialog.dismiss();
}
pDialog.dismiss();
}
}
public static boolean isInternetReachable()
{
try {
//make a URL to a known source
URL url = new URL("google");
//open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
//trying to retrieve data from the source. If there
//is no connection, this line will fail
Object objData = urlConnect.getContent();
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
}
catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}
Activity 2
Code:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class InnerNewsAndEvents extends Activity {
ProgressDialog pDialog;
ProgressDialog dialog = null;
Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inner_news_and_events);
TextView title=(TextView)findViewById(R.id.tvtitle);
TextView details=(TextView)findViewById(R.id.tvdetails);
ImageView img=(ImageView)findViewById(R.id.imgpic);
Intent intent = getIntent();
String strhead = intent.getStringExtra("head");
String strdetails = intent.getStringExtra("details");
String strdate = intent.getStringExtra("date");
String strimg = intent.getStringExtra("img");
title.setText(strhead);
details.setText(strdetails);
}
}
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class InnerNewsAndEvents extends Activity {
ProgressDialog pDialog;
ProgressDialog dialog = null;
Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inner_news_and_events);
TextView title=(TextView)findViewById(R.id.tvtitle);
TextView details=(TextView)findViewById(R.id.tvdetails);
ImageView img=(ImageView)findViewById(R.id.imgpic);
Intent intent = getIntent();
String strhead = intent.getStringExtra("head");
String strdetails = intent.getStringExtra("details");
String strdate = intent.getStringExtra("date");
String strimg = intent.getStringExtra("img");
title.setText(strhead);
details.setText(strdetails);
}
}

Categories

Resources