Search Results

Search found 383 results on 16 pages for 'toast'.

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

  • How to check if EditText has a value in Android / Java

    - by Allen Gingrich
    This should be simple, but I have tried if statements checking for null values and also ones checking the .length of it: EditText marketValLow = (EditText) findViewById(R.id.marketValLow); EditText marketValHigh = (EditText) findViewById(R.id.marketValHigh); if (marketValLow.getText().length() != 0 && marketValHigh.getText().length() != 0) { Intent intent = new Intent(); intent.setClass(v.getContext(), CurrentlyOwe.class); startActivity(intent); } else { Toast.makeText(CurrentMarketValue.this, "You need to enter a high AND low.", Toast.LENGTH_SHORT); } But it doesn't detect nothing was entered. Any ideas? Thanks!

    Read the article

  • Loop and ListView

    - by monomi
    I find a match with Regexp. How to correctly organize a loop, if more than one match and write it in the ListView? listAlbums = (ListView)findViewById(R.id.listAlbums); ... Pattern patternNameToId = Pattern.compile(kRegexp); String nameTo = "" Matcher matcherName = patternNameToId.matcher(response); if (matcherName.find()) { nameTo = matcherTopicTitle.group(2); albumsList = new ArrayList<String>(); albumsList.add(nameTo); ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, albumsList); listAlbums.setAdapter(adapter); } else Toast.makeText(context, "?? ???????", Toast.LENGTH_LONG).show();

    Read the article

  • How to get latitude and longitude position that stored in MySQL and use it in Android map application

    - by gunawan haruna
    I have tried to get the latitude and longitude position that was stored in MySQL. I want use the values to my Android map application. Here is my code: deskripsi.Java Button direction = (Button) findViewById (R.id.btnDir); direction.setOnClickListener(new OnClickListener(){ public void onClick(View arg0) { Intent z = getIntent(); des_lat = z.getExtras().getString("des_lat"); des_long = z.getExtras().getString("des_long"); Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?&daddr="+des_lat+","+des_long)); //("geo:37.827500,-122.481670")); startActivity(i); } }); And here is the content.Java private ListView list; int x; private String panjang[]; public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.kontent); super.initButtonSearch(); list = (ListView) findViewById(R.id.list); JSONObject jo; try { jo = new JSONObject(JsonKontent); JSONArray ja = jo.getJSONArray("result"); System.out.println("Panjang : " + ja.length()); if (ja.length() == 0) { Toast.makeText(Content.this, "Data tidak ada!", Toast.LENGTH_LONG).show(); finish(); } content_id = new String[ja.length()]; c_title = new String[ja.length()]; c_telephone = new String[ja.length()]; c_short_description = new String[ja.length()]; c_long_description = new String[ja.length()]; c_image1 = new String[ja.length()]; c_image2 = new String[ja.length()]; l_address = new String[ja.length()]; catagory_id = new String[ja.length()]; Location myLoc = new Location("sharedPreferences"); Location restLoc = new Location("restaurantTable"); l_latitude = new String[ja.length()]; l_longitude = new String[ja.length()]; c_name = new String[ja.length()]; panjang = new String[ja.length()]; for (x = 0; x < ja.length(); x++) { JSONObject joj = ja.getJSONObject(x); content_id[x] = joj.getString("content_id"); catagory_id[x] = joj.getString("catagory_id"); c_title[x] = joj.getString("c_title"); c_telephone[x] = joj.getString("c_telephone"); c_short_description[x] = joj.getString("c_short_description"); c_long_description[x] = joj.getString("c_long_description"); c_image1[x] = HTTPConnection.urlPicture + joj.getString("c_image1"); c_image2[x] = HTTPConnection.urlPicture + joj.getString("c_image2"); l_address[x] = joj.getString("l_address"); l_latitude[x] = joj.getString("l_latitude"); l_longitude[x] = joj.getString("l_longitude"); c_name[x] = joj.getString("c_name"); myLoc.setLatitude(myLatitude); myLoc.setLongitude(myLongitude); restLoc.setLatitude(Double.parseDouble(l_latitude[x])); restLoc.setLongitude(Double.parseDouble(l_longitude[x])); float f = myLoc.distanceTo(restLoc); int f_int = Math.round(f / 100); f = Float.valueOf(f_int) / 10; String dist = new DecimalFormat("#,##0.0").format(f); System.out.println("Panjang " + dist + " km"); panjang[x] = dist + " km"; } } catch (JSONException e) { Toast.makeText(Content.this, "Data yang dicari tidak ada!", Toast.LENGTH_LONG).show(); finish(); } PFCAdapter adapter = new PFCAdapter(this, c_image1, c_title, l_address, panjang); list.setAdapter(adapter); list.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub System.out.println("Content ID: " + Content.content_id[Deskripsi.id]); Deskripsi.id = arg2; waitDialog = ProgressDialog.show(Content.this, "Memuat", "Harap tunggu, sedang terhubung dengan server"); waitDialog.setIcon(R.drawable.iconnya); waitDialog.show(); new LihatRatingTask().execute(); } }); } class LihatRatingTask extends AsyncTask<Void, Void, Void> { protected Void doInBackground(Void... Arg0) { Deskripsi.jsonRating = HTTPConnection.openUrl(HTTPConnection.host + "lihat_rating.php?content_id=" + Content.content_id[Deskripsi.id]); Deskripsi.jsonSubCategory = HTTPConnection .openUrl(HTTPConnection.host + "sub_catagory_parameter.php?content_id=" + Content.content_id[Deskripsi.id]); RoutePath.place = HTTPConnection .LoadImageFromWeb(HTTPConnection.host + "Logo/" + image[Integer.valueOf(catagory_id[Deskripsi.id]) - 1]); Intent i = new Intent(Content.this, Deskripsi.class); i.putExtra("des_lat", l_latitude); i.putExtra("des_long", l_longitude); startActivity(i); waitDialog.dismiss(); return null; } protected void onPostExecute(Void result) { // TODO Auto-generated method stub super.onPostExecute(result); waitDialog.dismiss(); } } } The result is in destination EditText in maps application for Android "null,null" How to make it "destination_latitude, destination_longitude"? Help me please.

    Read the article

  • Android , Read in binary data and write it to file

    - by Shpongle
    Hi all , Im trying to read in image file from a server , with the code below . It keeps going into the exception. I know the correct number of bytes are being sent as I print them out when received. Im sending the image file from python like so #open the image file and read it into an object imgfile = open (marked_image, 'rb') obj = imgfile.read() #get the no of bytes in the image and convert it to a string bytes = str(len(obj)) #send the number of bytes self.conn.send( bytes + '\n') if self.conn.sendall(obj) == None: imgfile.flush() imgfile.close() print 'Image Sent' else: print 'Error' Here is the android part , this is where I'm having the problem. Any suggestions on the best way to go about receiving the image and writing it to a file ? //read the number of bytes in the image String noOfBytes = in.readLine(); Toast.makeText(this, noOfBytes, 5).show(); byte bytes [] = new byte [Integer.parseInt(noOfBytes)]; //create a file to store the retrieved image File photo = new File(Environment.getExternalStorageDirectory(), "PostKey.jpg"); DataInputStream dis = new DataInputStream(link.getInputStream()); try{ os =new FileOutputStream(photo); byte buf[]=new byte[1024]; int len; while((len=dis.read(buf))>0) os.write(buf,0,len); Toast.makeText(this, "File recieved", 5).show(); os.close(); dis.close(); }catch(IOException e){ Toast.makeText(this, "An IO Error Occured", 5).show(); } EDIT: I still cant seem to get it working. I have been at it since and the result of all my efforts have either resulted in a file that is not the full size or else the app crashing. I know the file is not corrupt before sending server side. As far as I can tell its definitely sending too as the send all method in python sends all or throws an exception in the event of an error and so far it has never thrown an exception. So the client side is messed up . I have to send the file from the server so I cant use the suggestion suggested by Brian .

    Read the article

  • Vertical Seek not progress value not showing on MainActivity textView

    - by Raju Gujarati
    I am try to display the progress value of the seekBar but when it comes to the execution, there is no update on the value being display on the TextView. I wonder what alternatives than putting two classes onto one big class in order to archive this aim ? The below is my code VerticalSeekBar.java package com.example.imagerotation; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.SeekBar; import android.widget.Toast; public class VerticalSeekBar extends SeekBar { public VerticalSeekBar(Context context) { super(context); } public VerticalSeekBar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public VerticalSeekBar(Context context, AttributeSet attrs) { super(context, attrs); } protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(h, w, oldh, oldw); } @Override protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(heightMeasureSpec, widthMeasureSpec); setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth()); } protected void onDraw(Canvas c) { c.rotate(-90); c.translate(-getHeight(), 0); super.onDraw(c); } @Override public boolean onTouchEvent(MotionEvent event) { if (!isEnabled()) { return false; } switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: case MotionEvent.ACTION_UP: int progress = getMax() - (int) (getMax() * event.getY() / getHeight()); setProgress(progress); onSizeChanged(getWidth(), getHeight(), 0, 0); //Toast.makeText(getContext(), String.valueOf(progress), Toast.LENGTH_SHORT).show(); break; case MotionEvent.ACTION_CANCEL: break; } return true; } } MainActvity.java package com.example.imagerotation; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class MainActivity extends Activity { private VerticalSeekBar seek; private TextView by; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); seek = (VerticalSeekBar)findViewById(R.id.seekBar1); by = (TextView)findViewById(R.id.textView1); by.setText(String.valueOf(seek.getProgress())); } }

    Read the article

  • how to control the width and height of default alert dialog in Android?

    - by sat
    AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Title"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); } }); AlertDialog alert = builder.create(); I am using above code to show alert dialog , By default it fills the screen in width and wrap_content in height. How to control the width and height of default alert dialog ? I tried , alert.getWindow().setLayout(100,100); // It dint work. How to get the layout params on the alert window and set manually the width and height ?

    Read the article

  • Fragment savedInstanceState is always null (Android support lib)

    - by Evgeny Egorov
    I wrote a simple test project, but I cant understand why I always receive savedInstanceState = null in lifecycle methods onCreate, onCreateView and onActivityCreated. I change the screen orientation, see the log, but state not saved. Tell me please where is my mistake. Thanks. The code of fragment class is: public class TestFragment extends Fragment { private String state = "1"; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (savedInstanceState != null) { //never works state = savedInstanceState.getString("state"); } //always prints 1 Toast.makeText(getActivity(), state, Toast.LENGTH_SHORT).show(); return inflater.inflate(R.layout.fragment_layout, container, false); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString("state", "2"); Log.e("", "saved 2"); } }

    Read the article

  • Paypal payments verify

    - by user2800899
    (sorry for my english). I have implemented Paypal sdk for android, it works fine! But maybe for my english I don´t understand what i have to do here: @Override protected void onActivityResult (int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION); if (confirm != null) { try { Log.i("paymentExample", confirm.toJSONObject().toString(4)); // TODO: send 'confirm' to your server for verification. // see https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/ // for more details. } catch (JSONException e) { Toast.makeText(this, "Ha ocurrido un error, inténtelo de nuevo en unos instantes", Toast.LENGTH_LONG).show(); IrActivityAnterior(); } } } I have read about it but I don´t know if I need to send a proof of payment to the person who has bought my app or if I only need to get this proof and save it. And the other question is how can I verify it? What steps I need to follow?? Thank you!!

    Read the article

  • download html source android?

    - by mars
    I'm trying to download a website source code and display it in a textbox but I seem to get an error and can't figure it out :s public void getHtml() throws ClientProtocolException, IOException { HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpGet httpGet = new HttpGet("http://www.spartanjava.com"); HttpResponse response = httpClient.execute(httpGet, localContext); String result = ""; BufferedReader reader = new BufferedReader( new InputStreamReader( response.getEntity().getContent() ) ); String line = null; while ((line = reader.readLine()) != null){ result += line + "\n"; Toast.makeText(activity.this, line.toString(), Toast.LENGTH_LONG).show(); } } how come this doesn't work and throw an IOException?

    Read the article

  • How to get radio button's id and convert to string?

    - by user3461659
    I am working in Android Studio and am trying to get the ID of the selected radio button and then store the ID in a string. Is this possible? I have tried replacing the .getText() method below with .getId() but it wont let me store it as a string: RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup); radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int checkedId) { RadioButton checkedRadioButton = (RadioButton) findViewById(checkedId); String text = checkedRadioButton.getText().toString(); Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show(); } });

    Read the article

  • Implicit Intent is not working [migrated]

    - by Sayem Siam
    I have a activity class named Notelist.In the Notelist class i have tried to insert a new note.For that i have used implicit Intent.But when i click to insert a new note it gives a run time error. public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_add: Log.d("sayem", "in case of fd"); Toast.makeText(this, "in the", Toast.LENGTH_LONG).show(); startActivity(new Intent(Intent.ACTION_INSERT, getIntent() .getData())); break; default: throw new IllegalArgumentException("not matched"); } return true; } And i have NoteEditor activity clas to Insert a new note. And here is my Androidmanifesto.xml file. <uses-sdk android:minSdkVersion="14" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:label="@string/app_name" android:name=".NotesList" > <intent-filter > <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <action android:name="android.intent.action.EDIT" /> <action android:name="android.intent.action.PICK" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.dir/vnd.google.note" /> </intent-filter> <intent-filter > <action android:name="android.intent.action.GET_CONTENT" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.item/vnd.google.note" /> </intent-filter> </activity> <activity android:name="NoteEditor" > <intent-filter> <action android:name="NoteEditor"></action> <action android:name="android.intent.action.INSERT" /> <action android:name="android.intent.action.PASTE" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="vnd.android.cursor.dir/vnd.google.note" /> </intent-filter> </activity> </application>

    Read the article

  • Silverlight Cream for April 27, 2010 -- #849

    - by Dave Campbell
    In this Issue: Mike Snow, Kunal Chowdhury, Giorgetti Alessandro, Alexander Strauss, Corey Schuman, Kirupa, John Papa, Miro Miroslavov, Michael Washington, and Jeremy Likness. Shoutouts: Erik Mork and crew have posted their latest This Week In Silverlight April 23 2010 The Silverlight Team announced Microsoft releases Silverlight-powered Windows Intune beta Jesse Liberty has posted his UK and Ireland Slides and Links The Expression Blend and Design Blog reports a Minor Update to The Expression Blend 4 Release Candidate From SilverlightCream.com: Silverlight Tip of the Day #6 – Toast Notifications Mike Snow has Tip #6 up today and it's about Toast notifications in OOB apps: Restrictions, creation, showing, and the code. Silverlight Tutorials Chapter 2: Introduction to Silverlight Application Development Part 2 of Kunal Chowdhury's Introductory tutorial set is up ... he's covering how to create a Silverlight project, what's contained in it, and creating a User Control. Silverlight, M-V-VM ... and IoC - part 3 Giorgetti Alessandro has part 3 of his Silverlight, IOC, and MVVM series up... this one with an example using the code discussed previously. The project is on CodePlex, and he's not done with the series. Application Partitioning with MEF, Silverlight and Windows Azure – Part I Alexander Strauss is discussing Silverlight and MEF for loosely-coupled and partitioned apps. He's also using Azure in this discussion. geekSpeak Recording - Five Key Developer Features in Expression Blend with Corey Schuman Check out the latest geekSpeak on Channel 9 where Corey Schuman talks about the 5 key Developer Features in Expression Blend that will improve your productivity. Using the ChangePropertyAction Kirupa is discussing and demonstrating ChangePropertyAction. Check out the demo near the top of the post, then read how to do it, and download the source. 3 Free Silverlight Demos John Papa blogged about the 2 demos (with source) that have been updated to SL4, and a new one all by Microsoft Luminaries Karen Corby, Adam Kinney, Mark Rideout, Jesse Bishop, and John Papa: "ScrapBook", "HTML and Video Puzzle", and "Rich Notepad". Floating Visual Elements I like Miro Miroslavov's comment: "every Silverlight application “must” have some objects floating around in a quite 3D manner" :) ... well they do that on the CompletIT site, and this is part 2 of their explanation of how all that goodness works. MVVM – A Total Design Change Of Your Application With No Code With some Blend goodness, Michael Washington completely reorganizes the UI of an MVVM application without touching any code ... project included MVVM with Transaction and View Locator Example Jeremy Likness responded to reader requests and has an example up, with explanation, of marrying his last two posts: transactions with MVVM and View Model Locator. Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    Windows Phone MIX10

    Read the article

  • Silverlight Cream for November 20, 2011 -- #1169

    - by Dave Campbell
    In this Issue: Andrea Boschin, Michael Crump, Michael Sync, WindowsPhoneGeek, Jesse Liberty, Derik Whittaker, Sumit Dutta, Jeff Blankenburg(-2-), and Beth Massi. Above the Fold: WP7: "Silver VNC 1.0 for Windows Phone "Mango"" Andrea Boschin Metro/WinRT/W8: "Lighting up your C# Metro apps by being a Share Source" Derik Whittaker LightSwitch: "Using the Save and Query Pipeline to “Archive” Deleted Records" Beth Massi Shoutouts: Michael Palermo's latest Desert Mountain Developers is up Michael Washington's latest Visual Studio #LightSwitch Daily is up From SilverlightCream.com: Silver VNC 1.0 for Windows Phone "Mango" Andrea Boschin published the first release of his "Silver VNC" version 1.0 on CodePlex. Check out the video on the blog post to see the capabilities, then go grab it from CodePlex. Fixing a broken toolbox (In Visual Studio 2010 SP1) Not Silverlight or Metro, but near to us all is Visual Studio... read how Michael Crump resolves the 'broken' toolbox that we all get now and then Windows Phone 7 – USB Device Not Recognized Error Michael Sync is looking for ideas about an error he gets any time he updates his phone. Windows Phone Toolkit MultiselectList in depth| Part2: Data Binding WindowsPhoneGeek has up the second part of his tutorial series on the MultiselectList from the Windows Phone Toolkit... this part is about data binding, complete with lots of code, discussion, pictures, and project to download New Mini-Tutorial Video Series Jesse Liberty started a new video series based on his Mango Mini tutorials. They will be on Channel 9, and he has a link on this post to the index. The firs of the series is on animation without code Lighting up your C# Metro apps by being a Share Source Derik Whittaker continues investigating Metro with this post about how to set your app up to share its content with other apps Part 21 - Windows Phone 7 - Toast Push Notification Sumit Dutta has part 21 of his WP7 series up and is talking about Toast Notification by creating a Windows form app for sending notifications to the WP7 app for viewing 31 Days of Mango | Day #6: Motion Jeff Blankenburg's Day 6 in his Mango series is about the Motion class which combines the data we get from the Accelerometer, Compass, and Gyroscope of the last couple days of posts 31 Days of Mango | Day #7: Raw Camera Data In Day 7, Jeff Blankenburg talks about the Camera on the WP7 and how to use the raw data in your own application Using the Save and Query Pipeline to “Archive” Deleted Records Beth Massi's latest LightSwith post is this one on tapping into the Save and Query pipelines to perform some data processing prior to saving or pulling data Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    Windows Phone MIX10

    Read the article

  • Where i set touch effect when a spawn Srite are comming on the screen?

    - by shihab_returns
    I just create a scene where create a spawn spirit that comes from above screen height in Landscape mode. Now i want to remove spirits when i touch on it. I tried but seems the code not works and crashed also after a while. here is my code: /** TimerHandler for collision detection and cleaning up */ IUpdateHandler detect = new IUpdateHandler() { @Override public void reset() { } @Override public void onUpdate(float pSecondsElapsed) { Iterator<AnimatedSprite> targets = targetLL.iterator(); AnimatedSprite _target; while (targets.hasNext()) { _target = targets.next(); if (_target.getY() >= cameraHeight) { // removeSprite(_target, targets); tPool.recyclePoolItem(_target); targets.remove(); Log.d("ok", "---------Looop Inside-----"); // fail(); break; } } targetLL.addAll(TargetsToBeAdded); TargetsToBeAdded.clear(); } }; /** adds a target at a random location and let it move along the y-axis */ public void addTarget() { Random rand = new Random(); int minX = mTargetTextureRegion.getWidth(); int maxX = (int) (mCamera.getWidth() - mTargetTextureRegion.getWidth()); int rangeX = maxX - minX; Log.d("----point----", "minX:" + minX + "maxX:" + maxX + "rangeX:" + rangeX); int rX = rand.nextInt(rangeX) + minX; int rY = (int) mCamera.getHeight() + mTargetTextureRegion.getHeight(); Log.d("---Random x----", "Random x" + rX + "Random y" + rY); target = tPool.obtainPoolItem(); target.setPosition(rX, rY); target.animate(100); mMainScene.attachChild(target, 1); mMainScene.registerTouchArea(target); int minDuration = 2; int maxDuration = 32; int rangeDuration = maxDuration - minDuration; int actualDuration = rand.nextInt(rangeDuration) + minDuration; // MoveXModifier mod = new MoveXModifier(actualDuration, target.getX(), // -target.getWidth()); MoveYModifier mody = new MoveYModifier(actualDuration, -target.getHeight(), cameraHeight + 10); target.registerEntityModifier(mody.deepCopy()); TargetsToBeAdded.add(target); } @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if (pTouchArea == target) { Toast.makeText(getApplicationContext(), "Yoooooooo", Toast.LENGTH_LONG).show(); } return true; } ** My question is where i implements IOnAreaTouchListener in My code. ? ** Thanks in Advance.

    Read the article

  • Program crashes when item selected from listView

    - by philip
    The application just crash every time I try to click from the list. ListMovingNames.java public class ListMovingNames extends Activity { ListView MoveList; SQLHandler SQLHandlerview; Cursor cursor; Button addMove; EditText etAddMove; TextView temp; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.selectorcreatemove); addMove = (Button) findViewById(R.id.bAddMove); etAddMove = (EditText) findViewById(R.id.etMoveName); temp = (TextView) findViewById(R.id.tvTemp); MoveList = (ListView) findViewById(R.id.lvMoveItems); SQLHandlerview = new SQLHandler(this); SQLHandlerview = new SQLHandler(ListMovingNames.this); SQLHandlerview.open(); cursor = SQLHandlerview.getMove(); startManagingCursor(cursor); String[] from = new String[]{SQLHandler.KEY_MOVENAME}; int[] to = new int[]{R.id.text}; SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to); MoveList.setAdapter(cursorAdapter); SQLHandlerview.close(); addMove.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub try { String ssmoveName = etAddMove.getText().toString(); SQLHandler entry = new SQLHandler(ListMovingNames.this); entry.open(); entry.createMove(ssmoveName); entry.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); MoveList.setOnItemClickListener(new OnItemClickListener() { @SuppressLint("ShowToast") public void onItemClick(AdapterView<?> arg0, View view, int position, long id) { // TODO Auto-generated method stub // String moveset = cursor.getString(position); // temp.setText(moveset); Toast.makeText(ListMovingNames.this, position, Toast.LENGTH_SHORT); } }); } } and here's my database handler. But I'm sure that there's nothing wrong with it, its probably the cursor adapter. SQLHandler.java public class SQLHandler { public static final String KEY_ROOMMOVEHOLDER = "roommoveholder"; public static final String KEY_ROOM = "room"; public static final String KEY_ITEMMOVEHOLDER = "itemmoveholder"; public static final String KEY_ITEMNAME = "itemname"; public static final String KEY_ITEMVALUE = "itemvalue"; public static final String KEY_ROOMHOLDER = "roomholder"; public static final String KEY_MOVENAME = "movename"; public static final String KEY_ID1 = "_id"; public static final String KEY_ID2 = "_id"; public static final String KEY_ID3 = "_id"; public static final String KEY_ID4 = "_id"; public static final String KEY_MOVEDATE = "movedate"; private static final String DATABASE_NAME = "mymovingfriend"; private static final int DATABASE_VERSION = 1; public static final String KEY_SORTANDPURGE = "sortandpurge"; public static final String KEY_RESEARCH = "research"; public static final String KEY_CREATEMOVINGBINDER = "createmovingbinder"; public static final String KEY_ORDERSUPPLIES = "ordersupplies"; public static final String KEY_USEITORLOSEIT = "useitorloseit"; public static final String KEY_TAKEMEASUREMENTS = "takemeasurements"; public static final String KEY_CHOOSEMOVER = "choosemover"; public static final String KEY_BEGINPACKING = "beginpacking"; public static final String KEY_LABEL = "label"; public static final String KEY_SEPARATEVALUES = "separatevalues"; public static final String KEY_DOACHANGEOFADDRESS = "doachangeofaddress"; public static final String KEY_NOTIFYIMPORTANTPARTIES = "notifyimportantparties"; private static final String DATABASE_TABLE1 = "movingname"; private static final String DATABASE_TABLE2 = "movingrooms"; private static final String DATABASE_TABLE3 = "movingitems"; private static final String DATABASE_TABLE4 = "todolist"; public static final String CREATE_TABLE_1 = "CREATE TABLE " + DATABASE_TABLE1 + " (" + KEY_ID1 + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_MOVEDATE + " TEXT NOT NULL, " + KEY_MOVENAME + " TEXT NOT NULL);"; public static final String CREATE_TABLE_2 = "CREATE TABLE " + DATABASE_TABLE2 + " (" + KEY_ID2 + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_ROOMMOVEHOLDER + " TEXT NOT NULL, " + KEY_ROOM + " TEXT NOT NULL);"; public static final String CREATE_TABLE_3 = "CREATE TABLE " + DATABASE_TABLE3 + " (" + KEY_ID3 + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_ITEMNAME + " TEXT NOT NULL, " + KEY_ITEMVALUE + " TEXT NOT NULL, " + KEY_ROOMHOLDER + " TEXT NOT NULL, " + KEY_ITEMMOVEHOLDER + " TEXT NOT NULL);"; public static final String CREATE_TABLE_4 = "CREATE TABLE " + DATABASE_TABLE4 + " (" + KEY_ID4 + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_SORTANDPURGE + " TEXT NOT NULL, " + KEY_RESEARCH + " INTEGER NOT NULL, " + KEY_CREATEMOVINGBINDER + " TEXT NOT NULL, " + KEY_ORDERSUPPLIES + " TEXT NOT NULL, " + KEY_USEITORLOSEIT + " TEXT NOT NULL, " + KEY_TAKEMEASUREMENTS + " TEXT NOT NULL, " + KEY_CHOOSEMOVER + " TEXT NOT NULL, " + KEY_BEGINPACKING + " TEXT NOT NULL, " + KEY_LABEL + " TEXT NOT NULL, " + KEY_SEPARATEVALUES + " TEXT NOT NULL, " + KEY_DOACHANGEOFADDRESS + " TEXT NOT NULL, " + KEY_NOTIFYIMPORTANTPARTIES + " TEXT NOT NULL);"; private DbHelper ourHelper; private final Context ourContext; private SQLiteDatabase ourDatabase; private static class DbHelper extends SQLiteOpenHelper{ public DbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL(CREATE_TABLE_1); db.execSQL(CREATE_TABLE_2); db.execSQL(CREATE_TABLE_3); db.execSQL(CREATE_TABLE_4); } @Override public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) { // TODO Auto-generated method stub db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE1); db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE2); db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE3); db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE4); onCreate(db); } } public SQLHandler(Context c){ ourContext = c; } public SQLHandler open() throws SQLException{ ourHelper = new DbHelper(ourContext); ourDatabase = ourHelper.getWritableDatabase(); return this; } public void close(){ ourHelper.close(); } public long createMove(String smovename){ ContentValues cv = new ContentValues(); cv.put(KEY_MOVENAME, smovename); cv.put(KEY_MOVEDATE, "Not yet set"); return ourDatabase.insert(DATABASE_TABLE1, null, cv); } public long addRooms(String sroommoveholder, String sroom){ ContentValues cv = new ContentValues(); cv.put(KEY_ROOMMOVEHOLDER, sroommoveholder); cv.put(KEY_ROOM, sroom); return ourDatabase.insert(DATABASE_TABLE2, null, cv); } public long addItems(String sitemmoveholder, String sroomholder, String sitemname, String sitemvalue){ ContentValues cv = new ContentValues(); cv.put(KEY_ITEMMOVEHOLDER, sitemmoveholder); cv.put(KEY_ROOMHOLDER, sroomholder); cv.put(KEY_ITEMNAME, sitemname); cv.put(KEY_ITEMVALUE, sitemvalue); return ourDatabase.insert(DATABASE_TABLE3, null, cv); } public long todoList(String todoitem){ ContentValues cv = new ContentValues(); cv.put(todoitem, "Done"); return ourDatabase.insert(DATABASE_TABLE4, null, cv); } public Cursor getMove(){ String[] columns = new String[]{KEY_ID1, KEY_MOVENAME}; Cursor cursor = ourDatabase.query(DATABASE_TABLE1, columns, null, null, null, null, null); return cursor; } } can anyone point out what I'm doing wrong? here's the log 09-19 03:22:36.596: E/AndroidRuntime(679): FATAL EXCEPTION: main 09-19 03:22:36.596: E/AndroidRuntime(679): android.content.res.Resources$NotFoundException: String resource ID #0x0 09-19 03:22:36.596: E/AndroidRuntime(679): at android.content.res.Resources.getText(Resources.java:201) 09-19 03:22:36.596: E/AndroidRuntime(679): at android.widget.Toast.makeText(Toast.java:258) 09-19 03:22:36.596: E/AndroidRuntime(679): at standard.internet.marketing.mymovingfriend.ListMovingNames$2.onItemClick(ListMovingNames.java:78) 09-19 03:22:36.596: E/AndroidRuntime(679): at android.widget.AdapterView.performItemClick(AdapterView.java:284) 09-19 03:22:36.596: E/AndroidRuntime(679): at android.widget.ListView.performItemClick(ListView.java:3382) 09-19 03:22:36.596: E/AndroidRuntime(679): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1696) 09-19 03:22:36.596: E/AndroidRuntime(679): at android.os.Handler.handleCallback(Handler.java:587) 09-19 03:22:36.596: E/AndroidRuntime(679): at android.os.Handler.dispatchMessage(Handler.java:92) 09-19 03:22:36.596: E/AndroidRuntime(679): at android.os.Looper.loop(Looper.java:123) 09-19 03:22:36.596: E/AndroidRuntime(679): at android.app.ActivityThread.main(ActivityThread.java:4627) 09-19 03:22:36.596: E/AndroidRuntime(679): at java.lang.reflect.Method.invokeNative(Native Method) 09-19 03:22:36.596: E/AndroidRuntime(679): at java.lang.reflect.Method.invoke(Method.java:521) 09-19 03:22:36.596: E/AndroidRuntime(679): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 09-19 03:22:36.596: E/AndroidRuntime(679): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 09-19 03:22:36.596: E/AndroidRuntime(679): at dalvik.system.NativeStart.main(Native Method)

    Read the article

  • Android Title bar leaving space in when application is resumed

    - by user466607
    I am using a Tab Host in my Android App. I have the Titlebar hidden. When I leave the App and resume to it, I have some strange behaviour. If I resume to a tab using a list activity with listView.setAdapter, the title bar is hidden and the space it takes up is consumed by the App. However, if I resume to any tab without the listView.setAdapter, the Titlebar is hidden, but space which was used by it is left behind. This is pushes my tabs (which are positioned at the bottom of the screen) off the screen. The space is once again consumed by my app if I then change to any other tab. I have tried to invalidate most of the obvious Views in my App without and success. Below is my tab_activity xml. many thanks <?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"> <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"> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="0dip" android:layout_weight="1" /> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="0" /> </LinearLayout> </TabHost> </LinearLayout> Here is the Manifest <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.tar.projectx" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <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.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.CALL_PHONE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" /> <application android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen" android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true"> <activity android:name=".Splash" android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen" android:label="@string/app_name" android:screenOrientation="portrait"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="SearchActivity" android:label="SearchActivity" android:screenOrientation="portrait"></activity> <activity android:name="SearchListActivity" android:label="SearchListActivity" android:screenOrientation="portrait"></activity> <activity android:name="ContactActivity" android:label="ContactActivity" android:screenOrientation="portrait"></activity> </application> </manifest> Interestingly, if I use the code below in the onResume method of my mainActivity which holds the tabhost, once the toast disappears, the view is refreshed and the space at the top is taken up by my app again. Obviously, this isn't much of a fix, but may help someone understand what is happening. @Override protected void onResume() { super.onResume(); Toast.makeText(this, "Welcome Back", Toast.LENGTH_LONG).show(); }

    Read the article

  • How can i make a gallery with web images from my website?

    - by ronhdoge
    I currently have two codes that i am trying to figure out how to mix or write a new code to have a gallery with image doing fill_parent but i can slide sideways to see the other url linked images from my site. here are both parts of code i have: package com.mandarich.gallerygrid; import java.io.InputStream; import java.net.URL; import android.app.Activity; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.widget.ImageView; public class Gallery extends Activity { /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ImageView imgView =(ImageView)findViewById(R.id.ImageView01); Drawable drawable = LoadImageFromWebOperations("http://www.mandarichmodels.com/hot-pics/"); imgView.setImageDrawable(drawable); } private Drawable LoadImageFromWebOperations(String url) { try { InputStream is = (InputStream) new URL(url).getContent(); Drawable d = Drawable.createFromStream(is, "src name"); return d; }catch (Exception e) { System.out.println("Exc="+e); return null; } } } and here is my gallery code package com.mandarich.Grid; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.ImageView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; public class gridfinal extends Activity { private Gallery gallery; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); gallery = (Gallery) findViewById(R.id.examplegallery); gallery.setAdapter(new AddImgAdp(this)); gallery.setOnItemClickListener(new OnItemClickListener() { @SuppressWarnings("unchecked") public void onItemClick(AdapterView parent, View v, int position, long id) { // Displaying the position when the gallery item in clicked Toast.makeText(gridfinal.this, "Position=" + position, Toast.LENGTH_SHORT).show(); } }); } public class AddImgAdp extends BaseAdapter { int GalItemBg; private Context cont; // Adding images. private Integer[] Imgid = { R.drawable.cindy, R.drawable.clinton, R.drawable.colin, R.drawable.cybil, R.drawable.david, R.drawable.demi, R.drawable.drew }; public AddImgAdp(Context c) { cont = c; TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme); GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0); typArray.recycle(); } public int getCount() { return Imgid.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView imgView = new ImageView(cont); imgView.setImageResource(Imgid[position]); // Fixing width & height for image to display imgView.setLayoutParams(new Gallery.LayoutParams(430, 370)); imgView.setScaleType(ImageView.ScaleType.FIT_XY); imgView.setBackgroundResource(GalItemBg); return imgView; } } }

    Read the article

  • Preference List only shows first element

    - by jmunoz
    I am developing a PreferenceActivity with custom Preference views. My problem is that I created a view with a ListView and it only shows the first element. I post my code and an image: http://imageshack.us/photo/my-images/545/sc20120307161530.png/ xml: <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > <PreferenceCategory android:key="player_settings" android:title="@string/settings_player_config" > <EditTextPreference android:defaultValue="@string/settings_player_default_name" android:dialogMessage="@string/settings_player_summary" android:dialogTitle="@string/settings_playersname" android:key="player_name" android:summary="@string/settings_player_summary" android:title="@string/settings_playersname" /> </PreferenceCategory> <PreferenceCategory android:key="volume" android:title="@string/settings_volume" > <com.battleship.preferences.SeekBarPreferences android:defaultValue="50" android:key="volume" android:title="@string/settings_volume" /> </PreferenceCategory> <PreferenceCategory android:key="shine" android:title="@string/settings_shine" > <com.battleship.preferences.SeekBarPreferences android:defaultValue="50" android:key="shine" android:title="@string/settings_shine" /> </PreferenceCategory> <PreferenceCategory android:key="themeTitle" android:title="@string/settings_group_themes" > <com.battleship.preferences.ListPreferences android:key="theme" /> </PreferenceCategory> <PreferenceCategory android:key="fontsTitle" android:title="@string/settings_group_font_size" > <com.battleship.preferences.ListPreferences android:key="font" /> </PreferenceCategory> </PreferenceScreen> The Custom ListPreference: package com.battleship.preferences; import com.battleship.R; import android.content.Context; import android.content.SharedPreferences; import android.media.AudioManager; import android.preference.Preference; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; import android.widget.Toast; public class ListPreferences extends Preference implements OnCheckedChangeListener { public ListPreferences(Context context) { super(context); } public ListPreferences(Context context, AttributeSet attrs) { super(context, attrs); } public ListPreferences(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onClick() { super.onClick(); Toast t = Toast.makeText(getContext(), "HOLA!", 3); t.show(); } @Override protected View onCreateView(ViewGroup parent) { String[] contentString = new String[3]; if (getKey().equals("theme")) { contentString = new String[] { (getContext().getString(R.string.settings_theme_default)), (getContext().getString(R.string.settings_theme_black)), (getContext().getString(R.string.settings_theme_white)) }; } else { contentString = new String[] { (getContext().getString(R.string.settings_font_big)), (getContext().getString(R.string.settings_font_medium)), (getContext().getString(R.string.settings_font_little)) }; } ListView listView = new ListView(getContext()); ArrayAdapter<String> array = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_single_choice, android.R.id.text1, contentString); listView.setAdapter(array); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); return listView; } private void updatePreference(int intRadio) { SharedPreferences.Editor editor = getEditor(); editor.putInt(getKey(), intRadio); editor.commit(); } }

    Read the article

  • Select Multiple Images Using GalleryView

    - by hwrdprkns
    Hi guys, I was just wondering if Android had built in code so that I could select multiple images in a gallery-view and then have those images exported as filenames in a string array(ex /sdcard/~f1.jpg, /sdcard/~f2.jpg,...). I have the gallery code here, but I'm not sure what modifications need to be made. Any help is appreciated. Thanks! // take_picture = (Button)findViewById(R.id.take_picture); // Here we set up a string array of the thumbnail ID column we want to // get back String[] proj = { MediaStore.Images.Thumbnails._ID }; if(proj.length == 0) { nopic.setVisibility(View.VISIBLE); } // Now we create the cursor pointing to the external thumbnail store cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, proj, // Which // columns // to // return null, // WHERE clause; which rows to return (all rows) null, // WHERE clause selection arguments (none) null); // Order-by clause (ascending by name) /* take_picture.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i = new Intent(GalleryActivity.this, CameraActivity.class); startActivity(i); } }); */ // We now get the column index of the thumbnail id column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID); // Reference the Gallery view g = (Gallery) findViewById(R.id.gallery); if(proj.length == 0) { nopic.setVisibility(View.VISIBLE); g.setVisibility(View.GONE); } // Set the adapter to our custom adapter (below) g.setAdapter(new ImageAdapter(this)); // Set a item click listener, and just Toast the clicked position g.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { // Now we want to actually get the data location of the file String[] proj = { MediaStore.Images.Media.DATA }; // We request our cursor again cursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj, // Which // columns // to // return null, // WHERE clause; which rows to return (all rows) null, // WHERE clause selection arguments (none) null); // Order-by clause (ascending by name) // We want to get the column index for the data uri column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); // Lets move to the selected item in the cursor cursor.moveToPosition((int) g.getSelectedItemId()); // And here we get the filename String filename = cursor.getString(column_index); Log.v("GalleryActivity", filename); Toast.makeText(GalleryActivity.this, filename, Toast.LENGTH_SHORT).show(); setPrefs(filename); Intent i = new Intent(GalleryActivity.this, OtherClass.class); startActivity(i); } }); } And the ImageAdapter code here: public class ImageAdapter extends BaseAdapter { int mGalleryItemBackground; public ImageAdapter(Context c) { mContext = c; // See res/values/attrs.xml for the that defines // Gallery1. TypedArray a = obtainStyledAttributes(R.styleable.Gallery); mGalleryItemBackground = a.getResourceId( R.styleable.Gallery_android_galleryItemBackground, 0); a.recycle(); } public int getCount() { return cursor.getCount(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView i = new ImageView(mContext); if (convertView == null) { cursor.moveToPosition(position); int id = cursor.getInt(column_index); i.setImageURI(Uri.withAppendedPath( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + id)); i.setScaleType(ImageView.ScaleType.FIT_XY); i.setLayoutParams(new Gallery.LayoutParams(200, 200)); // The preferred Gallery item background i.setBackgroundResource(mGalleryItemBackground); } return i; } } Again any help is appreciateds! Just to let you guys know, the gallery works fine (for one image) as in it exports the filename correctly. Just need to know if there is an easy way to select multiples and export them. Thanks again!

    Read the article

  • Logcat error: "addView(View, LayoutParams) is not supported in AdapterView" in a ListView

    - by HacKreatorz
    I'm doing an aplication for Android and something I need is that it shows a list of all files and directories in the SD Card and it has to be able to move through the different directories. I found a good tutorial in anddev: http://bit.ly/h4GyFC I modified a few things so the aplication moves in the SD Card and not in Android root Directories but the rest is mostly the same. This is my xml file for the activity: <?xml version="1.0" encoding="utf-8"?> <ListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@id/android:list" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" /> </ListView> And this is the code for the Activity: import hackreatorz.cifrador.R; import java.io.File; import java.util.ArrayList; import android.app.ListActivity; import android.content.res.Configuration; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class ArchivosSD extends ListActivity { private ArrayList<String> directoryEntries = new ArrayList<String>(); private File currentDirectory = new File("/sdcard/"); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); browseToSD(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } private void browseToSD() { browseTo(new File("/sdcard/")); } private void upOneLevel() { if(this.currentDirectory.getParent() != null) this.browseTo(this.currentDirectory.getParentFile()); } private void browseTo(final File directory) { if (directory.isDirectory()) { this.currentDirectory = directory; fill(directory.listFiles()); } else { Toast.makeText(ArchivosSD.this, this.directoryEntries.get(this.getSelectedItemPosition()), Toast.LENGTH_SHORT).show(); } } private void fill(File[] files) { this.directoryEntries.clear(); this.directoryEntries.add(getString(R.string.current_dir)); if(this.currentDirectory.getParent() != null) this.directoryEntries.add(getString(R.string.up_one_level)); int currentPathStringLength = (int) this.currentDirectory.getAbsoluteFile().length(); for (File file : files) { this.directoryEntries.add(file.getAbsolutePath().substring(currentPathStringLength)); } setListAdapter(new ArrayAdapter<String>(this, R.layout.archivos_sd, this.directoryEntries)); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { int selectionRowID = (int) this.getSelectedItemPosition(); String selectedFileString = this.directoryEntries.get(selectionRowID); if (selectedFileString.equals(".")) { this.browseToSD(); } else if(selectedFileString.equals("..")) { this.upOneLevel(); } else { File clickedFile = null; clickedFile = new File(this.currentDirectory.getAbsolutePath() + this.directoryEntries.get(selectionRowID)); if(clickedFile != null) this.browseTo(clickedFile); } } } I don't get any errores in Eclipse, but I get a Force Close when running the aplication on my phone and when I look at Logcat I see the following: 01-01 23:30:29.858: ERROR/AndroidRuntime(14911): FATAL EXCEPTION: main *01-01 23:30:29.858: ERROR/AndroidRuntime(14911): java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView* I don't have a clue what to do, I've looked up in Google and I didn't find anything and I did the same at stackoverflow. This is my first aplication in Java and for Android so I'm a real n00b and if the answer was there, I didn't understand it so I would really apreciate if you could explain what I should do to fix this error and why. Thanks for everything in advanced.

    Read the article

  • Error in code of basic game using multiple sprites and surfaceView [on hold]

    - by Khagendra Nath Mahato
    I am a beginner to android and i was trying to make a basic game with the help of an online video tutorial. I am having problem with the multi-sprites and how to use with surfaceview.The application fails launching. Here is the code of the game.please help me. package com.example.killthemall; import java.util.ArrayList; import java.util.List; import java.util.Random; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Rect; import android.os.Bundle; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.widget.Toast; public class Game extends Activity { KhogenView View1; @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); while(true){ try { OurThread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }} } Thread OurThread; int herorows = 4; int herocolumns = 3; int xpos, ypos; int xspeed; int yspeed; int herowidth; int widthnumber = 0; int heroheight; Rect src; Rect dst; int round; Bitmap bmp1; // private Bitmap bmp1;//change name public List<Sprite> sprites = new ArrayList<Sprite>() { }; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); View1 = new KhogenView(this); setContentView(View1); sprites.add(createSprite(R.drawable.image)); sprites.add(createSprite(R.drawable.bad1)); sprites.add(createSprite(R.drawable.bad2)); sprites.add(createSprite(R.drawable.bad3)); sprites.add(createSprite(R.drawable.bad4)); sprites.add(createSprite(R.drawable.bad5)); sprites.add(createSprite(R.drawable.bad6)); sprites.add(createSprite(R.drawable.good1)); sprites.add(createSprite(R.drawable.good2)); sprites.add(createSprite(R.drawable.good3)); sprites.add(createSprite(R.drawable.good4)); sprites.add(createSprite(R.drawable.good5)); sprites.add(createSprite(R.drawable.good6)); } private Sprite createSprite(int image) { // TODO Auto-generated method stub bmp1 = BitmapFactory.decodeResource(getResources(), image); return new Sprite(this, bmp1); } public class KhogenView extends SurfaceView implements Runnable { SurfaceHolder OurHolder; Canvas canvas = null; Random rnd = new Random(); { xpos = rnd.nextInt(canvas.getWidth() - herowidth)+herowidth; ypos = rnd.nextInt(canvas.getHeight() - heroheight)+heroheight; xspeed = rnd.nextInt(10 - 5) + 5; yspeed = rnd.nextInt(10 - 5) + 5; } public KhogenView(Context context) { super(context); // TODO Auto-generated constructor stub OurHolder = getHolder(); OurThread = new Thread(this); OurThread.start(); } @Override public void run() { // TODO Auto-generated method stub herowidth = bmp1.getWidth() / 3; heroheight = bmp1.getHeight() / 4; boolean isRunning = true; while (isRunning) { if (!OurHolder.getSurface().isValid()) continue; canvas = OurHolder.lockCanvas(); canvas.drawRGB(02, 02, 50); for (Sprite sprite : sprites) { if (widthnumber == 3) widthnumber = 0; update(); getdirection(); src = new Rect(widthnumber * herowidth, round * heroheight, (widthnumber + 1) * herowidth, (round + 1)* heroheight); dst = new Rect(xpos, ypos, xpos + herowidth, ypos+ heroheight); canvas.drawBitmap(bmp1, src, dst, null); } widthnumber++; OurHolder.unlockCanvasAndPost(canvas); } } public void update() { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (xpos + xspeed <= 0) xspeed = 40; if (xpos >= canvas.getWidth() - herowidth) xspeed = -50; if (ypos + yspeed <= 0) yspeed = 45; if (ypos >= canvas.getHeight() - heroheight) yspeed = -55; xpos = xpos + xspeed; ypos = ypos + yspeed; } public void getdirection() { double angleinteger = (Math.atan2(yspeed, xspeed)) / (Math.PI / 2); round = (int) (Math.round(angleinteger) + 2) % herorows; // Toast.makeText(this, String.valueOf(round), // Toast.LENGTH_LONG).show(); } } public class Sprite { Game game; private Bitmap bmp; public Sprite(Game game, Bitmap bmp) { // TODO Auto-generated constructor stub this.game = game; this.bmp = bmp; } } } Here is the LogCat if it helps.... 08-22 23:18:06.980: D/AndroidRuntime(28151): Shutting down VM 08-22 23:18:06.980: W/dalvikvm(28151): threadid=1: thread exiting with uncaught exception (group=0xb3f6f4f0) 08-22 23:18:06.980: D/AndroidRuntime(28151): procName from cmdline: com.example.killthemall 08-22 23:18:06.980: E/AndroidRuntime(28151): in writeCrashedAppName, pkgName :com.example.killthemall 08-22 23:18:06.980: D/AndroidRuntime(28151): file written successfully with content: com.example.killthemall StringBuffer : ;com.example.killthemall 08-22 23:18:06.990: I/Process(28151): Sending signal. PID: 28151 SIG: 9 08-22 23:18:06.990: E/AndroidRuntime(28151): FATAL EXCEPTION: main 08-22 23:18:06.990: E/AndroidRuntime(28151): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.killthemall/com.example.killthemall.Game}: java.lang.NullPointerException 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.os.Handler.dispatchMessage(Handler.java:99) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.os.Looper.loop(Looper.java:130) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.ActivityThread.main(ActivityThread.java:3683) 08-22 23:18:06.990: E/AndroidRuntime(28151): at java.lang.reflect.Method.invokeNative(Native Method) 08-22 23:18:06.990: E/AndroidRuntime(28151): at java.lang.reflect.Method.invoke(Method.java:507) 08-22 23:18:06.990: E/AndroidRuntime(28151): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880) 08-22 23:18:06.990: E/AndroidRuntime(28151): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:638) 08-22 23:18:06.990: E/AndroidRuntime(28151): at dalvik.system.NativeStart.main(Native Method) 08-22 23:18:06.990: E/AndroidRuntime(28151): Caused by: java.lang.NullPointerException 08-22 23:18:06.990: E/AndroidRuntime(28151): at com.example.killthemall.Game$KhogenView.<init>(Game.java:96) 08-22 23:18:06.990: E/AndroidRuntime(28151): at com.example.killthemall.Game.onCreate(Game.java:58) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) 08-22 23:18:06.990: E/AndroidRuntime(28151): ... 11 more 08-22 23:18:18.050: D/AndroidRuntime(28191): Shutting down VM 08-22 23:18:18.050: W/dalvikvm(28191): threadid=1: thread exiting with uncaught exception (group=0xb3f6f4f0) 08-22 23:18:18.050: I/Process(28191): Sending signal. PID: 28191 SIG: 9 08-22 23:18:18.050: D/AndroidRuntime(28191): procName from cmdline: com.example.killthemall 08-22 23:18:18.050: E/AndroidRuntime(28191): in writeCrashedAppName, pkgName :com.example.killthemall 08-22 23:18:18.050: D/AndroidRuntime(28191): file written successfully with content: com.example.killthemall StringBuffer : ;com.example.killthemall 08-22 23:18:18.050: E/AndroidRuntime(28191): FATAL EXCEPTION: main 08-22 23:18:18.050: E/AndroidRuntime(28191): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.killthemall/com.example.killthemall.Game}: java.lang.NullPointerException 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.os.Handler.dispatchMessage(Handler.java:99) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.os.Looper.loop(Looper.java:130) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.ActivityThread.main(ActivityThread.java:3683) 08-22 23:18:18.050: E/AndroidRuntime(28191): at java.lang.reflect.Method.invokeNative(Native Method) 08-22 23:18:18.050: E/AndroidRuntime(28191): at java.lang.reflect.Method.invoke(Method.java:507) 08-22 23:18:18.050: E/AndroidRuntime(28191): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880) 08-22 23:18:18.050: E/AndroidRuntime(28191): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:638) 08-22 23:18:18.050: E/AndroidRuntime(28191): at dalvik.system.NativeStart.main(Native Method) 08-22 23:18:18.050: E/AndroidRuntime(28191): Caused by: java.lang.NullPointerException 08-22 23:18:18.050: E/AndroidRuntime(28191): at com.example.killthemall.Game$KhogenView.<init>(Game.java:96) 08-22 23:18:18.050: E/AndroidRuntime(28191): at com.example.killthemall.Game.onCreate(Game.java:58) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) 08-22 23:18:18.050: E/AndroidRuntime(28191): ... 11 more

    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 ListView with SQLite

    - by soclose
    Hi I'd like to refresh the Listview items. These items are populated from SQLite database. My code is below public class Weeve extends Activity { private String[] lv_arr; protected ListView CView; private DBAdapter mDbHelper; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mDbHelper = new DBAdapter(this); mDbHelper.open(); Cursor c = mDbHelper.getAll(); if (c.getCount() > 0) {if (c.moveToFirst()) { ArrayList strings = new ArrayList(); do { String mC = c.getString(0); strings.add(mC); } while (c.moveToNext()); lv_arr = (String[]) strings.toArray(new String[strings.size()]); } } else Toast.makeText(this, "No more Records", Toast.LENGTH_SHORT).show(); c.close(); ListView CView = new ListView(this); CView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lv_arr)); setContentView(CView);}} I'd like to make refreshing this list view after adding, updating or deleting SQLite table. These operations are called by content or option menu. I tried to create these code into a separated function and call it after every operation. But can't. I think setContentView(CView) statement. I also tried to use SimpleCursorAdapter like notepad sample from Android.com. I got Thread error. Help me.

    Read the article

  • Android: How to keep onItemSelected from firing off on a newly instantiated Spinner

    - by Drennen
    I've thought of some less than elegant ways to solve this, but I know I must be missing something. My onItemSelected fires off immediately without any interaction with the user, and this is undesired behavior. I wish for the UI to wait until the user selects something before it does anything. I even tried setting up the listener in the onResume, hoping that would help, but it doesn't. How can I stop this from firing off before the user can touch the control? THANKS public class CMSHome extends Activity { private Spinner spinner; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Heres my spinner /////////////////////////////////////////// spinner = (Spinner) findViewById(R.id.spinner); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.pm_list, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); }; public void onResume() { super.onResume(); spinner.setOnItemSelectedListener(new MyOnItemSelectedListener()); } public class MyOnItemSelectedListener implements OnItemSelectedListener { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { Intent i = new Intent(CMSHome.this, ListProjects.class); i.putExtra("bEmpID", parent.getItemAtPosition(pos).toString()); startActivity(i); Toast.makeText(parent.getContext(), "The pm is " + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show(); } public void onNothingSelected(AdapterView parent) { // Do nothing. } } }

    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

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