Search Results

Search found 1372 results on 55 pages for 'intent'.

Page 9/55 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Need help with android.os.Build.VERSION.SDK_INT and SharedPreferences

    - by Fenderf4i
    I have a main activity where I call VersionSettings vs = new VersionSettings(this); if (vs.firstRun2()) vs.versionCheckbox(); What I'm trying to do is set a checkbox (checkboxVideoType) to an unchecked state if the Android version is 1.6-2.1 I only want to do this the very first time the app is ever run, it never needs to run again. I think I'm running into the problem when the main activity calls versionCheckbox(), I get a force close if it attempts to run the code inside that is going to set the checkbox to false. I'm very new to programming and would really appreciate some help with this. I think I'm close, but need a push. Thanks in advance! Main Activity import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.ImageView; public class Nasatv extends Activity implements OnClickListener { boolean checkboxIsChecked; SharedPreferences nasaTV_Prefs; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.main); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title); nasaTV_Prefs = getSharedPreferences("nasaTV_Prefs", 0); ChangeLog cl = new ChangeLog(this); if (cl.firstRun()) cl.getLogDialog().show(); VersionSettings vs = new VersionSettings(this); if (vs.firstRun2()) vs.versionCheckbox(); Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(this); Button button2 = (Button) findViewById(R.id.button2); button2.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(Nasatv.this, LaunchCalendar.class); startActivity(i); } }); Button button3 = (Button) findViewById(R.id.button3); button3.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(Nasatv.this, PhotoInfo.class); startActivity(i); } }); CheckConnectivity check = new CheckConnectivity(); Boolean conn = check.checkNow(this.getApplicationContext()); if(conn == true){ ImageView updateImage = (ImageView) findViewById(R.id.updateImage); ImageDownloader downloader = new ImageDownloader(updateImage); downloader.execute("http://www.url.com/trl/ubox.jpg"); } else { ImageView updateImage = (ImageView) findViewById(R.id.updateImage); updateImage.setImageResource(R.drawable.uboxerror); } } public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options_menu, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.setting_title: Intent settingsActivity =new Intent(getBaseContext(), Settings.class); startActivity(settingsActivity); return true; case R.id.photo_archive: Intent archive = new Intent(Nasatv.this, PhotoArchive.class); startActivity(archive); return true; case R.id.n_web: Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.nasa.gov/")); startActivity(intent); return true; case R.id.exit_title: finish(); return true; default: return super.onOptionsItemSelected(item); } } public void onResume() { super.onResume(); checkboxIsChecked = nasaTV_Prefs.getBoolean("checkboxVideoType", true); } @Override public void onClick(View v) { if (checkboxIsChecked) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.nasa.gov/multimedia/nasatv/nasatv_android_flash.html")); startActivity(intent); } else { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("rtsp://nasadln.qt.llnwd.net/nasa101.sdp")); startActivity(intent); } } } One-time run class import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import android.widget.CheckBox; public class VersionSettings { private final Context context; private String notRun, hasRun; private SharedPreferences run; private CheckBox checkboxVideoType; private SharedPreferences nasaTV_Prefs; private static final String HAS_RUN = "PREFS_HAS_RUN"; int currentapiVersion = android.os.Build.VERSION.SDK_INT; /** * Constructor * * Retrieves whether the app has been run or not and saves to * SharedPreferences */ public VersionSettings(Context context) { this.context = context; this.run = PreferenceManager.getDefaultSharedPreferences(context); // get run/not run string number, which is "1" this.notRun = run.getString(HAS_RUN, ""); Log.d(TAG, "notRun: " + notRun); this.hasRun = context.getResources().getString(R.string.has_run_string); Log.d(TAG, "hasRun: " + hasRun); // save new number to preferences, which will be the same number, // so this is run only the very first time the app is run SharedPreferences.Editor editor = run.edit(); editor.putString(HAS_RUN, hasRun); editor.commit(); } /** * @return true if this version of your app is started for the first * time */ public boolean firstRun2() { return ! notRun.equals(hasRun); } /** * @return Change the checkboxVideoType to "unchecked" (false) * */ public void versionCheckbox() { // this.context = context; if (currentapiVersion < android.os.Build.VERSION_CODES.FROYO){ this.nasaTV_Prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = nasaTV_Prefs.edit(); editor.putBoolean("checkboxVideoType", false); editor.commit(); } } private static final String TAG = "VersionSettings"; } Preferences Activity import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; public class Settings extends Activity implements OnCheckedChangeListener { private CheckBox checkboxVideoType; private SharedPreferences nasaTV_Prefs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.preferences); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title); checkboxVideoType = (CheckBox) findViewById(R.id.checkboxVideoType); checkboxVideoType.setOnCheckedChangeListener(this); nasaTV_Prefs = getSharedPreferences("nasaTV_Prefs", 0); checkboxVideoType.setChecked(nasaTV_Prefs.getBoolean("checkboxVideoType", true)); Button clbutton = (Button) findViewById(R.id.clbutton); clbutton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { ChangeLog cl = new ChangeLog(Settings.this); cl.getFullLogDialog().show(); } }); } public void onCheckedChanged(CompoundButton cb, boolean isChecked) { if (cb == checkboxVideoType){ SharedPreferences.Editor editor = nasaTV_Prefs.edit(); editor.putBoolean("checkboxVideoType", isChecked); editor.commit(); // Commit the edit, i.e., save the state of the flag! } } }

    Read the article

  • Logging broadcast Intents and manually trigger them (Android)

    - by poeschlorn
    Hey guys, during my development in android I've missed a function that can log every broadcast intent that occur. Sometimes it had been very useful to have a function like that... I'm also wondering how to trigger those broadcast intents manually on the emulator. Is there an entire overview of available broadcast intents? Would be great if someone would have some answers, greets, poeschlorn

    Read the article

  • How can I pick multiple images from the built-in picker Intent?

    - by dguardi
    Is it possible to reuse the picker Intent to select multiple pictures instead of one? I haven't found a way and I'm trying to reproduce it with a grid view but my alignment is very poor and my performance is not quite as good as the picker. Intent photoPickerIntent = new Intent(Intent.ACTION_PICK); photoPickerIntent.setType("image/*"); startActivityForResult(photoPickerIntent, REQ_PICKER);

    Read the article

  • Android Java Eclipse Intent with 2 Projects

    - by user3793685
    Good day! I have 2 Projects in my Eclipse. MainActivity1 and MainActivity2 are the names of the activities. The MainActivity2 is connected to the MainActivity1 via Project in the properties of the MainActivity1. So far, I can call the package of the MainActivity2 from the MainActivity1. Now, below are my problem: I have a button in MainActivity1. What I want to do is after I click on the button in the MainActivity1, it runs the MainActivity2 project and some variables will be passed on to the MainActivity2. I've been searching in google for a while now and I couldn't get the right keyword for it. I've checked some of the questions here in StackOverflow but I'm unable to locate the problem similar to mine with calling and running the MainActivity2 class from the MainActivity1.java I'm a noob in Android Java but have knowledge in other OOP. Any tips will be a great help. Thanks

    Read the article

  • How to establish a two-way communication between Activity and Service in different process?

    - by steff
    Hi everyone, I'm working on establishing a two-way communication between an Activity and a Service which runs in a different process. Querying the process from the Activity is no big deal. But I want the process to notify the Activity on events. The idea behind it is this: the service runs independently from the actual app. It queries a webserver periodically. If a new task is found on the webserver the process should notify the activity. I found this thread over at AndDev.org but it doesn't seem to work for me. I've been messing around with BroadcastReceiver. I've implemented an interface which should notify the Activity but the problem is that the listener is always null since the Broadcast from the process is done via Intent, hence the class that extends BroadcastReceiver will be newly instantiated. How can I establish a 2-way communication? This has to be possible. Thanks for any help, steff

    Read the article

  • Can jQuery perform a compound select against the top level only? (a.k.a. "How to avoid chaining chil

    - by harpo
    Basically, is there a way to write a.children('.outer').children('.inner') without the intermediate selector? I can't write $('.outer > .inner', a) because I don't want to do full-depth search against a — I know that the .outer elements are immediate children of a. It's partly a matter of "elegance", but partly because I'm trying to avoid "throwaway" element sets. Yes, jQuery may in effect do the same thing, but it has a better chance of optimizing (at least in theory), when it knows the full query's intent.

    Read the article

  • Android service puts multiple instances of an activity in the history

    - by HenryAdamsJr
    I'm making a music player. When you press play, it loads a notification into the OnGoing section. When you go anywhere else in the system, I want the music to keep playing. All of this is fine. The problem is that when I relaunch my activity from the Notification, it adds a task to the history stack each time, so if I hit back, I have to see the instance of Activity B from where I pressed play, and from every time I clicked on the notification to go back to Activity B. I want the instance of Activity B that I launch from the notification (via the service) to be the only copy of that Activity in the history. I've been playing around with various Intent flags and Activity attributes in the manifest, but I haven't found the proper combination.

    Read the article

  • How to add a dynamically resolved activity name to the back stack (without using PARENT_ACTIVITY)?

    - by user3214249
    The goal is 1) Start activity A from AppWidgetProvider or any other background task (it is simple). 2) From activity A go to activity B after clicking Back button. The problem is that I can't set PARENT_ACTIVITY in AndroidManifest.xml, because the activity B class name gets determined at run time. So in one case I need to go to activity B, in other case it is another activity. Seems like I can't use TaskStackBuilder without PARENT_ACTIVITY. I could handle this in the finish() method of activity A, but it should be a simpler way to add activity B to the "back stack" when I run startActivity(intent). Any ideas?

    Read the article

  • Can jQuery perform a compound select against the top level only?

    - by harpo
    Basically, is there a way to write a.children('.outer').children('.inner') without the intermediate selector? I can't write $('.outer > .inner', a) because I don't want to do full-depth search against a — I know that the .outer elements are immediate children of a. It's partly a matter of "elegance", but partly because I'm trying to avoid "throwaway" element sets. Yes, jQuery may in effect do the same thing, but it has a better chance of optimizing (at least in theory), when it knows the full query's intent.

    Read the article

  • Failure in Yahoo Authentication in Android

    - by Jayson Tamayo
    I'm trying to integrate Yahoo into my application. I want them to login using their Yahoo accounts because I will be needing their names later in the application. But whenever I request for a token, I receive the following errors: getRequestToken() Exception: oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: Service provider responded in error: 400 (Bad Request) Here is my code (Request_Token_Activity.java): import oauth.signpost.OAuth; import oauth.signpost.OAuthConsumer; import oauth.signpost.OAuthProvider; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import oauth.signpost.commonshttp.CommonsHttpOAuthProvider; import oauth.signpost.signature.HmacSha1MessageSigner; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; public class Request_Token_Activity extends Activity { private OAuthConsumer consumer; private OAuthProvider provider; private SharedPreferences prefs; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { consumer = new CommonsHttpOAuthConsumer("my consumer key", "my consumer secret"); consumer.setMessageSigner(new HmacSha1MessageSigner()); provider = new CommonsHttpOAuthProvider( "http://api.login.yahoo.com/oauth/v2/get_request_token", "http://api.login.yahoo.com/oauth/v2/get_token", "http://api.login.yahoo.com/oauth/v2/request_auth"); } catch (Exception e) { Log.e("", "onCreate Exception: " + e.toString()); } getRequestToken(); } private void getRequestToken() { try { String url = provider.retrieveRequestToken(consumer, "yahooapi://callback"); Log.i("", "Yahoo URL: " + url); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND); this.startActivity(intent); } catch (Exception e) { Log.i("", "getRequestToken() Exception: " + e.toString()); } } @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); prefs = PreferenceManager.getDefaultSharedPreferences(this); final Uri uri = intent.getData(); if (uri != null && uri.getScheme().equals("yahooapi")) { getAccessToken(uri); } } private void getAccessToken(Uri uri) { final String oauth_verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER); try { provider.retrieveAccessToken(consumer, oauth_verifier); final Editor edit = prefs.edit(); edit.putString("YAHOO_OAUTH_TOKEN", consumer.getToken()); edit.putString("YAHOO_OAUTH_TOKEN_SECRET", consumer.getTokenSecret()); edit.commit(); String token = prefs.getString("YAHOO_OAUTH_TOKEN", ""); String secret = prefs.getString("YAHOO_OAUTH_TOKEN_SECRET", ""); consumer.setTokenWithSecret(token, secret); Log.i("", "Yahoo OAuth Token: " + token); Log.i("", "Yahoo OAuth Token Secret: " + token); } catch (Exception e) { Log.i("", "getAccessToken Exception: " + e.toString()); } } } And this is a snapshot of my AndroidManifest.xml: <activity android:name="Request_Token_Activity" android:launchMode="singleTask"> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="yahooapi" android:host="callback" /> </intent-filter> </activity> I have set-up my Yahoo Project as a Web Application and put Read and Write access to Social and Contacts. What am I doing wrong?

    Read the article

  • Passing ArrayList<String> between tabs

    - by Christophe
    Hi all, I'm not very clear about the Intent object and how to use it to pass data between Activities. In my application I have several tabs between which I want to pass ArrayList. Here is a sample code I plan to use, but I'm missing the part where the main activity catches the Intent and passes it to the new activity on start : 1. myTabs.java == This is where I think I need to add some code to pass the data between TabOne and TabTwo. For now it is just using the sample code of the TabActivity sample. public class myTabs extends TabActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Resources res = getResources(); // Resource object to get Drawables TabHost tabHost = getTabHost(); // The activity TabHost TabHost.TabSpec spec; // Reusable TabSpec for each tab Intent intent; // Reusable Intent for each tab // Create an Intent to launch an Activity for the tab (to be reused) intent = new Intent().setClass(this, TabPeopleActivity.class); // Initialize a TabSpec for each tab and add it to the TabHost spec = tabHost.newTabSpec("TabOne").setIndicator("TabOne", res.getDrawable(R.drawable.ic_tab_one)) .setContent(intent); tabHost.addTab(spec); // Do the same for the other tabs intent = new Intent().setClass(this, TabTransactionActivity.class); spec = tabHost.newTabSpec("TabTwo").setIndicator("TabTwo", res.getDrawable(R.drawable.ic_tab_two)) .setContent(intent); tabHost.addTab(spec); tabHost.setCurrentTab(0); } } 2. TabOne.java == I added a piece of code in the onStop procedure to fill in the Intent data with the array I want to pass to TabTwo. Not sure it is the right way to do though. public class TabOne extends Activity { [...] private ArrayList<String> arrayPeople; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tabone); arrayPeople = new ArrayList<String>(); [... here we modify arrayPeople ...] } /** Called when the activity looses focus **/ @Override public void onStop(){ Intent myIntent = new Intent(); myIntent.putStringArrayListExtra("arrayPeople", arrayPeople); this.setIntent(myIntent); } } 3. TabTwo.java == Here I am trying to fetch the ArrayList from the Intent that is supposed to be passed when the Activity starts. But how to do this? public class TabTwo extends Activity { private ArrayList<String> arrayPeople; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.transaction); Intent myIntent = new Intent(); myIntent = this.getIntent(); arrayPeople = myIntent.getStringArrayListExtra("arrayPeople"); } } Thanks for your ideas !

    Read the article

  • Display HttpResponse (string from Handler) in new WebView

    - by datguywhowanders
    I have the following code in a form's submit button onClickListener: String action, user, pwd, user_field, pwd_field; action = "theURL"; user_field = "id"; pwd_field = "pw"; user = "username"; pwd = "password!!"; List<NameValuePair> myList = new ArrayList<NameValuePair>(); myList.add(new BasicNameValuePair(user_field, user)); myList.add(new BasicNameValuePair(pwd_field, pwd)); HttpParams params = new BasicHttpParams(); HttpClient client = new DefaultHttpClient(params); HttpPost post = new HttpPost(action); HttpResponse end = null; String endResult = null; try { post.setEntity(new UrlEncodedFormEntity(myList)); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { HttpResponse response = client.execute(post); end = response; } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } BasicResponseHandler myHandler = new BasicResponseHandler(); try { endResult = myHandler.handleResponse(end); } catch (HttpResponseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } How can I take the resulting string (endResult) and start a new activity using an intent that will open webview and load the html?

    Read the article

  • how to show all added items into another activity, like: AddtoCart and ViewCart Functionality

    - by Stanley
    i am trying to make a shopping cart app, allowing user to choose category then select item to purchase, once user will click on any item to purchase, then showing that selected item into another activity with item image, name, cost, qty (to accept by user) and also providing add to cart functionality, now i want whenever user will click on Add to Cart button, then selected item need to show in ViewCart Activity, so here i am placing my AddtoCart Activity code, please tell me what i need to write to show added item(s) into ViewCart Category just like in shopping cart, In ViewCart activity i just want to show item title, cost and qty (entered by user):- public class AddtoCart extends Activity{ static final String KEY_TITLE = "title"; static final String KEY_COST = "cost"; static final String KEY_THUMB_URL = "imageUri"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.single); Intent in = getIntent(); String title = in.getStringExtra(KEY_TITLE); String thumb_url = in.getStringExtra(KEY_THUMB_URL); String cost = in.getStringExtra(KEY_COST); ImageLoader imageLoader = new ImageLoader(getApplicationContext()); ImageView imgv = (ImageView) findViewById(R.id.single_thumb); TextView txttitle = (TextView) findViewById(R.id.single_title); TextView txtcost = (TextView) findViewById(R.id.single_cost); txttitle.setText(title); txtcost.setText(cost); imageLoader.DisplayImage(thumb_url, imgv); // Save a reference to the quantity edit text final EditText editTextQuantity = (EditText) findViewById(R.id.edit_qty); ImageButton addToCartButton = (ImageButton) findViewById(R.id.img_add); addToCartButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Check to see that a valid quantity was entered int quantity = 0; try { quantity = Integer.parseInt(editTextQuantity.getText() .toString()); if (quantity <= 0) { Toast.makeText(getBaseContext(), "Please enter a quantity of 1 or higher", Toast.LENGTH_SHORT).show(); return; } } catch (Exception e) { Toast.makeText(getBaseContext(), "Please enter a numeric quantity", Toast.LENGTH_SHORT).show(); return; } // Close the activity finish(); } }); }}

    Read the article

  • Options for organizing android app with multiple independent apps

    - by lazyguy
    Problem Definition: We have a fairly large app which has multiple use cases such that they are all independent of each other. For example lets say we have a1, a2, a3 & a4 modules that are independent apps or use cases for our main app 'A'. The independent a1, a2, a3, a4 are all purchasable apps such that the user goes to our website instead of play store and activate either a1 or a2 by paying some fees on our website. So basically App 'A' is a free app in play-store and is sort of Dashboard with buttons to launch a1, a2, a3, a4. When the user click on lets say a1 button then we will check if a1 is already installed and launch it but if it is not present then give the user a link to download it. Option 1: Have a main app 'A' and a1, a2, a3, a4 as library project. But with this approach the main app A is too big in size. Option 2: Have a1, a2, a3, a4 build as separate .apk and then put in the assets folder of main app 'A' and then install them as needed. Again size of main app A is bigger. Option 3: Upload a1, a2, a3, a4 to a third party website or play store and download from it as needed. This way the main app remains lighter. Observation: In all these approaches there will be an independent app installed with its own icon on users phone. So basically user can launch from either the Dashboard (which will eventually launch an intent from Activity in a1 app) or user can directly launch app a1. Follow-up Question: Is there any other solution that anyone can suggest to tackle this kind of problem? Another things is by going this approach app a1, a2, a3, a4 can be developed & tested independently of each other.

    Read the article

  • Click on notification starts activity twice

    - by Karussell
    I'm creating a notification from a service with the following code: NotificationManager notificationManager = (NotificationManager) ctx .getSystemService(Context.NOTIFICATION_SERVICE); CharSequence tickerText = "bla ..."; long when = System.currentTimeMillis(); Notification notification = new Notification(R.drawable.icon, tickerText, when); Intent notificationIntent = new Intent(ctx, SearchActivity.class). putExtra(SearchActivity.INTENT_SOURCE, MyNotificationService.class.getSimpleName()); PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, notificationIntent, 0); notification.setLatestEventInfo(ctx, ctx.getString(R.string.app_name), tickerText, contentIntent); notification.flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(1, notification); The logs clearly says that the the method startActivity is called twice times: 04-02 23:48:06.923: INFO/ActivityManager(2466): Starting activity: Intent { act=android.intent.action.SEARCH cmp=com.xy/.SearchActivity bnds=[0,520][480,616] (has extras) } 04-02 23:48:06.923: WARN/ActivityManager(2466): startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { act=android.intent.action.SEARCH cmp=com.xy/.SearchActivity bnds=[0,520][480,616] (has extras) } 04-02 23:48:06.958: INFO/ActivityManager(2466): Starting activity: Intent { act=android.intent.action.SEARCH cmp=com.xy/.SearchActivity bnds=[0,0][480,96] (has extras) } 04-02 23:48:06.958: WARN/ActivityManager(2466): startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { act=android.intent.action.SEARCH cmp=com.xy/.SearchActivity bnds=[0,0][480,96] (has extras) } 04-02 23:48:07.087: INFO/notification(5028): onStartCmd: received start id 2: Intent { cmp=com.xy/.NotificationService } 04-02 23:48:07.310: INFO/notification(5028): onStartCmd: received start id 3: Intent { cmp=com.xy/.NotificationService } 04-02 23:48:07.392: INFO/ActivityManager(2466): Displayed activity com.xy/.SearchActivity: 462 ms (total 462 ms) 04-02 23:48:07.392: INFO/ActivityManager(2466): Displayed activity com.xy/.SearchActivity: 318 ms (total 318 ms) Why are they started twice? There are two identical questions on stackoverflow: here and here. But they do not explain what the initial issue could be and they do not work for me. E.g. changing to launchMode singleTop is not appropriated for me and it should work without changing launchMode according to the official docs (see Invoking the search dialog). Nevertheless I also tried to add the following flags to notificationIntent Intent.FLAG_ACTIVITY_CLEAR_TOP | PendingIntent.FLAG_UPDATE_CURRENT but the problem remains the same.

    Read the article

  • Image Rescan issue

    - by user1296361
    I am working on a code that could scan the specific folder, when picture is taken, I used the following code: Intent intent = new Intent(); intent.setType("image/*"); //intent.setAction(Intent.ACTION_GET_CONTENT); sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://sdcard/ghost/" + Environment.getExternalStorageDirectory()))); startActivityForResult( Intent.createChooser(intent, "Select Picture"), 0); It works fine, but when I exit the app and start the app again, scan is not performed, what could be the issue? Help needed!!!

    Read the article

  • Video Recording Not Working in ICS

    - by Nirav Ranpara
    I have implement code Record video in Android Phone . This code is working in 2.2 , 2.3 . not in ICS But when I checked in ICS code is not working ? here I posted code and xml file. videorecord.java import java.io.File; import java.io.IOException; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.hardware.Camera; import android.media.CamcorderProfile; import android.media.MediaRecorder; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Environment; import android.util.Log; import android.view.Display; import android.view.KeyEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class videorecord extends Activity{ SharedPreferences.Editor pre; String filename; CountDownTimer t; private Camera myCamera; private MyCameraSurfaceView myCameraSurfaceView; private MediaRecorder mediaRecorder; Integer cnt=0; LinearLayout myButton; TextView myButton1; SurfaceHolder surfaceHolder; boolean recording; private TextView txtcount; private ImageView btnplay; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); recording = false; setContentView(R.layout.videorecord); init(); myCamera = getCameraInstance(); if(myCamera == null){ } myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera); FrameLayout myCameraPreview = (FrameLayout)findViewById(R.id.videoview); Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); myCameraSurfaceView.setLayoutParams(new LinearLayout.LayoutParams(width, height-60)); myCameraPreview.addView(myCameraSurfaceView); myButton = (LinearLayout)findViewById(R.id.mybutton); btnplay.setOnClickListener(myButtonOnClickListener); } private void init() { txtcount = (TextView) findViewById(R.id.txtcounter); //myButton1 = (TextView) findViewById(R.id.mybutton1); btnplay = (ImageView)findViewById(R.id.btnplay); t = new CountDownTimer( Long.MAX_VALUE , 1000) { @Override public void onTick(long millisUntilFinished) { cnt++; String time = new Integer(cnt).toString(); long millis = cnt; int seconds = (int) (millis / 60); int minutes = seconds / 60; seconds = seconds % 60; txtcount.setText(String.format("%d:%02d:%02d", minutes, seconds,millis)); } @Override public void onFinish() { } }; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)) { if(recording) { new AlertDialog.Builder(videorecord.this).setTitle("Do you want to save Video ?") .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { filename(); //finish(); } }).setNegativeButton("Cancle", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }).show(); } else { if ((keyCode == KeyEvent.KEYCODE_BACK)) { //Intent homeIntent= new Intent(Intent.ACTION_MAIN); //homeIntent.addCategory(Intent.CATEGORY_HOME); //homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //startActivity(homeIntent); //this.finishActivity(1); finish(); } //moveTaskToBack(true); // finish(); return super.onKeyDown(keyCode, event); } } else { // Toast.makeText(getApplicationContext(), "asd", Toast.LENGTH_LONG).show(); android.os.Process.killProcess(android.os.Process.myPid()) ; } return super.onKeyDown(keyCode, event); } ImageView.OnClickListener myButtonOnClickListener = new ImageView.OnClickListener(){ public void onClick(View v) { if(recording){ Log.e("Record error", "error in recording ."); mediaRecorder.stop(); t.cancel(); filename(); releaseMediaRecorder(); }else{ releaseCamera(); Log.e("Record Stop error", "error in recording ."); // if(!prepareMediaRecorder()){ prepareMediaRecorder(); finish(); } mediaRecorder.start(); recording = true; // myButton1.setText("STOP Recording"); // btnplay.setImageResource(android.R.drawable.ic_media_pause); btnplay.setImageResource(R.drawable.stoprec); t.start(); } }}; private Camera getCameraInstance(){ Camera c = null; try { c = Camera.open(); } catch (Exception e){ } return c; } private void filename() { AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Save Video"); alert.setMessage("Enter File Name"); final EditText input = new EditText(this); alert.setView(input); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if(input.getText().length()>=1) { filename = input.getText().toString(); File sdcard = new File(Environment.getExternalStorageDirectory() + "/VideoRecord"); File from = new File(sdcard,"null.mp4"); File to = new File(sdcard,filename+".mp4"); from.renameTo(to); SharedPreferences sp = videorecord.this.getSharedPreferences("data", MODE_WORLD_WRITEABLE); pre = sp.edit(); pre.clear(); pre.commit(); pre.putString("lastvideo", filename+".mp4"); pre.commit(); //btnplay.setImageResource(android.R.drawable.ic_media_play); btnplay.setImageResource(R.drawable.startrec); // Intent intent = new Intent(videorecord.this,StopVidoWatch_Activity.class); // startActivity(intent); Intent myIntent = new Intent(getApplicationContext(), StopVidoWatch_Activity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(myIntent); } else { filename(); } } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Intent intent = new Intent(videorecord.this,StopVidoWatch_Activity.class); // startActivity(intent); File file = new File(Environment.getExternalStorageDirectory() + "/VideoRecord/null.mp4"); //boolean deleted = file.delete(); file.delete(); finish(); } }); alert.show(); } private boolean prepareMediaRecorder(){ myCamera = getCameraInstance(); mediaRecorder = new MediaRecorder(); myCamera.unlock(); mediaRecorder.setCamera(myCamera); mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH)); File folder = new File(Environment.getExternalStorageDirectory() + "/VideoRecord"); boolean success = false; if (!folder.exists()) { success = folder.mkdir(); } if (!success) { } else { } mediaRecorder.setOutputFile("/sdcard/VideoRecord/"+filename+".mp4"); mediaRecorder.setMaxDuration(60000); mediaRecorder.setMaxFileSize(5000000); Display display = getWindowManager().getDefaultDisplay(); int width = display.getHeight(); int height = display.getWidth(); String s = new String(); s= s.valueOf(width); String s1 = new String(); s1= s1.valueOf(height); // Toast.makeText(videorecord.this, "Width : " + s , Toast.LENGTH_LONG).show(); // Toast.makeText(videorecord.this, "Height : " + s1 , Toast.LENGTH_LONG).show(); mediaRecorder.setVideoSize(height, width); mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder().getSurface()); try { mediaRecorder.prepare(); } catch (IllegalStateException e) { releaseMediaRecorder(); return false; } catch (IOException e) { releaseMediaRecorder(); return false; } return true; } @Override protected void onPause() { super.onPause(); releaseMediaRecorder(); releaseCamera(); } private void releaseMediaRecorder() { if (mediaRecorder != null) { mediaRecorder.reset(); mediaRecorder.release(); mediaRecorder = null; myCamera.lock(); } } private void releaseCamera(){ if (myCamera != null){ myCamera.release(); myCamera = null; } } public class MyCameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{ private SurfaceHolder mHolder; private Camera mCamera; public MyCameraSurfaceView(Context context, Camera camera) { super(context); mCamera = camera; mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void surfaceChanged(SurfaceHolder holder, int format, int weight, int height) { if (mHolder.getSurface() == null){ return; } try { mCamera.stopPreview(); } catch (Exception e){ } try { mCamera.setPreviewDisplay(mHolder); mCamera.startPreview(); } catch (Exception e){ } } public void surfaceCreated(SurfaceHolder holder) { try { mCamera.setPreviewDisplay(holder); mCamera.startPreview(); } catch (IOException e) { } } public void surfaceDestroyed(SurfaceHolder holder) { } } } videorecord.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <FrameLayout android:layout_width="fill_parent" android:layout_height="fill_parent" > <FrameLayout android:id="@+id/videoview" android:layout_width="fill_parent" android:layout_height="fill_parent"></FrameLayout> <LinearLayout android:id="@+id/mybutton" android:layout_width="fill_parent" android:layout_marginBottom="0dip" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_weight="0" > <!-- <TextView android:text="START Recording" android:id="@+id/mybutton1" android:layout_height="wrap_content" android:layout_width="wrap_content" style="@style/savestyle" android:layout_weight="1" android:gravity="left" > </TextView> --> <ImageView android:layout_height="wrap_content" android:id="@+id/btnplay" android:padding="5dip" android:background="#A0000000" android:textColor="#ffffffff" android:layout_width="wrap_content" android:src="@drawable/startrec" /> </LinearLayout> <TextView android:text="00:00:00" android:id="@+id/txtcounter" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right|bottom" android:padding="5dip" android:background="#A0000000" android:textColor="#ffffffff" /> </FrameLayout> <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/bgcolor" > <LinearLayout android:layout_above="@+id/mybutton" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" > </LinearLayout> </RelativeLayout> </LinearLayout>

    Read the article

  • Android Expandable List View Update

    - by Gaurav Arora
    I am implementing a chatting application, where I have made a service to listen all the presence changed. On the change of the presence I want to update the data and I am unable to update the data that is showing in the expandable list view. Please suggest me a means to do the same. public class UserMenuActivity extends ExpandableListActivity { private XMPPConnection connection; String name,availability,subscriptionStatus; TextView tv_Status; /** Variable Define here */ private String[] data = { "View my profile", "New Multiperson Chat", "New Broad Cast Message", "New Contact Category", "New Group", "Invite to CCM", "Search", "Expand All", "Settings", "Help", "Close" }; private String[] data_Contact = { "Rename Category","Move Contact to Category", "View my profile", "New Multiperson Chat", "New Broad Cast Message", "New Contact Category", "New Group", "Invite to CCM", "Search", "Expand All", "Settings", "Help", "Close" }; private String[] data_child_contact = { "Open chat", "Delete Contact","View my profile", "New Multiperson Chat", "New Broad Cast Message", "New Contact Category", "New Group", "Invite to CCM", "Search", "Expand All", "Settings", "Help", "Close" }; private String[] menuItem = { "Chats", "Contacts", "CGM Groups", "Pending","Request" }; private List<String> menuItemList = Arrays.asList(menuItem); private int commonGroupPosition = 0; private String etAlertVal; private DatabaseHelper dbHelper; private int categoryID, listPos; /** New Code here.. */ private ArrayList<String> groupNames; private ArrayList<ArrayList<ChildItems>> childs; private UserMenuAdapter adapter; private Object object; private String[] data2 = { "PIN Michelle", "IP Call" }; private ListView mlist2; private ImageButton mimBtnMenu; private LinearLayout mllpopmenu; private View popupView; private PopupWindow popupWindow; private AlertDialog.Builder alert; private EditText input; private TextView mtvUserName, mtvUserTagLine; private ExpandableListView mExpandableListView; public static List<CategoryDataClass> categoryList; private boolean menuType = false; private String childValContact=""; public static Context context; @Override public void onBackPressed() { if (mllpopmenu.getVisibility() == View.VISIBLE) { mllpopmenu.setVisibility(View.INVISIBLE); } else { if (CCMStaticVariable.CommonConnection.isConnected()) { CCMStaticVariable.CommonConnection.disconnect(); } super.onBackPressed(); } } @SuppressWarnings("unchecked") @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { if (mllpopmenu.getVisibility() == View.VISIBLE) { mllpopmenu.setVisibility(View.INVISIBLE); } else { if (commonGroupPosition >= 4 && menuType == true) { if(childValContact == ""){ mllpopmenu.setVisibility(View.VISIBLE); mlist2.setAdapter(new ArrayAdapter(UserMenuActivity.this, R.layout.listviewtext, R.id.tvMenuText, data_Contact)); }else{ mllpopmenu.setVisibility(View.VISIBLE); mlist2.setAdapter(new ArrayAdapter(UserMenuActivity.this, R.layout.listviewtext, R.id.tvMenuText, data_child_contact)); } } else if (commonGroupPosition == 0) { mllpopmenu.setVisibility(View.VISIBLE); mlist2.setAdapter(new ArrayAdapter(UserMenuActivity.this, R.layout.listviewtext, R.id.tvMenuText, data)); } } return true; } return super.onKeyDown(keyCode, event); } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.usermenulayout); dbHelper = new DatabaseHelper(UserMenuActivity.this); //this.context = context.getApplicationContext(); XMPPConn.getContactList(); connection = CCMStaticVariable.CommonConnection; Presence userPresence = new Presence(Presence.Type.available); userPresence.setPriority(24); userPresence.setMode(Presence.Mode.away); connection.sendPacket(userPresence); } @Override protected void onResume() { super.onResume(); Presence userPresence = new Presence(Presence.Type.available); userPresence.setPriority(24); userPresence.setMode(Presence.Mode.away); connection.sendPacket(userPresence); XMPPConn.getContactList(); setExpandableListView(); } public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { if (groupPosition == 1 && childPosition == 0) { startActivity(new Intent(UserMenuActivity.this, InvitetoCCMActivity.class)); } else if (groupPosition == 1 && childPosition != 0) { Intent intent = new Intent(UserMenuActivity.this, UserChatActivity.class); intent.putExtra("userNameVal", XMPPConn.mfriendList.get(childPosition - 1).friendName); startActivity(intent); } else if (groupPosition == 2 && childPosition == 0) { startActivity(new Intent(UserMenuActivity.this, CreateGroupActivity.class)); } else if (groupPosition == 2 && childPosition != 0) { String GROUP_NAME = childs.get(groupPosition).get(childPosition) .getName().toString(); int end = GROUP_NAME.indexOf("("); CCMStaticVariable.groupName = GROUP_NAME.substring(0, end).trim(); startActivity(new Intent(UserMenuActivity.this, GroupsActivity.class)); } else if (groupPosition >= 4) { childValContact = childs.get(groupPosition).get(childPosition).getName().trim(); showToast("user==>"+childValContact, 0); } return false; } private void setExpandableListView() { /***###############GROUP ARRAY ############################*/ final ArrayList<String> groupNames = new ArrayList<String>(); groupNames.add("Chats (2)"); groupNames.add("Contacts (" + XMPPConn.mfriendList.size() + ")"); groupNames.add("CGM Groups (" + XMPPConn.mGroupList.size() + ")"); groupNames.add("Pending (1)"); XMPPConn.getGroup(); categoryList = dbHelper.getAllCategory(); /**Group From Sever*/ if (XMPPConn.mGroupList.size() > 0) { for (int g = 0; g < XMPPConn.mGroupList.size(); g++) { XMPPConn.getGroupContact(XMPPConn.mGroupList.get(g).groupName); groupNames.add(XMPPConn.mGroupList.get(g).groupName + "(" + XMPPConn.mGroupContactList.size()+ ")"); } } if(categoryList.size() > 0){ for (int cat = 0; cat < categoryList.size(); cat++) { groupNames.add(categoryList.get(cat).getCategoryName()+ "(0)"); } } this.groupNames = groupNames; /*** ###########CHILD ARRAY * #################*/ ArrayList<ArrayList<ChildItems>> childs = new ArrayList<ArrayList<ChildItems>>(); ArrayList<ChildItems> child = new ArrayList<ChildItems>(); child.add(new ChildItems("Alisha", "Hi",0)); child.add(new ChildItems("Michelle", "Good Morning",0)); childs.add(child); child = new ArrayList<ChildItems>(); child.add(new ChildItems("", "",0)); if (XMPPConn.mfriendList.size() > 0) { for (int n = 0; n < XMPPConn.mfriendList.size(); n++) { child.add(new ChildItems(XMPPConn.mfriendList.get(n).friendNickName, XMPPConn.mfriendList.get(n).friendStatus, XMPPConn.mfriendList.get(n).friendState)); } } childs.add(child); /************** CGM Group Child here *********************/ child = new ArrayList<ChildItems>(); child.add(new ChildItems("", "",0)); if (XMPPConn.mGroupList.size() > 0) { for (int grop = 0; grop < XMPPConn.mGroupList.size(); grop++) { child.add(new ChildItems( XMPPConn.mGroupList.get(grop).groupName + " (" + XMPPConn.mGroupList.get(grop).groupUserCount + ")", "",0)); } } childs.add(child); child = new ArrayList<ChildItems>(); child.add(new ChildItems("Shuchi", "Pending (Waiting for Authorization)",0)); childs.add(child); /************************ Group Contact List *************************/ if (XMPPConn.mGroupList.size() > 0) { for (int g = 0; g < XMPPConn.mGroupList.size(); g++) { /** Contact List */ XMPPConn.getGroupContact(XMPPConn.mGroupList.get(g).groupName); child = new ArrayList<ChildItems>(); for (int con = 0; con < XMPPConn.mGroupContactList.size(); con++) { child.add(new ChildItems( XMPPConn.mGroupContactList.get(con).friendName, XMPPConn.mGroupContactList.get(con).friendStatus,0)); } childs.add(child); } } if(categoryList.size() > 0){ for (int cat = 0; cat < categoryList.size(); cat++) { child = new ArrayList<ChildItems>(); child.add(new ChildItems("-none-", "",0)); childs.add(child); } } this.childs = childs; /** Set Adapter here */ adapter = new UserMenuAdapter(this, groupNames, childs); setListAdapter(adapter); object = this; mlist2 = (ListView) findViewById(R.id.list2); mimBtnMenu = (ImageButton) findViewById(R.id.imBtnMenu); mllpopmenu = (LinearLayout) findViewById(R.id.llpopmenu); mtvUserName = (TextView) findViewById(R.id.tvUserName); mtvUserTagLine = (TextView) findViewById(R.id.tvUserTagLine); //Set User name.. System.out.println("CCMStaticVariable.loginUserName===" + CCMStaticVariable.loginUserName); if (!CCMStaticVariable.loginUserName.equalsIgnoreCase("")) { mtvUserName.setText("" + CCMStaticVariable.loginUserName); } /** Expandable List set here.. */ mExpandableListView = (ExpandableListView) this .findViewById(android.R.id.list); mExpandableListView.setOnGroupClickListener(new OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { XMPPConn.getContactList(); if (parent.isGroupExpanded(groupPosition)) { commonGroupPosition = 0; }else{ commonGroupPosition = groupPosition; } String GROUP_NAME = groupNames.get(groupPosition); int end = groupNames.get(groupPosition).indexOf("("); String GROUP_NAME_VALUE = GROUP_NAME.substring(0, end).trim(); if (menuItemList.contains(GROUP_NAME_VALUE)) { menuType = false; CCMStaticVariable.groupCatName = GROUP_NAME_VALUE; } else { menuType = true; CCMStaticVariable.groupCatName = GROUP_NAME_VALUE; } long findCatId = dbHelper.getCategoryID(GROUP_NAME_VALUE); if (findCatId != 0) { categoryID = (int) findCatId; } childValContact=""; showToast("Clicked on==" + GROUP_NAME_VALUE, 0); return false; } }); /** Click on item */ mlist2.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int pos,long arg3) { if (commonGroupPosition >= 4) { if(childValContact == ""){ if (pos == 0) { showAlertEdit(CCMStaticVariable.groupCatName); } /** Move contact to catgory */ if (pos == 1) { startActivity(new Intent(UserMenuActivity.this,AddContactCategoryActivity.class)); } }else{ if(pos == 0){ Intent intent = new Intent(UserMenuActivity.this,UserChatActivity.class); intent.putExtra("userNameVal",childValContact); startActivity(intent); } if(pos == 1){ XMPPConn.removeEntry(childValContact); showToast("Contact deleted sucessfully", 0); Intent intent = new Intent(UserMenuActivity.this,UserMenuActivity.class); } } } else { /** MyProfile */ if (pos == 0) { startActivity(new Intent(UserMenuActivity.this, MyProfileActivity.class)); } /** New multiperson chat start */ if (pos == 1) { startActivity(new Intent(UserMenuActivity.this, NewMultipersonChatActivity.class)); } /** New Broadcast message */ if (pos == 2) { startActivity(new Intent(UserMenuActivity.this, NewBroadcastMessageActivity.class)); } /** Click on add category */ if (pos == 3) { showAlertAdd(); } if (pos == 4) { startActivity(new Intent(UserMenuActivity.this, CreateGroupActivity.class)); } if (pos == 5) { startActivity(new Intent(UserMenuActivity.this, InvitetoCCMActivity.class)); } if (pos == 6) { startActivity(new Intent(UserMenuActivity.this, SearchActivity.class)); } if (pos == 7) { onGroupExpand(2); for (int i = 0; i < groupNames.size(); i++) { mExpandableListView.expandGroup(i); } } /** Click on settings */ if (pos == 8) { startActivity(new Intent(UserMenuActivity.this, SettingsActivity.class)); } if (pos == 10) { System.exit(0); } if (pos == 14) { if (mllpopmenu.getVisibility() == View.VISIBLE) { mllpopmenu.setVisibility(View.INVISIBLE); if (popupWindow.isShowing()) { popupWindow.dismiss(); } } else { mllpopmenu.setVisibility(View.VISIBLE); mlist2.setAdapter(new ArrayAdapter( UserMenuActivity.this, R.layout.listviewtext, R.id.tvMenuText, data)); } } } } }); } /** Toast message display here.. */ private void showToast(String msg, int time) { Toast.makeText(this, msg, time).show(); } public String showSubscriptionStatus(String friend){ return friend; } } Service.class public class UpdaterService extends Service { private XMPPConnection connection; String Friend; String user = ""; @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { // Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show(); super.onCreate(); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } @Override public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub showToast("My Service Started", 0); connection = getConnection(); if (connection.isConnected()) { final Roster roster = connection.getRoster(); RosterListener r1 = new RosterListener() { @Override public void presenceChanged(Presence presence) { // TODO Auto-generated method stub XMPPConn.getContactList(); } @Override public void entriesUpdated(Collection<String> arg0) { // TODO Auto-generated method stub //notification("entriesUpdated"); } @Override public void entriesDeleted(Collection<String> arg0) { // TODO Auto-generated method stub //notification("entriesDeleted"); } @Override public void entriesAdded(Collection<String> arg0) { // TODO Auto-generated method stub Iterator<String> it = arg0.iterator(); if (it.hasNext()) { user = it.next(); } RosterEntry entry = roster.getEntry(user); if(entry.getType().toString().equalsIgnoreCase("to")){ int index_of_Alpha = Friend.indexOf("@"); String subID = Friend.substring(0, index_of_Alpha); notification("Hi "+subID+" wants to add you"); } } }; if (roster != null) { roster.setSubscriptionMode(Roster.SubscriptionMode.manual); System.out.println("subscription going on"); roster.addRosterListener(r1); } } else { showToast("Connection lost-", 0); } } protected void showToast(String msg, int time) { Toast.makeText(this, msg, time).show(); } private XMPPConnection getConnection() { return CCMStaticVariable.CommonConnection; } /** Notification manager */ private void notification(CharSequence message) { String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); int icon = R.drawable.ic_launcher; CharSequence tickerText = message; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickerText, when); Context context = getApplicationContext(); CharSequence contentTitle = "CCM"; CharSequence contentText = message; Intent notificationIntent = new Intent(this, ManageNotification.class); notificationIntent.putExtra("Subscriber_ID",user ); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); notification.flags |= Notification.FLAG_AUTO_CANCEL; final int HELLO_ID = 1; mNotificationManager.notify(HELLO_ID, notification); } } Here is my adapter class public class UserMenuAdapter extends BaseExpandableListAdapter { private ArrayList<String> groups; private ArrayList<ArrayList<ChildItems>> childs; private Context context; public LayoutInflater inflater; ImageView img_availabiliy; private static final int[] EMPTY_STATE_SET = {}; private static final int[] GROUP_EXPANDED_STATE_SET = {android.R.attr.state_expanded}; private static final int[][] GROUP_STATE_SETS = { EMPTY_STATE_SET, // 0 GROUP_EXPANDED_STATE_SET // 1 }; public UserMenuAdapter(Context context, ArrayList<String> groups, ArrayList<ArrayList<ChildItems>> childs) { this.context = context; this.groups = groups; this.childs = childs; inflater = LayoutInflater.from(context); } @Override public Object getChild(int groupPosition, int childPosition) { return childs.get(groupPosition).get(childPosition); } @Override public long getChildId(int groupPosition, int childPosition) { return (long) (groupPosition * 1024 + childPosition); } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { View v = null; if (convertView != null) v = convertView; else v = inflater.inflate(R.layout.child_layout, parent, false); ChildItems ci = (ChildItems) getChild(groupPosition, childPosition); TextView tv = (TextView) v.findViewById(R.id.tvChild); tv.setText(ci.getName()); TextView tv2 = (TextView) v.findViewById(R.id.tvChild2); tv2.setText(ci.getDailyStatus()); img_availabiliy = (ImageView)v.findViewById(R.id.img_childlayout_AVAILABILITY); ImageView friendPics = (ImageView)v.findViewById(R.id.ivFriendPics); if(ci.getStatusState() == 1){ img_availabiliy.setImageResource(R.drawable.online); } else if(ci.getStatusState()==0){ img_availabiliy.setImageResource(R.drawable.offline); } else if (ci.getStatusState()==2) { img_availabiliy.setImageResource(R.drawable.away); } else if(ci.getStatusState()==3){ img_availabiliy.setImageResource(R.drawable.busy); } else{ img_availabiliy.setImageDrawable(null); } if((groupPosition == 1 && childPosition == 0)){ friendPics.setImageResource(R.drawable.inviteto_ccm); img_availabiliy.setVisibility(View.INVISIBLE); } else if(groupPosition == 2 && childPosition == 0){ friendPics.setImageResource(R.drawable.new_ccmgroup); img_availabiliy.setVisibility(View.VISIBLE); }else{ if(ci.getPicture()!= null){ Bitmap bitmap = BitmapFactory.decodeByteArray(ci.getPicture(), 0, ci.getPicture().length); bitmap = Bitmap.createScaledBitmap(bitmap, 50, 50, true); friendPics.setImageBitmap(bitmap); }else{ friendPics.setImageResource(R.drawable.avatar); } img_availabiliy.setVisibility(View.VISIBLE); } return v; } @Override public int getChildrenCount(int groupPosition) { return childs.get(groupPosition).size(); } @Override public Object getGroup(int groupPosition) { return groups.get(groupPosition); } @Override public int getGroupCount() { return groups.size(); } @Override public long getGroupId(int groupPosition) { return (long) (groupPosition * 1024); } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { View v = null; if (convertView != null) v = convertView; else v = inflater.inflate(R.layout.group_layout, parent, false); String gt = (String) getGroup(groupPosition); TextView tv2 = (TextView) v.findViewById(R.id.tvGroup); if (gt != null) tv2.setText(gt); /**Set Image on group layout, Max/min*/ View ind = v.findViewById( R.id.explist_indicator); View groupInd = v.findViewById( R.id.llgroup); if( ind != null ) { ImageView indicator = (ImageView)ind; if( getChildrenCount( groupPosition ) == 0 ) { indicator.setVisibility( View.INVISIBLE ); } else { indicator.setVisibility( View.VISIBLE ); int stateSetIndex = ( isExpanded ? 1 : 0) ; Drawable drawable = indicator.getDrawable(); drawable.setState(GROUP_STATE_SETS[stateSetIndex]); } } if( groupInd != null ) { RelativeLayout indicator2 = (RelativeLayout)groupInd; if( getChildrenCount( groupPosition ) == 0 ) { indicator2.setVisibility( View.INVISIBLE ); } else { indicator2.setVisibility( View.VISIBLE ); int stateSetIndex = ( isExpanded ? 1 : 0) ; Drawable drawable2 = indicator2.getBackground(); drawable2.setState(GROUP_STATE_SETS[stateSetIndex]); } } return v; } @Override public boolean hasStableIds() { return true; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } public void onGroupCollapsed(int groupPosition) { } public void onGroupExpanded(int groupPosition) { } } I just want to update my list in ON PRESENCE CHANGED method in the Service class.. Please suggest me a means to do the same.

    Read the article

  • Android custom categories

    - by marian
    Hello, I have a view as a main screen of the application which contains the available application's actions as icon+text pairs ( desktop like). I want to find out programatically what are the activities defined ONLY in my AndroidManifest.xml Suppose I have : < activity android:name="example.mainActivity" android:label="mainActivity" < intent-filter < action android:name="android.intent.action.MAIN" / < category android:name="android.intent.category.LAUNCHER" / < /intent-filter < /activity < activity android:name="example.activity1" android:label="Activity1" < intent-filter < action android:name="android.intent.action.VIEW" / < category android:name="example.custom.ACTIVITY" / < /intent-filter < /activity < activity android:name="example.activity2" android:label="Activity2" < intent-filter < action android:name="android.intent.action.VIEW" / < category android:name="example.custom.ACTIVITY" / < /intent-filter < /activity I want that in the mainActivity to dinamically read Activity1 and Activity2 because when i add Activity3 for example it will be automatically read. I thought that this could be done by defining a custom category, example.custom.ACTIVITY, and in the mainActivity use the packageManager.queryIntentActivities(Intent intent, int flags) but it doesn't seem to be working. I really would like to code it to dinamically discover the installed activities in my application. Do you have any ideas on how to do this? Thank you

    Read the article

  • Why doesn't my android application show up in the launcher?

    - by rushinge
    I'm developing an application for the Android platform targeted for api level 4 (Android 1.6) but I can't get it to show up on my phone and I can't figure out why. Here's my AndroidManifest.xml is there a problem in here? Or is there something else I should be looking at? <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.sbe.app.hellocogen" android:versionCode="1" android:versionName="1.0"> <uses-permission android:name="android.permission.INTERNET" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".activity.ListPlants" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".activity.AddPlant" android:label="Add Plant"> <intent-filter> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </activity> <activity android:name=".activity.UnitActivity" android:label="IP HERE, PLANT NAME"> <intent-filter> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> </activity> </application> <uses-sdk android:minSdkVersion="4"/> </manifest> When I started this application it didn't show up but I fixed it by setting the minimum api level to 4 instead of 7 then it started showing up but now it stopped showing up again and I don't know why.

    Read the article

  • setCurrentTab Android

    - by Ali
    i have 4 tabs on my main screen, main ( set to current ) , Call, Email, Web When a user clicks on any of tab call, email or web, it starts making a call, or go to compose a email, or opens up the browser respectfully. Problem is, i want just three tabs (Call, Email, Web) and i Dont want any tab to be selected by default, means they should only become active when a user Touch them..(a call or any service cant be main at all) All java coding, XML file, and Manifest code is given below, XML File (tab_activity_layout) <?xml version="1.0" encoding="utf-8"?> <TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp"> <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" > <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp"></FrameLayout> </RelativeLayout> </LinearLayout> </TabHost> Java Coding (MainTabActivity) package com.NVT.android; import android.app.TabActivity; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.widget.TabHost; public class MainTabActivity extends TabActivity{ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tab_activity_layout); Resources res = getResources(); // Resource object to get Drawables TabHost tabHost = getTabHost(); // The activity TabHost TabHost.TabSpec spec; // Resusable TabSpec for each tab Intent intent; // Reusable Intent for each tab // Create an Intent to launch an Activity for the tab (to be reused) intent = new Intent().setClass(this, Main.class); // Initialize a TabSpec for each tab and add it to the TabHost spec = tabHost.newTabSpec("main").setIndicator("Main", res.getDrawable(R.drawable.ic_tab_artists_grey)) .setContent(intent); tabHost.addTab(spec); TabHost host=getTabHost(); host.addTab(host.newTabSpec("one") .setIndicator("Call") .setContent(new Intent(this, CallService.class))); host.addTab(host.newTabSpec("two") .setIndicator("Email") .setContent(new Intent(this, EmailService.class))); host.addTab(host.newTabSpec("three") .setIndicator("Web") .setContent(new Intent(this, WebService.class))); } } Manifest file <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.NVT.android" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Main" android:label="@string/app_name"> <!-- <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> --> </activity> <activity android:name=".MainTabActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".Courses"> </activity> <activity android:name=".CampusMap"> </activity> <activity android:name=".GettingHere"> </activity> <activity android:name=".ILoveNescot"> </activity> <activity android:name=".FurtherEducationCourses"> </activity> <activity android:name=".HigherEducationCourses"> </activity> <activity android:name=".EmployersTrainingCourses"> </activity> <activity android:name=".WebService"> </activity> <activity android:name=".CallService"> </activity> <activity android:name=".EmailService"> </activity> </application> <uses-sdk android:minSdkVersion="9" /> <uses-permission android:name="android.permission.CALL_PHONE"></uses-permission> <uses-permission android:name="android.permission.INTERNET" /> </manifest>

    Read the article

  • Why / When / How is this Android serviceBinder resetting to null?

    - by GaZ
    I've written a ListActivity for Android 2.1 which is used to display a list of event categories. As the user selects a category, the program calls a web service to retrieve a list of sub-events. For example, a top level event might be "soccer" and when the user selects this the web service would return various soccer associations (e.g. "english", "french", "german", etc.) and display them in a new list. The following code seems to work occasionally, however sometimes the call to the service (in EventsListTask) fails because the serviceBinder is null. How/Why does this happen? public class EventListsActivity extends ListActivity { private static final String EVENT_ID = "EventId"; private List<ListItem> eventList; private ArrayAdapter<ListItem> listItemArrayAdapter; private static final int LOADING_DIALOG = 1; private EventsListTask eventsListTask = null; private BFService serviceBinder; private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName componentName, IBinder iBinder) { Log.i("EventListsActivity", "service connected"); serviceBinder = ((BFService.BFBinder)iBinder).getService(); } public void onServiceDisconnected(ComponentName componentName) { Log.i("EventListsActivity", "service disconnected"); serviceBinder = null; } }; @Override public void onCreate(Bundle savedInstanceState) { Log.i("EventListsActivity", "onCreate"); super.onCreate(savedInstanceState); setContentView(R.layout.list); eventList = new ArrayList<ListItem>(); listItemArrayAdapter = new ArrayAdapter<ListItem>(this, R.layout.row, eventList); setListAdapter(listItemArrayAdapter); Intent bindIntent = new Intent(this, BFService.class); bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE); int eventId = getIntent().getIntExtra(EVENT_ID, -1); if (eventsListTask == null || eventsListTask.getStatus() == AsyncTask.Status.FINISHED) { eventsListTask = new EventsListTask(); eventsListTask.execute(eventId); } } @Override protected void onDestroy() { Log.i("EventListsActivity", "destroyed"); super.onDestroy(); unbindService(mConnection); } @Override protected void onListItemClick(ListView listView, View view, int position, long id) { super.onListItemClick(listView, view, position, id); ListItem selectedItem = (ListItem) listView.getAdapter().getItem(position); Intent intent; if (selectedItem.getMarketType() != null) { intent = new Intent(this, MarketActivity.class); intent.putExtra(EVENT_ID, selectedItem.getId()); startActivityIfNeeded(intent, -1); } else if (selectedItem.getId() != -1) { intent = new Intent(this, EventListsActivity.class); intent.putExtra(EVENT_ID, selectedItem.getId()); startActivityIfNeeded(intent, -1); } else { Log.e("EventListsActivity", "unexpected item selected!"); } } @Override protected Dialog onCreateDialog(int id) { switch (id) { case (LOADING_DIALOG) : AlertDialog.Builder loadingDialog = new AlertDialog.Builder(this); loadingDialog.setTitle("Please Wait..."); loadingDialog.setMessage("Communicating with remote service."); return loadingDialog.create(); } return null; } private class EventsListTask extends AsyncTask<Integer, Void, LoginStatusEnum> { @Override protected void onPreExecute() { showDialog(LOADING_DIALOG); } @Override protected void onPostExecute(LoginStatusEnum loginStatusEnum) { dismissDialog(LOADING_DIALOG); if (loginStatusEnum != null) { switch (loginStatusEnum) { case OK: for (ListItem item : eventList) { listItemArrayAdapter.add(item); } listItemArrayAdapter.notifyDataSetChanged(); break; } } } @Override protected LoginStatusEnum doInBackground(Integer... params) { LoginStatusEnum result = LoginStatusEnum.OK; Integer eventId = params[0]; if (serviceBinder != null) { try { if (eventId == null || eventId == -1) { eventList = serviceBinder.getActiveEventTypes(); } else { eventList = serviceBinder.getEvents(eventId); } } catch (WebServiceException wse) { result = LoginStatusEnum.valueOf(wse.getMessage()); } } else { Log.e("EventListsActivity", "serviceBinder is null!"); } return result; } } } EDIT: The serviceBinder appears to be set to null when I reach the bottom of a list, when I change the target intent to go to a different activity: intent = new Intent(this, MarketActivity.class); intent.putExtra(EVENT_ID, selectedItem.getId()); startActivity(intent); This new activity also uses the same background service (binds in the same way, etc.). Is there anything I need to watch out for when doing this? Am I calling the target intent incorrectly? EDIT2: Here's the output from LogCat when I start the activity which calls the service (this time the service failed straight away!): 04-02 07:02:49.147: INFO/ActivityManager(61): Starting activity: Intent { cmp=net.foobar.activity/.EventListsActivity } 04-02 07:02:49.257: INFO/EventListsActivity(353): onCreate 04-02 07:02:49.426: INFO/EventListsActivity(353): service connected 04-02 07:02:49.437: ERROR/EventListsActivity(353): serviceBinder is null!

    Read the article

  • Android TabHost: update tabs from tab's activity

    - by joshuadlillie
    I have a TabActivity and am going to have 3 or 4 tabs. In TabA, I would like to have an ExpandableListView, which will list products. I would like TabC to act as a sort of "shopping cart", probably with a ListView of itself. So, my question is: is there a way to interact with the TabHost from the Activity? I would like to be able to click a button inside of TabA and have it update and switch to TabC. Is this possible? Can I get the Tab's activities call it's parents methods?

    Read the article

  • Problem running android HelloTabWidget example - NullPointerException on addTab()

    - by Poindextrose
    I've tried the Tab Layout example, and I've also fixed the few typos in the example (and added all the activities to the manifest). However, when I run it on the emulator I get a NullPointerException on the first line that says tabHost.addTab(spec); So my question, of course, is. What is wrong with the example that would cause this exception? I'm using Eclipse Galileo and set the target package as Android 1.5. So far I've had no other problems with the other examples on the android dev site. package com.example.hellotabwidget; import android.app.TabActivity; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.widget.TabHost; public class HelloTabWidget extends TabActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) throws RuntimeException { super.onCreate(savedInstanceState); setContentView(R.layout.main); Resources res = getResources(); // Resource object to get Drawables TabHost tabHost = getTabHost(); // The activity TabHost TabHost.TabSpec spec; // Reusable TabSpec for each tab Intent intent; // Reusable Intent for each tab // Create an Intent to launch an Activity for the tab (to be reused) //final Context context = getApplicationContext(); intent = new Intent().setClass(this, ArtistsActivity.class); // Initialize a TabSpec for each tab and add it to the TabHost spec = tabHost.newTabSpec("artists").setIndicator("Artists", res.getDrawable(R.drawable.ic_tab_artists)) .setContent(intent); tabHost.addTab(spec); //******** NullPointerException after running this line // Do the same for the other tabs intent = new Intent().setClass(this, AlbumsActivity.class); spec = tabHost.newTabSpec("albums").setIndicator("Albums", res.getDrawable(R.drawable.ic_tab_artists)) .setContent(intent); tabHost.addTab(spec); intent = new Intent().setClass(this, SongsActivity.class); spec = tabHost.newTabSpec("songs").setIndicator("Songs", res.getDrawable(R.drawable.ic_tab_artists)) .setContent(intent); tabHost.addTab(spec); tabHost.setCurrentTabByTag("artists"); } } main.xml: <?xml version="1.0" encoding="utf-8"?> <TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp"> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp" /> </LinearLayout> </TabHost>

    Read the article

  • How to pass object from one activity to another in android

    - by kaibuki
    Hi I am trying to work on sending an object of my "Customer" class from one activity and display on other activity. the code for the customer class : `package com.kaibuki; public class Customer { private String firstName, lastName, Address; int Age; public Customer(String fname, String lname, int age, String address) { firstName = fname; lastName = lname; Age = age; Address = address; } public String printValues() { String data = null; data = "First Name :" + firstName + " Last Name :" + lastName + " Age : " + Age + " Address : " + Address; return data; } } I want to send its object from one activity to another and then display the data on the other activity. Please need urgent help. Thanks alot Kai`

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >