Search Results

Search found 416 results on 17 pages for 'onclicklistener'.

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

  • How to switch between views in android?

    - by aurezza
    I've tried several methods to switch between two views in my program. I've tried creating a new thread then have the view run for 5 seconds before creating intent to start my main activity. This is the code snippet from the said view class: mHelpThread = new Thread(){ @Override public void run(){ try { synchronized(this){ // Wait given period of time or exit on touch wait(5000); } } catch(InterruptedException ex){ } finish(); // Run next activity Intent intent = new Intent(Intent.ACTION_MAIN, null); intent.addCategory(Intent.CATEGORY_HOME); startActivity(intent); //stop(); } }; mHelpThread.start(); I can access the said view without error but it doesn't disappear after 5 seconds nor did it switched to main view when I even utilized an onTouchEvent() to detect touch on the screen of which it should have automatically closed. I've also tried adding a button on the said view to manually switch to main view: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.help); final HelpView helpView = this; final Button btnback = (Button) findViewById(R.id.back); btnback.setOnClickListener(new View.OnClickListener(){ public void onClick(View v) { Intent intent = new Intent(helpView, MainActivity.class); startActivity(intent); } }); } These codes worked, though, for creating a launcher for my program. So I thought that it would work the same if I added an option for help/rules(for the game) that would switch to another view. I've only since started using eclipse for android so pardon my lack of knowledge. Here is also the snippet from my manifest: <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="MainActivity" android:label="@string/title_activity_main"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> <intent-filter></intent-filter> </activity> <activity android:name="SplashScreen" android:theme="@style/Theme.Transparent"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <activity android:name="HelpView" android:theme="@style/Theme.Transparent"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.DEFAULT"/> </intent-filter> <intent-filter></intent-filter> </activity> </application>

    Read the article

  • android client not working [migrated]

    - by Syeda Zunairah
    i have a java client and c# server the server code is static Socket listeningSocket; static Socket socket; static Thread thrReadRequest; static int iPort = 4444; static int iConnectionQueue = 100; static void Main(string[] args) { Console.WriteLine(IPAddress.Parse(getLocalIPAddress()).ToString()); try { listeningSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //listeningSocket.Bind(new IPEndPoint(0, iPort)); listeningSocket.Bind(new IPEndPoint(IPAddress.Parse(getLocalIPAddress()), iPort)); listeningSocket.Listen(iConnectionQueue); thrReadRequest = new Thread(new ThreadStart(getRequest)); thrReadRequest.Start(); } catch (Exception e) { Console.WriteLine("Winsock error: " + e.ToString()); //throw; } } static private void getRequest() { int i = 0; while (true) { i++; Console.WriteLine("Outside Try i = {0}", i.ToString()); try { socket = listeningSocket.Accept(); // Receiving //byte[] rcvLenBytes = new byte[4]; //socket.Receive(rcvLenBytes); //int rcvLen = System.BitConverter.ToInt32(rcvLenBytes, 0); //byte[] rcvBytes = new byte[rcvLen]; //socket.Receive(rcvBytes); //String formattedBuffer = System.Text.Encoding.ASCII.GetString(rcvBytes); byte[] buffer = new byte[socket.SendBufferSize]; int iBufferLength = socket.Receive(buffer, 0, buffer.Length, 0); Console.WriteLine("Received {0}", iBufferLength); Array.Resize(ref buffer, iBufferLength); string formattedBuffer = Encoding.ASCII.GetString(buffer); Console.WriteLine("Data received by Client: {0}", formattedBuffer); if (formattedBuffer == "quit") { socket.Close(); listeningSocket.Close(); Environment.Exit(0); } Console.WriteLine("Inside Try i = {0}", i.ToString()); Thread.Sleep(500); } catch (Exception e) { //socket.Close(); Console.WriteLine("Receiving error: " + e.ToString()); Console.ReadKey(); //throw; } finally { socket.Close(); //listeningsocket.close(); } } } static private string getLocalIPAddress() { IPHostEntry host; string localIP = ""; host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { localIP = ip.ToString(); break; } } return localIP; } } and the jave android code is private TCPClient mTcpClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText editText = (EditText) findViewById(R.id.edit_message); Button send = (Button)findViewById(R.id.sendbutton); // connect to the server new connectTask().execute(""); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String message = editText.getText().toString(); //sends the message to the server if (mTcpClient != null) { mTcpClient.sendMessage(message); } editText.setText(""); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } public class connectTask extends AsyncTask<String,String,TCPClient> { @Override protected TCPClient doInBackground(String... message) { mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() { @Override public void messageReceived(String message) { publishProgress(message); } }); mTcpClient.run(); return null; } @Override protected void onProgressUpdate(String... values) { super.onProgressUpdate(values); } } } when i run the server it gives output of try i=1. can any one tell me what to do next

    Read the article

  • Null Validation on EditText box in Alert Dialog - Android

    - by LordSnoutimus
    Hi, I am trying to add some text validation to an edit text field located within an alert dialog box. It prompts a user to enter in a name. I want to add some validation so that if what they have entered is blank or null, it does not do anything apart from creating a Toast saying error. So far I have: AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Record New Track"); alert.setMessage("Please Name Your Track:"); // Set an EditText view to get user input final EditText trackName = new EditText(this); alert.setView(trackName); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String textString = trackName.getText().toString(); // Converts the value of getText to a string. if (textString != null && textString.trim().length() ==0) { Context context = getApplicationContext(); CharSequence error = "Please enter a track name" + textString; int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, error, duration); toast.show(); } else { SQLiteDatabase db = waypoints.getWritableDatabase(); ContentValues trackvalues = new ContentValues(); trackvalues.put(TRACK_NAME, textString); trackvalues.put(TRACK_START_TIME,tracktimeidentifier ); insertid=db.insertOrThrow(TRACK_TABLE_NAME, null, trackvalues); } But this just closes the Alert Dialog and then displays the Toast. I want the Alert Dialog to still be on the screen. Thanks

    Read the article

  • Android visibility issue with checkbox

    - by fxi
    Hi all! I´m using a checkbox in my code that when its checked it makes a textview and a editText visibles, but if I uncheck de checkbox they continue being visible instead of dissapear. Here is the code: final CheckBox save = (CheckBox) findViewById(R.id.checkbox); save.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Perform action on clicks, depending on whether it's now checked if (((CheckBox) v).isChecked()) { nameText.setVisibility(1); editName.setVisibility(1); } else { nameText.setVisibility(0); editName.setVisibility(0); } } }); And part of the xml which is inside an Relative Layout: <LinearLayout android:id="@+id/linearLayout3" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below = "@+id/linearLayout2"> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/name" android:visibility="invisible"/> <EditText android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:visibility="invisible"/> <CheckBox android:id="@+id/checkbox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/save" /> </LinearLayout> What should i do to make the textView and EditText dissapear when i uncheck the checkbox? Thank you!

    Read the article

  • how to add item to Spinner's ArrayAdapter?

    - by allen-c
    i had a EditText , a button and a spinner . When click the button , the spinner will add a new item with name you entered in the EditText. But here is the question, my adapter.add() method seems doesn't work...here is my code: public class Spr extends Activity { Button bt1; EditText et; ArrayAdapter<CharSequence> adapter; Spinner spinner; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); bt1 = (Button)this.findViewById(R.id.bt1); et = (EditText)this.findViewById(R.id.et); spinner = (Spinner)this.findViewById(R.id.spr); adapter = ArrayAdapter.createFromResource( this, R.array.planets_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); bt1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String temp = et.getText().toString(); adapter.add(temp); adapter.notifyDataSetChanged(); spinner.setAdapter(adapter); } }); spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { Toast.makeText(parent.getContext(), "The planet is " + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show(); } @Override public void onNothingSelected(AdapterView<?> arg0) { }}); } }

    Read the article

  • Process: Unable to start service com.google.android.gms.checkin.CheckinService with Intent

    - by AndyRoid
    I'm trying to build a Google map application but keep receiving this in my LogCat. I have all the permissions and meta-data set in my manifest, but am still dumbfounded by this error. Have looked everywhere on SO for this specific error but found nothing relating to com.google.android.gms.checkin A little bit about my structural hierarchy. MainActivity extends ActionBarActivity with three tabs underneath actionbar. Each tab has it's own fragment. On the gMapFragment I create a GPSTrack object from my GPSTrack class which extends Service and implements LocationListener. The problem is that when I start the application I get this message: I have all my libraries imported properly and I even added the google-play-services.jar into my libs folder. I also installed Google Play Services APKs through CMD onto my emulator. Furthermore the LocationManager lm = = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); in my GPSTrack class always returns null. Why is this and how can I fix these issues? Would appreciate an explanation along with solution too, I want to understand what's going on here. ============== Code: gMapFragment.java public class gMapFragment extends SupportMapFragment { private final String TAG = "gMapFragment"; private GoogleMap mMap; protected SupportMapFragment mapFrag; private Context mContext = getActivity(); private static View view; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (view != null) { ViewGroup parent = (ViewGroup) view.getParent(); if (parent != null) { parent.removeView(view); } } try { super.onCreateView(inflater, container, savedInstanceState); view = inflater.inflate(R.layout.fragment_map, container, false); setupGoogleMap(); } catch (Exception e) { /* * Map already there , just return as view */ } return view; } private void setupGoogleMap() { mapFrag = (SupportMapFragment) getFragmentManager().findFragmentById( R.id.mapView); if (mapFrag == null) { FragmentManager fragManager = getFragmentManager(); FragmentTransaction fragTransaction = fragManager .beginTransaction(); mapFrag = SupportMapFragment.newInstance(); fragTransaction.replace(R.id.mapView, mapFrag).commit(); } if (mapFrag != null) { mMap = mapFrag.getMap(); if (mMap != null) { setupMap(); mMap.setOnMapClickListener(new OnMapClickListener() { @Override public void onMapClick(LatLng point) { // TODO your click stuff on map } }); } } } @Override public void onAttach(Activity activity) { super.onAttach(activity); Log.d("Attach", "on attach"); } @Override public void onDetach() { super.onDetach(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); } @Override public void onDestroy() { super.onDestroy(); } private void setupMap() { GPSTrack gps = new GPSTrack(mContext); // Enable MyLocation layer of google map mMap.setMyLocationEnabled(true); Log.d(TAG, "MyLocation enabled"); // Set Map type mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); // Grab current location **ERROR HERE/Returns Null** Location location = gps.getLocation(); Log.d(TAG, "Grabbing location..."); if (location != null) { Log.d(TAG, "location != null"); // Grab Latitude and Longitude double latitude = location.getLatitude(); double longitude = location.getLongitude(); Log.d(TAG, "Getting lat, long.."); // Initialize LatLng object LatLng latLng = new LatLng(latitude, longitude); Log.d(TAG, "LatLng initialized"); // Show current location on google map mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); // Zoom in on google map mMap.animateCamera(CameraUpdateFactory.zoomTo(20)); mMap.addMarker(new MarkerOptions().position( new LatLng(latitude, longitude)).title("You are here.")); } else { gps.showSettingsAlert(); } } } GPSTrack.java public class GPSTrack extends Service implements LocationListener{ private final Context mContext; private boolean isGPSEnabled = false; //See if network is connected to internet private boolean isNetworkEnabled = false; //See if you can grab the location private boolean canGetLocation = false; protected Location location = null; protected double latitude; protected double longitude; private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 Meters private static final long MINIMUM_TIME_CHANGE_FOR_UPDATES = 1000 * 60 * 1; //1 minute protected LocationManager locationManager; public GPSTrack(Context context) { this.mContext = context; getLocation(); } public Location getLocation() { try { //Setup locationManager for controlling location services **ERROR HERE/Return Null** locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); //See if GPS is enabled isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); //See if Network is connected to the internet or carrier service isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (!isGPSEnabled && !isNetworkEnabled) { Toast.makeText(getApplicationContext(), "No Network Provider Available", Toast.LENGTH_SHORT).show(); } else { this.canGetLocation = true; if (isNetworkEnabled) { locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MINIMUM_TIME_CHANGE_FOR_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("GPS", "GPS Enabled"); if (locationManager != null) { location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } } } catch (Exception e) { e.printStackTrace(); } return location; } public void stopUsingGPS() { if (locationManager != null) { locationManager.removeUpdates(GPSTrack.this); } } public double getLatitude() { if (location != null) { latitude = location.getLatitude(); } return latitude; } public double getLongitude() { if (location != null) { longitude = location.getLongitude(); } return longitude; } public boolean canGetLocation() { return this.canGetLocation; } public void showSettingsAlert() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); //AlertDialog title alertDialog.setTitle("GPS Settings"); //AlertDialog message alertDialog.setMessage("GPS is not enabled. Do you want to go to Settings?"); alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); mContext.startActivity(i); } }); alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.cancel(); } }); alertDialog.show(); } @Override public void onLocationChanged(Location location) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } } logcat 06-08 22:35:03.441: E/AndroidRuntime(1370): FATAL EXCEPTION: main 06-08 22:35:03.441: E/AndroidRuntime(1370): Process: com.google.android.gms, PID: 1370 06-08 22:35:03.441: E/AndroidRuntime(1370): java.lang.RuntimeException: Unable to start service com.google.android.gms.checkin.CheckinService@b1094e48 with Intent { cmp=com.google.android.gms/.checkin.CheckinService }: java.lang.SecurityException: attempting to read gservices without permission: Neither user 10053 nor current process has com.google.android.providers.gsf.permission.READ_GSERVICES. 06-08 22:35:03.441: E/AndroidRuntime(1370): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2719) 06-08 22:35:03.441: E/AndroidRuntime(1370): at android.app.ActivityThread.access$2100(ActivityThread.java:135) 06-08 22:35:03.441: E/AndroidRuntime(1370): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293) 06-08 22:35:03.441: E/AndroidRuntime(1370): at android.os.Handler.dispatchMessage(Handler.java:102) 06-08 22:35:03.441: E/AndroidRuntime(1370): at android.os.Looper.loop(Looper.java:136) 06-08 22:35:03.441: E/AndroidRuntime(1370): at android.app.ActivityThread.main(ActivityThread.java:5017) 06-08 22:35:03.441: E/AndroidRuntime(1370): at java.lang.reflect.Method.invokeNative(Native Method) 06-08 22:35:03.441: E/AndroidRuntime(1370): at java.lang.reflect.Method.invoke(Method.java:515) 06-08 22:35:03.441: E/AndroidRuntime(1370): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 06-08 22:35:03.441: E/AndroidRuntime(1370): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 06-08 22:35:03.441: E/AndroidRuntime(1370): at dalvik.system.NativeStart.main(Native Method) 06-08 22:35:03.441: E/AndroidRuntime(1370): Caused by: java.lang.SecurityException: attempting to read gservices without permission: Neither user 10053 nor current process has com.google.android.providers.gsf.permission.READ_GSERVICES. 06-08 22:35:03.441: E/AndroidRuntime(1370): at android.app.ContextImpl.enforce(ContextImpl.java:1685) 06-08 22:35:03.441: E/AndroidRuntime(1370): at android.app.ContextImpl.enforceCallingOrSelfPermission(ContextImpl.java:1714) 06-08 22:35:03.441: E/AndroidRuntime(1370): at android.content.ContextWrapper.enforceCallingOrSelfPermission(ContextWrapper.java:572) 06-08 22:35:03.441: E/AndroidRuntime(1370): at imq.c(SourceFile:107) 06-08 22:35:03.441: E/AndroidRuntime(1370): at imq.a(SourceFile:121) 06-08 22:35:03.441: E/AndroidRuntime(1370): at imq.a(SourceFile:227) 06-08 22:35:03.441: E/AndroidRuntime(1370): at bwq.c(SourceFile:166) 06-08 22:35:03.441: E/AndroidRuntime(1370): at com.google.android.gms.checkin.CheckinService.a(SourceFile:237) 06-08 22:35:03.441: E/AndroidRuntime(1370): at com.google.android.gms.checkin.CheckinService.onStartCommand(SourceFile:211) 06-08 22:35:03.441: E/AndroidRuntime(1370): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2702) AndroidManifest <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="19" /> <uses-permission android:name="com.curio.permission.MAPS_RECEIVE" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /> <uses-feature android:name="android.hardware.camera" android:required="true" /> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.app.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AI........................" /> </application>

    Read the article

  • Alert Dialog with custom layout failing

    - by cmptrer
    So this is related to a question I asked earlier. I am trying to display an alert using a specified layout. My layout is: And the code to call and show the alert dialog is: Context mContext = getApplicationContext(); AlertDialog.Builder builder = new AlertDialog.Builder(mContext); // use a custom View defined in xml View view = LayoutInflater.from(mContext).inflate(R.layout.sell_dialog, (ViewGroup) findViewById(R.id.layout_root)); builder.setView(view); builder.setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // do whatever you want with the input } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); When I run it I get an error saying: Uncaught handler: thread main exiting due to uncaught exception android.view.WindowManager$NadTokenException: Unable to add window -- token null is not for an application I've looked through the android development site and can't figure it out. I think I'm just missing something obvious but the fix isn't jumping out at me. How can I get this alert dialog to display?

    Read the article

  • Android - Views in Custom Compound Component are not inflated (findByView returns null)

    - by Julian Arz
    I have made a Custom Component in XML, consisting of a button with an imageview stacked on top of it: <myapp.widget.ClearableCaptionedButton xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/ccbutton_button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_vertical|left" android:textAppearance="?android:attr/textAppearanceMedium" android:background="@android:drawable/edit_text"/> <ImageView android:id="@+id/ccbutton_clear" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="5dip" android:layout_alignRight="@id/ccbutton_button" android:layout_alignTop="@id/ccbutton_button" android:layout_alignBottom="@id/ccbutton_button"/> </myapp.widget.ClearableCaptionedButton> extract of java source code: public class ClearableCaptionedButton extends RelativeLayout implements OnClickListener { ... public ClearableCaptionedButton(Context context, AttributeSet attrs) { super(context, attrs); // some stuff that works fine } .. protected void onFinishInflate() { super.onFinishInflate(); mButton = (Button) findViewById(R.id.ccbutton_button); mClear = (ImageView) findViewById(R.id.ccbutton_clear); mButton.setText(""); // error here: mButton == null } My problem is similar to this one. When i try to find the views inside the custom compound, findViewById returns null. But, as you can see, i already added super(context, attrs); to the constructor. i am using the custom component directly in xml layout, like this: <LinearLayout> <!-- some stuff --> <de.pockettaxi.widget.ClearableCaptionedButton android:layout_width="fill_parent" android:layout_height="wrap_content" app:caption="to"/> </LinearLayout> can anybody spot something? thanks.

    Read the article

  • ListView with Custom ArrayAdapter not updating

    - by Intelwalk
    I am currently trying to return a custom view of a textview, chrono, and checkbox. I have overriden the getView method but I am not sure if I did it correctly. I would appreciate some comments on the arrayadapter. It currently does not update in my application. Thanks! main java public class TaskTracker extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button addButton; addButton=(Button)findViewById(R.id.button1); ListView myListView= (ListView)findViewById(R.id.listView1); final EditText myEditText= (EditText)findViewById(R.id.editText1) ; //final ArrayList<String> taskitems = new ArrayList<String>(); final TTAdapterView aa = new TTAdapterView(this); // aa = new ArrayAdapter<String>(this, 0); myListView.setAdapter(aa); addButton.setOnClickListener(new OnClickListener(){ public void onClick(View v){ aa.add(myEditText.getText().toString()); //taskitems.add(count, myEditText.getText().toString()); aa.notifyDataSetChanged(); myEditText.setText(""); myEditText.requestFocus(); } }); } } ArrayAdapter public class TTAdapterView extends ArrayAdapter<String> { public View v; public TTAdapterView(Context context){ super(context,R.layout.row); } @Override public View getView(int position, View convertView, ViewGroup parent){ this.v = convertView; if(v==null){ LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.row, null); } return v; }

    Read the article

  • Nested Linear layout only shows first view after being set from gone to visible in Android

    - by Adam
    Hi guys, I am developing an Android app but I'm still pretty new. I want to have a button, and when you push that button, a few TextViews and Buttons will appear. So I have a main linear layout, and then another linear layout nested inside containing the things I want hidden. I have the nested linear layout set to android:visibility="gone". The problem I am having is that it only shows the first item inside the hidden linear layout instead of all of them. The way I try to make it appear is vgAddView = (ViewGroup)findViewById(R.id.add_details); btnAche.setOnClickListener(new OnClickListener(){ public void onClick(View v){ vgAddView.setVisibility(0); } }); My XML file is this <?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" > <Button android:text="@string/but_stomach_ache" android:id="@+id/but_stomach_ache" android:layout_width="fill_parent" android:layout_height="wrap_content"> </Button> <Button android:text="@string/but_food" android:id="@+id/but_food" android:layout_width="fill_parent" android:layout_height="wrap_content"> </Button> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/add_details" android:visibility="gone"> <TextView android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="@string/when_happen"> </TextView> <Button android:text="@string/happen_now" android:id="@+id/happen_now" android:layout_width="fill_parent" android:layout_height="wrap_content"> </Button> </LinearLayout> </LinearLayout>

    Read the article

  • android checkbox box issue

    - by raqz
    i have this check box in a alertdialog. when i try to check the state of the checkbox, the application force closes. any idea why? LayoutInflater factory = LayoutInflater.from(NewActivity.this); final View textDisplayView = factory.inflate(R.layout.nearestlocs, null); final AlertDialog.Builder newAlert = new AlertDialog.Builder(NewActivity.this); newAlert.setView(textDisplayView); final CheckBox checkBoxLab = (CheckBox) findViewById(R.id.checkboxlab); newAlert.setPositiveButton("Display on Map", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if(checkBoxLab.isChecked()){ libDisplayFlag = true; } error log 03-13 08:01:58.273: ERROR/AndroidRuntime(6188): Uncaught handler: thread main exiting due to uncaught exception 03-13 08:01:58.292: ERROR/AndroidRuntime(6188): java.lang.NullPointerException 03-13 08:01:58.292: ERROR/AndroidRuntime(6188): at com.isproj3.NewActivity$3.onClick(NewActivity.java:158) 03-13 08:01:58.292: ERROR/AndroidRuntime(6188): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:158) 03-13 08:01:58.292: ERROR/AndroidRuntime(6188): at android.os.Handler.dispatchMessage(Handler.java:99) xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="horizontal" android:gravity="center" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1"> <CheckBox android:id="@+id/checkboxlib" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Library" android:gravity="left" android:textColor="#FF0000" android:paddingBottom="5px" android:textSize="07pt" android:checked="true" /> <TextView android:id="@+id/librarytext" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:paddingBottom="5px" android:textSize="8pt" /> </LinearLayout> </LinearLayout>

    Read the article

  • Spinner in Android crashing when visibilty changes while handling OnClick in a button

    - by Dave George
    I have a spinner in UI, which I want to hide when I handle onClick method for a button. But the application is crashing all the time. Is it that I can't use the setVisibility(View.Gone) on spinners (it is not written anywhere). If I comment it out, then application run fine. I am getting NullPointerException and I am using RelativeLayout. Also, can I do this: public void onItemSelected(AdapterView<?> arg0, View view, int pos, long arg3) { // TODO Auto-generated method stub Toast.makeText(SpinnerActivity.this,selected , Toast.LENGTH_SHORT).show(); spinner.setVisibility(View.GONE); } } Spinner code fore reference: itemsCity=getResources().getStringArray(R.array.cities_array); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.cities_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerCity.setAdapter(adapter); And here is Button code: private class BtClickListner implements View.OnClickListener{ @Override public void onClick(View v) { essEditText.setVisibility(View.GONE); spinnerCity.setEnabled(false);// Getting exception here // Also tried spinnerCity.setVisibility(View.GONE);// Exception SameBt.setVisibility(View.GONE);// This is same button for which I am handliing event, but it allows me to change tis property at run time. }

    Read the article

  • How to call a new thread from button click

    - by Lynnooi
    Hi, I'm trying to call a thread on a button click (btn_more) but i cant get it right. The thread is to get some data and update the images. The problem i have is if i only update 4 or 5 images then it works fine. But if i load more than 5 images i will get a force close. At times when the internet is slow I will face the same problem too. Can please help me to solve this problem or provide me some guidance? Here is the error i got from LogCat: 04-19 18:51:44.907: ERROR/AndroidRuntime(1034): Uncaught handler: thread main exiting due to uncaught exception 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): java.lang.NullPointerException 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at mobile9.android.gallery.GalleryWallpapers.setWallpaperThumb(GalleryWallpapers.java:383) 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at mobile9.android.gallery.GalleryWallpapers.access$4(GalleryWallpapers.java:320) 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at mobile9.android.gallery.GalleryWallpapers$1.handleMessage(GalleryWallpapers.java:266) 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at android.os.Handler.dispatchMessage(Handler.java:99) 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at android.os.Looper.loop(Looper.java:123) 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at android.app.ActivityThread.main(ActivityThread.java:4310) 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at java.lang.reflect.Method.invokeNative(Native Method) 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at java.lang.reflect.Method.invoke(Method.java:521) 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 04-19 18:51:44.927: ERROR/AndroidRuntime(1034): at dalvik.system.NativeStart.main(Native Method) My Code: public class GalleryWallpapers extends Activity implements Runnable { public static String MODEL = android.os.Build.MODEL ; private static final String rootURL = "http://www.uploadhub.com/mobile9/gallery/c/"; private int wallpapers_count = 0; private int ringtones_count = 0; private int index = 0; private int folder_id; private int page; private int page_counter = 1; private String family; private String keyword; private String xmlURL = ""; private String thread_op = "xml"; private ImageButton btn_back; private ImageButton btn_home; private ImageButton btn_filter; private ImageButton btn_search; private TextView btn_more; private ProgressDialog pd; GalleryExampleHandler myExampleHandler = new GalleryExampleHandler(); Context context = GalleryWallpapers.this.getBaseContext(); Drawable image; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MODEL = "HTC Legend"; // **needs to be remove after testing** try { MODEL = URLEncoder.encode(MODEL,"UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.gallerywallpapers); Bundle b = this.getIntent().getExtras(); family = b.getString("fm").trim(); folder_id = Integer.parseInt(b.getString("fi")); keyword = b.getString("kw").trim(); page = Integer.parseInt(b.getString("page").trim()); WindowManager w = getWindowManager(); Display d = w.getDefaultDisplay(); final int width = d.getWidth(); final int height = d.getHeight(); xmlURL = rootURL + "wallpapers/1/?output=rss&afm=wallpapers&mdl=" + MODEL + "&awd=" + width + "&aht=" + height; if (folder_id > 0) { xmlURL = xmlURL + "&fi=" + folder_id; } pd = ProgressDialog.show(GalleryWallpapers.this, "", "Loading...", true, false); Thread thread = new Thread(GalleryWallpapers.this); thread.start(); btn_more = (TextView) findViewById(R.id.btn_more); btn_more.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { myExampleHandler.filenames.clear(); myExampleHandler.authors.clear(); myExampleHandler.duration.clear(); myExampleHandler.fileid.clear(); btn_more.setBackgroundResource(R.drawable.btn_more_click); page = page + 1; thread_op = "xml"; xmlURL = rootURL + "wallpapers/1/?output=rss&afm=wallpapers&mdl=" + MODEL + "&awd=" + width + "&aht=" + height; xmlURL = xmlURL + "&pg2=" + page; index = 0; pd = ProgressDialog.show(GalleryWallpapers.this, "", "Loading...", true, false); Thread thread = new Thread(GalleryWallpapers.this); thread.start(); } }); } public void run() { if(thread_op.equalsIgnoreCase("xml")){ readXML(); } else if(thread_op.equalsIgnoreCase("getImg")){ getWallpaperThumb(); } handler.sendEmptyMessage(0); } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { int count = 0; if (!myExampleHandler.filenames.isEmpty()){ count = myExampleHandler.filenames.size(); } count = 6; if(thread_op.equalsIgnoreCase("xml")){ pd.dismiss(); thread_op = "getImg"; btn_more.setBackgroundResource(R.drawable.btn_more); } else if(thread_op.equalsIgnoreCase("getImg")){ setWallpaperThumb(); index++; if (index < count){ Thread thread = new Thread(GalleryWallpapers.this); thread.start(); } } } }; private void readXML(){ if (xmlURL.length() != 0) { try { /* Create a URL we want to load some xml-data from. */ URL url = new URL(xmlURL); /* Get a SAXParser from the SAXPArserFactory. */ SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); /* Get the XMLReader of the SAXParser we created. */ XMLReader xr = sp.getXMLReader(); /* * Create a new ContentHandler and apply it to the * XML-Reader */ xr.setContentHandler(myExampleHandler); /* Parse the xml-data from our URL. */ xr.parse(new InputSource(url.openStream())); /* Parsing has finished. */ /* * Our ExampleHandler now provides the parsed data to * us. */ ParsedExampleDataSet parsedExampleDataSet = myExampleHandler .getParsedData(); } catch (Exception e) { //showDialog(DIALOG_SEND_LOG); } } } private void getWallpaperThumb(){ int i = this.index; if (!myExampleHandler.filenames.elementAt(i).toString().equalsIgnoreCase("")){ image = ImageOperations(context, myExampleHandler.thumbs.elementAt(i).toString(), "image.jpg"); } } private void setWallpaperThumb(){ int i = this.index; if (myExampleHandler.filenames.elementAt(i).toString() != null) { String file_info = myExampleHandler.filenames.elementAt(i).toString(); String author = "\nby " + myExampleHandler.authors.elementAt(i).toString(); final String folder = myExampleHandler.folder_id.elementAt(folder_id).toString(); final String fid = myExampleHandler.fileid.elementAt(i).toString(); ImageView imgView = new ImageView(context); TextView tv_filename = null; TextView tv_author = null; switch (i + 1) { case 1: imgView = (ImageView) findViewById(R.id.image1); tv_filename = (TextView) findViewById(R.id.filename1); tv_author = (TextView) findViewById(R.id.author1); break; case 2: imgView = (ImageView) findViewById(R.id.image2); tv_filename = (TextView) findViewById(R.id.filename2); tv_author = (TextView) findViewById(R.id.author2); break; case 3: imgView = (ImageView) findViewById(R.id.image3); tv_filename = (TextView) findViewById(R.id.filename3); tv_author = (TextView) findViewById(R.id.author3); break; case 4: . . . . . case 10: imgView = (ImageView) findViewById(R.id.image10); tv_filename = (TextView) findViewById(R.id.filename10); tv_author = (TextView) findViewById(R.id.author10); break; } if (image.getIntrinsicHeight() > 0) { imgView.setImageDrawable(image); } else { imgView.setImageResource(R.drawable.default_wallpaper); } tv_filename.setText(file_info); tv_author.setText(author); imgView.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { // Perform action on click } }); } } private Drawable ImageOperations(Context ctx, String url, String saveFilename) { try { InputStream is = (InputStream) this.fetch(url); Drawable d = Drawable.createFromStream(is, "src"); return d; } catch (MalformedURLException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } } }

    Read the article

  • Android: Can not send http post

    - by jpartogi
    Hi all, I've been banging my head trying to figure out how to send a post method in Android. This is how my code look like: public class HomeActivity extends Activity implements OnClickListener { private TextView textView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); textView = (TextView) findViewById(R.id.text); Button button = (Button)findViewById(R.id.button); button.setOnClickListener(this); } @Override public void onClick(View view) { HttpPost httpMethod = new HttpPost("http://www.example.com/"); httpMethod.addHeader("Accept", "text/html"); httpMethod.addHeader("Content-Type", "application/xml"); AndroidHttpClient client = AndroidHttpClient.newInstance("Android"); String result = null; try { HttpResponse response = client.execute(httpMethod); textView.setText(response.toString()); HttpEntity entity = response.getEntity(); Log.i(HomeActivity.class.toString(), result); textView.setText("Invoked webservice"); } catch (IOException e) { e.printStackTrace(); Log.e(HomeActivity.class.toString(), e.getMessage()); textView.setText("Something wrong:" + e.getMessage()); } } } What am I doing wrong here? Is there anything that I may need to configure from the Android emulator to get this working? Thank you for your help.

    Read the article

  • findViewById returns null for EditText

    - by jayesh
    public class MainActivity extends Activity { private EditText editText; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); editText = (EditText) findViewById(R.id.etext); if(editText == null) { Log.v("editText", "booohooo"); } else { Log.v("editText", "Success"); } final Button button = (Button) findViewById(R.id.gobutton); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(editText != null) { Log.v("editText", "is not NULL"); } else { Log.v("editText", "is NULL :("); } // Perform action on click if(editText != null) { editText.getText(); } else { Log.v("editText", "is NULL"); } Log.v("url", editText.getText().toString().trim()); Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(editText.getText().toString().trim())); startActivity(browserIntent); } }); } } <?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" > <TextView android_id="@+id/websiteurlheading" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Enter web site URL" /> <EditText android_id="@+id/etext" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@id/websiteurlheading" /> <Button android:id="@+id/gobutton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Enter" /> </LinearLayout> Any help is appreciated.

    Read the article

  • how to read image uri in to byte conversion in android image upload in sdcard

    - by satyamurthy
    public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button b1 = (Button) findViewById(R.id.Button01); b1.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub startActivityForResult(new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), 1); } }); } public void onActivityResult(int requestCode,int resultCode,Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { Uri selectedImage = data.getData(); Cursor cur = PhotoImage.this.managedQuery(selectedImage, null, null, null, null); if(cur.moveToFirst()) { File Img = new File(selectedImage+inFileType); try { FileInputStream fis = new FileInputStream(Img); Bitmap bi = BitmapFactory.decodeStream(fis); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bi.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] data1 = baos.toByteArray(); for (int i = 0; i < data1.length; i++) { System.out.print(""+data1[i]); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } this code not i am implementing file not found error please help some suggition

    Read the article

  • Play and Stop in One button

    - by Ardi
    i'm newbie, i'm tried to make play audio play and stop for 1 button only, but i'm in trouble now. if i touch a button when audio is playing, it doesn't stop, even playing audio again and make a double sound. here's my code public class ProjectisengActivity extends Activity{ ImageButton mainkan; MediaPlayer mp; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.test2); mainkan=(ImageButton)findViewById(R.id.imageButton1); mainkan.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v){ go(); } }); public void go(){ mp=MediaPlayer.create(ProjectisengActivity.this, R.raw.test); if(mp.isPlaying()){ mp.stop(); try { mp.prepare(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mp.seekTo(0); } else { mp.start(); } i'm create for android 3.0 (HoneyComb) thanks for help

    Read the article

  • Is there a better way to refresh WebView?

    - by cdg
    Hi all. Ok. I have looked EVERYWHERE and my little brain just can't understand a better way to refresh an activity. Any suggestions that I can understand would be great. :) Here is the java code: package com.dge.dges; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.webkit.WebView; import android.widget.Button; public class dgeActivity extends Activity { WebView mWebView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mWebView = (WebView) findViewById(R.id.webview); mWebView.getSettings(); mWebView.loadUrl("http://www.websitehere.php"); Button newButton = (Button)findViewById(R.id.new_button); newButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(dgeActivity.this, dgeActivity.class); startActivity(intent); } }); } } And here is the main.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/RelativeLayout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#000000" > <WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:scrollbars="none" /> <Button android:id="@+id/new_button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:text="Refresh" /> </RelativeLayout> I don't like the idea of just re-stacking activity after activity. There has to be an easier way to refresh the webview. Please help. :)

    Read the article

  • Declaring Intent Filter in android

    - by Rahul Varma
    Hi, I have problem in declaring the intents on my app. I have a form with text fields and spinner. I have added a button which onClick must display Datepicker. I have declared the DatePicker as a new class and added to intent onCLick. date.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent i=new Intent(SendMail.this,DatePicker.class); startActivity(i); } }); In manifest i have declared <activity android:name=".DatePicker"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> Now the problem is when i click the button the whole form is getting reset and all the spinner values are getting vanished. This must be because of declaring the intent wrongly. So, can anyone specify how to declare my intent so that the DatePicker will be called on the main form iteself

    Read the article

  • Close application on error

    - by poke
    I’m currently writing an application for the Android platform that requires a mounted SD card (or ExternalStorage). I know that it might not be the best way to require something like that, but the application will work with quite a lot of data, and I don’t even want to think about storing that on the device’s storage. Anyway, to ensure that the application won’t run without the external storage, I do a quick check in the activity’s onCreate method. If the card is not mounted, I want to display an error message and then quit the application. My current approach looks like this: public void onCreate ( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); setContentView( R.layout.main ); try { // initialize data storage // will raise an exception if it fails, or the SD card is not mounted // ... } catch ( Exception e ) { AlertDialog.Builder builder = new AlertDialog.Builder( this ); builder .setMessage( "There was an error: " + e.getMessage() ) .setCancelable( false ) .setNeutralButton( "Ok.", new DialogInterface.OnClickListener() { public void onClick ( DialogInterface dialog, int which ) { MyApplication.this.finish(); } } ); AlertDialog error = builder.create(); error.show(); return; } // continue ... } When I run the application, and the exception gets raised (I raise it manually to check if everything works), the error message is displayed correctly. However when I press the button, the application closes and I get an Android error, that the application was closed unexpectedly (and I should force exit). I read some topics before on closing an application, and I know that it maybe shouldn’t happen like that. But how should I instead prevent the application from continuing to run? How do you close the application correctly when an error occurs?

    Read the article

  • Playing Multiple sounds at the same time in Android

    - by Wrapper
    I am unable to use the following to code to play multiple sounds/beeps simultaneously. In my onclicklistener I have added ... public void onClick(View v) { mSoundManager.playSound(1); mSoundManager.playSound(2); } ... But this plays only one sound at a time, sound with index 1 followed by sound with index 2. How can I play atleast 2 sounds simultaneously using this code whenever there is an onClick() event? public class SoundManager { private SoundPool mSoundPool; private HashMap<Integer, Integer> mSoundPoolMap; private AudioManager mAudioManager; private Context mContext; public SoundManager() { } public void initSounds(Context theContext) { mContext = theContext; mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0); mSoundPoolMap = new HashMap<Integer, Integer>(); mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE); } public void addSound(int Index,int SoundID) { mSoundPoolMap.put(1, mSoundPool.load(mContext, SoundID, 1)); } public void playSound(int index) { int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f); } public void playLoopedSound(int index) { int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, -1, 1f); } }

    Read the article

  • Streaming Media Player Tutorial Stops Unexpectedly. How Should I Debug (And Other Questions From A

    - by Danny
    Hello! I'm a fledgling in the Android and Eclipse ways. I was reading and downloaded the source code for a Streaming Media Player tutorial from Pocket Journey, here. However, when I try to run it through the "Run As..." or "Debug As..." features in Eclipse, the emulator reports: "Sorry! The application Android Tutorials (process com.pocketjourney.tutorials) has stopped unexpectedly. Please try again." Now, from stepping through the Tutorial 1 activity (for those of you that may be familiar with it), it seems something funky happens here: button.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Toast.makeText(Tutorial1.this, "Button Clicked",Toast.LENGTH_SHORT).show(); }}); My questions are: What's up with that line? Apparently, other comments haven't had this problem; am I missing some library that I should be downloading from someplace? How should I go about debugging this other than/in addition to stepping through code? I'm used to Visual Studio, which has a nice box with exception details for me to sift through and copy/paste to google with. Eclipse debugging showed a "No Source Code" page, or a list of exceptions. I've heard of something called LogCat; is that relevant here? Thanks in advance!

    Read the article

  • Puting contact number into field

    - by dfilkovi
    I have this code that has one button that let's me choose an entry from contacts, and passes that choesn contact to onActivityResult function. My question is how do I select data of that single contact when all that is passed is an Intent in data variable. That data variable, if converted to string shows something like "dat: content://contacts/people/4" so I see that selected contact is somehow passed, but what now? How to get that data? And also all I found by googling was examples with deprecated class People, so I don't know how too use new classes. Please help. Thank you. public class HelloAndroid extends Activity { private static final int CONTACT_ACTIVITY = 100; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final Button contactButton = (Button) findViewById(R.id.pick_contact_button); contactButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Uri uri = Uri.parse("content://contacts/people"); Intent contacts_intent = new Intent(Intent.ACTION_PICK, uri); startActivityForResult(contacts_intent, CONTACT_ACTIVITY); } }); } public void onActivityResult(int requestCode, int resultCode, Intent data){ super.onActivityResult(requestCode, resultCode, data); switch(requestCode){ case(CONTACT_ACTIVITY): { if(resultCode == Activity.RESULT_OK) { alertText(data.toString()); } break; } } } }

    Read the article

  • storing data at remote server using php

    - by VIPUL GOYAL
    I want to send data to php file and execute insert query in it to store data in database. When i execute this code, it executes but database does not get updated. Code of PHP file Java code------------------------------Remote.java------------------------------ public class Remote extends Activity { EditText name; Button s; String r; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); name= (EditText)findViewById(R.id.editText1); s=(Button)findViewById(R.id.button1); s.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { r = name.getText().toString(); ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuePair("username", r)); CustomHttpClient.executeHttpPost("http://vipul.eu5.org/abc.php", postParameters); //Enetr Your remote PHP,ASP, Servlet file link } catch (Exception e) { e.printStackTrace(); } } }); } } -----------------------------CustomHttpClient.java---------------------------- public class CustomHttpClient { private static HttpClient getHttpClient() { if (mHttpClient == null) { mHttpClient = new DefaultHttpClient(); final HttpParams params = mHttpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT); HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT); ConnManagerParams.setTimeout(params, HTTP_TIMEOUT); } return mHttpClient; } /** * Performs an HTTP Post request to the specified url with the * specified parameters. * * @param url The web address to post the request to * @param postParameters The parameters to send via the request * @return The result of the request * @throws Exception */ public static void executeHttpPost(String url, ArrayList postParameters) throws Exception { try { HttpClient client = getHttpClient(); HttpPost request = new HttpPost(url); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters); request.setEntity(formEntity); HttpResponse response = client.execute(request); } catch(Exception e) { } } }

    Read the article

  • Android Custom Dialog Class Title Problems

    - by y ramesh rao
    public class MessageDisplayDialog extends Dialog implements OnClickListener { public MessageDisplayDialog(Context context, String title, String message) { super(context); setTitle(title); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.color.default_text_color); Log.v(getClass().getSimpleName(), "MessageDisplayDialog"); LinearLayout objLinearLayout = new LinearLayout(context); LinearLayout objButtonLayout = new LinearLayout(context); TextView objMesaageView = new TextView(context); objMesaageView.setText(message); objMesaageView.setTextColor(Color.WHITE); objMesaageView.setGravity(Gravity.CENTER_HORIZONTAL); objMesaageView.setPadding(0, 0, 0, 10); Button okButton = new Button(context); okButton.setText(" OK "); okButton.setOnClickListener(this); okButton.setWidth(100); objButtonLayout.addView(okButton); objButtonLayout.setGravity(Gravity.CENTER_HORIZONTAL); objButtonLayout.setPadding(0, 5, 0, 0); objButtonLayout.setBackgroundColor(Color.LTGRAY); objLinearLayout.setOrientation(LinearLayout.VERTICAL); objLinearLayout.addView(objMesaageView); objLinearLayout.addView(objButtonLayout); setContentView(objLinearLayout); //LayoutParams param = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); //this.addContentView(objLinearLayout, param); } public void onClick(View v) { this.dismiss(); } } But the Dialog is not showing bar below the Title, how to crack it.

    Read the article

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