Search Results

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

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

  • How to stop an iteration of TextView when click in on one of the TextView?

    - by sgiro
    Hello, i have one doubt. I have an iteration of TextViews, and what i want is when i click in one TextView , i want stop the iteration and open a web, who can i know what TextView as been click on? i have this code: Iterator it = text.iterator(); while(it.hasNext()){ test = it.next(); test.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //mWebView = (WebView) findViewById(R.id.webview); mWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.loadUrl(url); } }); // condition to stop the iteration when i click on TextView } And what i want is the condition to stop the iteration when i click on the TextView that i want see, i try using some methods that are in the TextView and don't work. Anyone can help me? Thanks and forgive my English

    Read the article

  • Android. Playing multiple sounds using SoundManager

    - by Jerry
    Shown are a few lines of code. If I play a single sound, it runs fine. Adding a second sound causes it to crash. Any advice is appreciated. private SoundManager mSoundManager; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sos); mSoundManager = new SoundManager(); mSoundManager.initSounds(getBaseContext()); mSoundManager.addSound(1,R.raw.dit); mSoundManager.addSound(1,R.raw.dah); Button SoundButton = (Button)findViewById(R.id.SoundButton); SoundButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mSoundManager.playSound(1); mSoundManager.playSound(2); } }); }

    Read the article

  • how to set layout_weight programmatically for alert dialog button?

    - by Are
    Hi, Iam planing to give create 3 buttons with layout_weight=1, not interested in custom dialog.So I have written below code.It is not working.Always yes button gives me null. Whats wrong in this code? AlertDialog dialog= new AlertDialog.Builder(this).create(); dialog.setIcon(R.drawable.alert_icon); dialog.setTitle("title"); dialog.setMessage("Message"); dialog.setButton(AlertDialog.BUTTON_POSITIVE,"Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { } }); Button yesButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE); Log.w("Button",""+yesButton);//here getting null LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, 1f); yesButton.setLayoutParams(layoutParams); dialog.show(); Regards, Android developer.

    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

  • Can't add email signature in Android

    - by user1680411
    I'm trying to compose and send an email which will include a signature at the bottom of my email content in android. I'm able to send an email but I'm not getting the way that allows me to add my own signature. Do you have any suggestion? here's my code: public void addListener() { final Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { findViewById = (TextView) findViewById(R.id.t1); Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_EMAIL, new String[] { "[email protected]"}); /*i.putExtra(Intent.EXTRA_CC, new String[] { "[email protected]" });*/ i.putExtra(Intent.EXTRA_SUBJECT, "Android Test"); i.putExtra(Intent.EXTRA_TEXT, "Body"); //i.putExtra(Intent.EXTRA_TEXT, "signature"); try { startActivity(Intent.createChooser(i, "Choose mail app...")); } catch (android.content.ActivityNotFoundException ex) { } } }); }

    Read the article

  • store image in sqlite

    - by bbkaaka
    i have the folloing code : final Gallery g = (Gallery) findViewById(R.id.gallery); g.setAdapter(new ImageAdapter(this)); g.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id) { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Bitmap b = null; b=BitmapFactory.decodeResource(getResources(),*********); b.compress(CompressFormat.PNG, 0, outputStream); AlertDialog.Builder builder = new AlertDialog.Builder(Edit.this); builder.setTitle("Comfirm"); builder.setMessage("Do you want to choose this picture?"); builder.setPositiveButton("Continue", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { image = outputStream.toByteArray(); } }); you see * which need type int like android.R.drawble.icon. i want to store the picture when users click to picture how can i get the picture

    Read the article

  • I can't set main Class variable in onCreate Method

    - by natrollus
    Main class has two variables that want to reach another class: public class MyClassA extends Activity { int i = 1; Button b1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); this.i = 31; this.b1 = (Button) findViewById(R.id.btn1); ~~ } } Second class want to call variables in mainClass object: public class MyclassB implements OnClickListener{ MyClassA mainClass = new MyClassA(); Button btn = mainClass.b1; int n = mainClass.i; public void OnClick(View arg0){ Log.v("btn:",btn); Log.v("int:",n); } //btn returns null; //int returns 1; But onCreate method not set variables.. Why not set main class variables like this.i=31 ?

    Read the article

  • How can I put the results of Cursor into String[]. For more detail, please refer to the code below

    - by Hicen
    public class DisplayCustomersActivity extends Activity implements Button.OnClickListener { private SalesDB sdb; private ListView lvDCList; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.displaycustomers); lvDCList = (ListView) findViewById(R.id.lvDCList); sdb = new SalesDB(this); SQLiteDatabase db = sdb.getReadableDatabase(); Cursor results = db.query(sdb.TABLE_CUSTOMER, new String[] {sdb.CUSTOMER_ID, sdb.CUSTOMER_NAME, sdb.CUSTOMER_GENDER}, null, null, null, null, null); int resultCount = results.getCount(); String[] customers = new String[resultCount]; if (resultCount == 0 || !results.moveToFirst()) { customers = null; } else { for(int i=0; i<resultCount; i++) { //Process results to String array here ... ... results.moveToNext(); } } }

    Read the article

  • Changing background color in Android SDK by clicking a button does not work

    - by DavidNg
    I have a simple program which is able to change the background color after clicking a button, but it does not work public class ChangeBackgroundActivity extends Activity { /** Called when the activity is first created. */ Button blueButton; LinearLayout myLO; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); myLO=(LinearLayout)findViewById(R.layout.main); blueButton=(Button)findViewById(R.id.button1); blueButton.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { // TODO Auto-generated method stub myLO.setBackgroundColor(0x0000FF); //blue color code #0000FF } }); } }

    Read the article

  • Click Listener not invoked within ListFragment

    - by membersound
    I'm extending a SherlockListFragment, but it should not matter as my question seems to be more general related to Fragments. Now, I implement a simple click listener for my list, but it does not get called. public class MyListFragment extends SherlockListFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.list, container, false); v.setOnClickListener(new OnClickListener() { public void onClick(View view) { Log.i("debug", "single click"); } }); return v; } } Is anything wrong with this? //Solution: listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.i("debug", "single click"); } });

    Read the article

  • reference to XML file is not a member of the R file

    - by yoavstr
    how can i had to class layout in R another xml file ? it should b autmatic as i had new resources to res but it's not someone knows what i did wrong ? i open an activity and now i want to open another activity that will work with another xml example i have menu and main.xml now i want to go for anther activity called gamescreen using this method : newGameButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { Intent i = = new Intent(this, gameScreen.class); startActivity(i); } } i want to move to another "page" to another activity called gameScreen which should b associated to the xml called gameScreen.xml but in his onCreate : public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.gameScreen); } and gameScreen is not a member of the R file please help me i am sitting for the last 4 hours felling like an idiot ...

    Read the article

  • Developed android application cannot connect to phpmyadmin

    - by user1850936
    I am developing an app with eclipse. I tried to store the data that key in by user into database in phpmyadmin. Unfortunately, after the user has clicked on submit button, there is no response and data is not stored in my database. Here is my java file: import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONObject; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.content.res.Configuration; public class UserRegister extends Activity { JSONParser jsonParser = new JSONParser(); EditText inputName; EditText inputUsername; EditText inputEmail; EditText inputPassword; RadioButton button1; RadioButton button2; Button button3; int success = 0; private static String url_register_user = "http://10.20.92.81/database/add_user.php"; private static final String TAG_SUCCESS = "success"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_register); inputName = (EditText) findViewById(R.id.nameTextBox); inputUsername = (EditText) findViewById(R.id.usernameTextBox); inputEmail = (EditText) findViewById(R.id.emailTextBox); inputPassword = (EditText) findViewById(R.id.pwTextBox); Button button3 = (Button) findViewById(R.id.regSubmitButton); button3.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { String name = inputName.getText().toString(); String username = inputUsername.getText().toString(); String email = inputEmail.getText().toString(); String password = inputPassword.getText().toString(); if (name.contentEquals("")||username.contentEquals("")||email.contentEquals("")||password.contentEquals("")) { AlertDialog.Builder builder = new AlertDialog.Builder(UserRegister.this); builder.setMessage(R.string.nullAlert) .setTitle(R.string.alertTitle); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog dialog = builder.show(); } // creating new product in background thread RegisterNewUser(); } }); } public void RegisterNewUser() { try { String name = inputName.getText().toString(); String username = inputUsername.getText().toString(); String email = inputEmail.getText().toString(); String password = inputPassword.getText().toString(); // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("name", name)); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("email", email)); params.add(new BasicNameValuePair("password", password)); // getting JSON Object // Note that create product url accepts POST method JSONObject json = jsonParser.makeHttpRequest(url_register_user, "GET", params); // check log cat for response Log.d("Send Notification", json.toString()); success = json.getInt(TAG_SUCCESS); if (success == 1) { // successfully created product Intent i = new Intent(getApplicationContext(), StudentLogin.class); startActivity(i); finish(); } else { // failed to register } } catch (Exception e) { e.printStackTrace(); } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } } my php file: <?php $response = array(); require_once __DIR__ . '/db_connect.php'; $db = new DB_CONNECT(); if (isset($_GET['name']) && isset($_GET['username']) && isset($_GET['email']) && isset($_GET['password'])) { $name = $_GET['name']; $username = $_GET['username']; $email = $_GET['email']; $password = $_GET['password']; // mysql inserting a new row $result = mysql_query("INSERT INTO register(name, username, email, password) VALUES('$name', '$username', '$email', '$password')"); // check if row inserted or not if ($result) { // successfully inserted into database $response["success"] = 1; $response["message"] = "You are successfully registered to MEMS."; // echoing JSON response echo json_encode($response); } else { // failed to insert row $response["success"] = 0; $response["message"] = "Oops! An error occurred."; // echoing JSON response echo json_encode($response); } } else { // required field is missing $response["success"] = 0; $response["message"] = "Required field(s) is missing"; // echoing JSON response echo json_encode($response); } ?> the log cat is as follows: 11-25 10:37:46.772: I/Choreographer(638): Skipped 30 frames! The application may be doing too much work on its main thread.

    Read the article

  • How to restrict this function from execution in android? Please help

    - by andyfan
    This code is present in one of this activity. I want to restrict addJoke() function from executing if the String variable new_joke is null, has no text or contains just spaces. Here is code protected void initAddJokeListeners() { // TODO m_vwJokeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { //Implement code to add a new joke here... String new_joke=m_vwJokeEditText.getText().toString(); if(new_joke!=null&&new_joke!=""&&new_joke!=" ") { addJoke(new_joke); } } }); } I don't know why addJoke() function is getting executed even I don't enter any text in EditText field. Please help.

    Read the article

  • Waiting for DialogActivity to return before continuing executing of the main thread

    - by jax
    How would I force the current thread to wait until another has finished before continuing. In my program the user selects a MODE from an AlertDialog, I want to halt executing of the program before continuing as the mode holds important configuration for the gameplay. new AlertDialog.Builder(this) .setItems(R.array.game_modes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: setMode(TRAINING_MODE); case 1: setMode(QUIZ_MODE); default: setMode(TRAINING_MODE); break; } //continue loading the rest of onCreate(); contineOnCreate(); } }) .create().show(); If this is impossible can anyone give a possible solution?

    Read the article

  • Add two webview in framelayout

    - by user1478916
    I want to add two webview in a layout..I use frameLayout <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <WebView android:id="@+id/webview1" android:layout_width="350dip" android:layout_height="350dip" /> <WebView android:layout_height="250dip" android:layout_width="250dip" android:id="@+id/webview2" /> </FrameLayout> And in Main Activity : web1=(WebView)findViewById(R.id.webview1); web2=(WebView)findViewById(R.id.webview2); web1.loadUrl("http://www.google.com"); web2.loadUrl("http://www.youtube.com"); web2.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub Animation anim=AnimationUtils.loadAnimation(FrameWebViewActivity.this, android.R.anim.slide_in_left); web2.setAnimation(anim); } }); But when run project,it only display webview youtube full screen ..I want to display both two webview..What i must do??

    Read the article

  • Help making a button open another app with Java/Android

    - by user569503
    I am trying to learn to make a simple app that opens a couple of other apps to eliminate the need for another apps. I just can't figure it out. From reading here and other places it seems this should work. Button batteryhistory = (Button)findViewById(R.string.BatteryHistoryButtonDialog); batteryhistory.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(); ComponentName n = new ComponentName("com.android.settings", "com.android.settings.BatteryHistory"); i.setComponent(n); startActivity(i); Thanks so much for the help :D

    Read the article

  • How to convert string to integer?

    - by user1260584
    So I'm having a hard time with my situation and need some advice. I'm trying to convert my two Strings that I have into integers, so that I can use them in math equations. Here is what I tried, however it brings me an error in the app. ' equals.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { // TODO Auto-generated method stub num1 = edit.getText().toString(); num2 = edit.getText().toString(); int first = Integer.parseInt(num1); int second = Integer.parseInt(num2); edit.setText(first + second); } }); Is there something that I am doing wrong? Thank you for any help. EDIT: Yes this is Java. num1 and num2 are strings that I have previously named. What do you mean by trim?

    Read the article

  • code setOnClickListener for multiple TextViews

    - by user2870583
    I have 40+ TextViews and I want to add click events on them, but I try to do it "shortly" : final GridLayout myGL; myGL = (GridLayout) v0725.findViewById( R.id.tab1 ); for( int i = 0; i < myGL.getChildCount(); i++ ) if ( getResources().getResourceEntryName(((TextView) myGL.getChildAt(i)).getId()).indexOf("v")==0 ) { ((TextView) myGL.getChildAt(i)).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.v("edf", getResources().getResourceEntryName(((TextView) myGL.getChildAt(i)).getId())); } }); }; But Eclipse stops me on the Log.v line, because i should be final (but I can't) any tips?

    Read the article

  • Android camera to take multiple photos

    - by user2975407
    problem.java public class problem extends Activity { ImageView iv; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.problem); iv=(ImageView) findViewById(R.id.imageView1); Button b=(Button) findViewById(R.id.button1); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, 0); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); Bitmap bm=(Bitmap) data.getExtras().get("data"); iv.setImageBitmap(bm); } } From this code I can only take one photo and it displayed in the screen. **But I want to take more photos nearly 5 photos and display in the screen** Further I want to add these photos to MySQL database.please help me to do that.I am new to android

    Read the article

  • parseInt and viewflipper layout problems

    - by user1234167
    I have a problem with parseInt it throws the error: unable to parse 'null' as integer. My view flipper is also not working. Hopefully this is an easy enough question. Here is my activity: import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.ViewFlipper; import xml.parser.dataset; public class XmlParserActivity extends Activity implements OnClickListener { private final String MY_DEBUG_TAG = "WeatherForcaster"; // private dataset myDataSet; private LinearLayout layout; private int temp= 0; /** Called when the activity is first created. */ //the ViewSwitcher private Button btn; private ViewFlipper flip; // private TextView tv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); layout=(LinearLayout)findViewById(R.id.linearlayout1); btn=(Button)findViewById(R.id.btn); btn.setOnClickListener(this); flip=(ViewFlipper)findViewById(R.id.flip); //when a view is displayed flip.setInAnimation(this,android.R.anim.fade_in); //when a view disappears flip.setOutAnimation(this, android.R.anim.fade_out); // String postcode = null; // public String getPostcode { // return postcode; // } //URL newUrl = c; // myweather.setText(c.toString()); /* Create a new TextView to display the parsingresult later. */ TextView tv = new TextView(this); // run(0); //WeatherApplicationActivity postcode = new WeatherApplicationActivity(); try { /* Create a URL we want to load some xml-data from. */ URL url = new URL("http://new.myweather2.com/developer/forecast.ashx?uac=gcV3ynNdoV&output=xml&query=G41"); //String url = new String("http://new.myweather2.com/developer/forecast.ashx?uac=gcV3ynNdoV&output=xml&query="+WeatherApplicationActivity.postcode ); //URL url = new URL(url); //url.toString( ); //myString(url.toString() + WeatherApplicationActivity.getString(postcode)); // url + WeatherApplicationActivity.getString(postcode); /* 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*/ handler myHandler = new handler(); xr.setContentHandler(myHandler); /* 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. */ dataset parsedDataSet = myHandler.getParsedData(); /* Set the result to be displayed in our GUI. */ tv.setText(parsedDataSet.toString()); } catch (Exception e) { /* Display any Error to the GUI. */ tv.setText("Error: " + e.getMessage()); Log.e(MY_DEBUG_TAG, "WeatherQueryError", e); } temp = Integer.parseInt(xml.parser.dataset.getTemp()); if(temp <0){ //layout.setBackgroundColor(Color.BLUE); //layout.setBackgroundColor(getResources().getColor(R.color.silver)); findViewById(R.id.flip).setBackgroundColor(Color.BLUE); } else if(temp > 0 && temp < 9) { //layout.setBackgroundColor(Color.GREEN); //layout.setBackgroundColor(getResources().getColor(R.color.silver)); findViewById(R.id.flip).setBackgroundColor(Color.GREEN); } else { //layout.setBackgroundColor(Color.YELLOW); //layout.setBackgroundColor(getResources().getColor(R.color.silver)); findViewById(R.id.flip).setBackgroundColor(Color.YELLOW); } /* Display the TextView. */ this.setContentView(tv); } @Override public void onClick(View arg0) { // TODO Auto-generated method stub onClick(View arg0) { // TODO Auto-generated method stub flip.showNext(); //specify flipping interval //flip.setFlipInterval(1000); //flip.startFlipping(); } } this is my dataset: package xml.parser; public class dataset { static String temp = null; // private int extractedInt = 0; public static String getTemp() { return temp; } public void setTemp(String temp) { this.temp = temp; } this is my handler: public void characters(char ch[], int start, int length) { if(this.in_temp){ String setTemp = new String(ch, start, length); // myParsedDataSet.setTempUnit(new String(ch, start, length)); // myParsedDataSet.setTemp; } the dataset and handler i only pasted the code that involves the temp as i no they r working when i take out the if statement. However even then my viewflipper wont work. This is my main xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/linearlayout1" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="25dip" android:text="Flip Example" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="25dip" android:id="@+id/tv" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25dip" android:text="Flip" android:id="@+id/btn" android:onClick="ClickHandler" /> <ViewFlipper android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/flip"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="25dip" android:text="Item1a" /> </LinearLayout> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="25dip" android:id="@+id/tv2" /> </ViewFlipper> </LinearLayout> this is my logcat: 04-01 18:02:24.744: E/AndroidRuntime(7331): FATAL EXCEPTION: main 04-01 18:02:24.744: E/AndroidRuntime(7331): java.lang.RuntimeException: Unable to start activity ComponentInfo{xml.parser/xml.parser.XmlParserActivity}: java.lang.NumberFormatException: unable to parse 'null' as integer 04-01 18:02:24.744: E/AndroidRuntime(7331): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1830) 04-01 18:02:24.744: E/AndroidRuntime(7331): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1851) 04-01 18:02:24.744: E/AndroidRuntime(7331): at android.app.ActivityThread.access$1500(ActivityThread.java:132) 04-01 18:02:24.744: E/AndroidRuntime(7331): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1038) 04-01 18:02:24.744: E/AndroidRuntime(7331): at android.os.Handler.dispatchMessage(Handler.java:99) 04-01 18:02:24.744: E/AndroidRuntime(7331): at android.os.Looper.loop(Looper.java:150) 04-01 18:02:24.744: E/AndroidRuntime(7331): at android.app.ActivityThread.main(ActivityThread.java:4293) 04-01 18:02:24.744: E/AndroidRuntime(7331): at java.lang.reflect.Method.invokeNative(Native Method) 04-01 18:02:24.744: E/AndroidRuntime(7331): at java.lang.reflect.Method.invoke(Method.java:507) 04-01 18:02:24.744: E/AndroidRuntime(7331): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849) 04-01 18:02:24.744: E/AndroidRuntime(7331): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607) 04-01 18:02:24.744: E/AndroidRuntime(7331): at dalvik.system.NativeStart.main(Native Method) 04-01 18:02:24.744: E/AndroidRuntime(7331): Caused by: java.lang.NumberFormatException: unable to parse 'null' as integer 04-01 18:02:24.744: E/AndroidRuntime(7331): at java.lang.Integer.parseInt(Integer.java:356) 04-01 18:02:24.744: E/AndroidRuntime(7331): at java.lang.Integer.parseInt(Integer.java:332) 04-01 18:02:24.744: E/AndroidRuntime(7331): at xml.parser.XmlParserActivity.onCreate(XmlParserActivity.java:118) 04-01 18:02:24.744: E/AndroidRuntime(7331): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1072) 04-01 18:02:24.744: E/AndroidRuntime(7331): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1794) I hope I have given enough information about my problems. I will be extremely grateful if anyone can help me out.

    Read the article

  • How to put Listview items into String Array?

    - by user2851687
    Im developing an app and as the title says how to put items of listview into String array, not string array to listview but listview to string array. I've been searching for this but what I only found is putting String array items into listview. Please help me thank you in advance. To clarify this thread, the question is how to put listview items into String array. Thanks. :D Codes public class DailyPlanTab extends Activity implements OnItemClickListener { ListView dailyPlanList; ArrayList<DailyManager> taskList = new ArrayList<DailyManager>(); DatabaseDailyPlan db; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.dailyplan_layout); dailyPlanList = (ListView) findViewById(R.id.lvDailyPlanList); dailyPlanList.setOnItemClickListener(this); ImageView add = (ImageView) findViewById(R.id.ivDailyPlanAdd); add.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent newDailyIntent = new Intent(getApplicationContext(), NewDailyPlan.class); startActivity(newDailyIntent); } }); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); taskList.clear(); db = new DatabaseDailyPlan(getApplicationContext()); db.getWritableDatabase(); ArrayList<DailyManager> tempList = db.getTask(); for (int i = 0; i < tempList.size(); i++) { String getTask = tempList.get(i).getDaily_name(); String getDate = tempList.get(i).getDaily_date(); int getId = tempList.get(i).getDaily_id(); DailyManager dm = new DailyManager(); dm.setDaily_name(getTask); dm.setDaily_date(getDate); dm.setDaily_id(getId); taskList.add(dm); } dailyPlanList.setAdapter(new ListAdapter(this)); // db.close(); } public class ListAdapter extends BaseAdapter { LayoutInflater inflater; ViewHolder viewHolder; public ListAdapter(Context c) { // TODO Auto-generated constructor stub inflater = LayoutInflater.from(c); } @Override public int getCount() { // TODO Auto-generated method stub return taskList.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub if (convertView == null) { convertView = inflater.inflate(R.layout.row_checklist_item, null); viewHolder = new ViewHolder(); viewHolder.taskTitle = (TextView) convertView .findViewById(R.id.tvCheckListItem); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.taskTitle.setText("" + taskList.get(position).getDaily_name()); return convertView; } } public class ViewHolder { TextView taskTitle, taskDate; } @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { // TODO Auto-generated method stub int taskId = taskList.get(position).getDaily_id(); String taskName = taskList.get(position).getDaily_name(); String taskDate = taskList.get(position).getDaily_date(); Intent newPlan = new Intent(getApplicationContext(), DailyPlan.class); newPlan.putExtra("task_id", taskId); newPlan.putExtra("task_name", taskName); startActivity(newPlan); } next is the information of the item inside the listview public class DailyPlan extends Activity implements OnItemClickListener { final ArrayList<DailyManager> savedItems = new ArrayList<DailyManager>(); ListView checkList; Boolean nextItem = false; TempManager tm; DatabaseTemp dbTemp; Intent i; int taskId = -1; String taskName = " ", taskDate = null; DatabaseDailyPlan db; DailyManager dm; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.saved_dailyplan); checkList = (ListView) findViewById(R.id.lvCheckList); // checkList.setOnItemClickListener(this); try { i = getIntent(); taskId = i.getExtras().getInt("task_id"); taskName = i.getExtras().getString("task_name"); Toast.makeText(getApplicationContext(), "From new id is" + taskId, 5000).show(); } catch (Exception e) { } Button addList = (Button) findViewById(R.id.bAddList); addList.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub // openDialog("", false, -1); } }); if (nextItem) { // openDialog("", false, -1); } } public void refresh() { DailyPlan.this.onResume(); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); savedItems.clear(); dbTemp = new DatabaseTemp(getApplicationContext()); dbTemp.getWritableDatabase(); db = new DatabaseDailyPlan(getApplicationContext()); db.getWritableDatabase(); if (taskId != -1) { // / For Load ArrayList<DailyManager> savedList = db.getList(taskId); for (int i = 0; i < savedList.size(); i++) { String savedListItems = savedList.get(i).getDaily_list(); String savedListTitle = savedList.get(i).getDaily_name(); String savedListDate = savedList.get(i).getDaily_date(); int savedListId = savedList.get(i).getDaily_id(); DailyManager dm = new DailyManager(); dm.setDaily_list(savedListItems); dm.setDaily_name(savedListTitle); dm.setDaily_date(savedListDate); dm.setDaily_id(savedListId); savedItems.add(dm); } } else { // / For New } checkList.setAdapter(new ListAdapter(this)); } public class ListAdapter extends BaseAdapter { LayoutInflater inflater; ViewHolder viewHolder; public ListAdapter(Context c) { // TODO Auto-generated constructor stub inflater = LayoutInflater.from(c); } @Override public int getCount() { // TODO Auto-generated method stub return savedItems.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub if (convertView == null) { convertView = inflater.inflate(R.layout.row_checklist_item, null); viewHolder = new ViewHolder(); viewHolder.checkListItem = (TextView) convertView .findViewById(R.id.tvCheckListItem); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.checkListItem.setText(savedItems.get(position) .getDaily_list() + position); final int temp = position; return convertView; } } private class ViewHolder { TextView checkListItem; } @Override public void onItemClick(AdapterView<?> arg0, View arg1, int item, long arg3) { // TODO Auto-generated method stub // openDialog(savedItems.get(item).getDaily_name(), true, // savedItems.get(item).getDaily_id()); } }

    Read the article

  • Trying to get around this Webservice call from Android using AsycTask

    - by Kevin Rave
    I am a fairly beginner in Android Development. I am developing an application that extensively relays on Webservice calls. First screen takes username and password and validates the user by calling the Webservice. If U/P is valid, then I need to fire up the 2nd activity. In that 2nd activity, I need to do 3 calls. But I haven't gotten to the 2nd part yet. In fact, I haven't completed the full coding yet. But I wanted to test if the app is working as far as I've come through. When calling webserivce, I am showing alert dialog. But the app is crashing somewhere. The LoginActivity shows up. When I enter U/P and press Login Button, it crashes. My classes: TaskHandler.java public class TaskHandler { private String URL; private User userObj; private String results; private JSONDownloaderTask task; ; public TaskHandler( String url, User user) { this.URL = url; this.userObj = user; } public String handleTask() { Log.d("Two", "In the function"); task = new JSONDownloaderTask(); Log.d("Three", "In the function"); task.execute(URL); return results; } private class JSONDownloaderTask extends AsyncTask<String, Void, String> { private String username;// = userObj.getUsername(); private String password; //= userObj.getPassword(); public HttpStatus status_code; public JSONDownloaderTask() { Log.d("con", "Success"); this.username = userObj.getUsername(); this.password = userObj.getPassword(); Log.d("User" + this.username , " Pass" + this.password); } private AsyncProgressActivity progressbar = new AsyncProgressActivity(); @Override protected void onPreExecute() { progressbar.showLoadingProgressDialog(); } @Override protected String doInBackground(String... params) { final String url = params[0]; //getString(R.string.api_staging_uri) + "Authenticate/"; // Populate the HTTP Basic Authentitcation header with the username and password HttpAuthentication authHeader = new HttpBasicAuthentication(username, password); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setAuthorization(authHeader); requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); // Create a new RestTemplate instance RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); try { // Make the network request Log.d(this.getClass().getName(), url); ResponseEntity<Message> response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<Object>(requestHeaders), Message.class); status_code = response.getStatusCode(); return response.getBody().toString(); } catch (HttpClientErrorException e) { status_code = e.getStatusCode(); return new Message(0, e.getStatusText(), e.getLocalizedMessage(), "error").toString(); } catch ( Exception e ) { Log.d(this.getClass().getName() ,e.getLocalizedMessage()); return "Unknown Exception"; } } @Override protected void onPostExecute(String result) { progressbar.dismissProgressDialog(); switch ( status_code ) { case UNAUTHORIZED: result = "Invalid username or passowrd"; break; case ACCEPTED: result = "Invalid username or passowrd" + status_code; break; case OK: result = "Successful!"; break; } } } } AsycProgressActivity.java public class AsyncProgressActivity extends Activity { protected static final String TAG = AsyncProgressActivity.class.getSimpleName(); private ProgressDialog progressDialog; private boolean destroyed = false; @Override protected void onDestroy() { super.onDestroy(); destroyed = true; } public void showLoadingProgressDialog() { Log.d("Here", "Progress"); this.showProgressDialog("Authenticating..."); Log.d("Here", "afer p"); } public void showProgressDialog(CharSequence message) { Log.d("Here", "Message"); if (progressDialog == null) { progressDialog = new ProgressDialog(this); progressDialog.setIndeterminate(true); } Log.d("Here", "Message 2"); progressDialog.setMessage(message); progressDialog.show(); } public void dismissProgressDialog() { if (progressDialog != null && !destroyed) { progressDialog.dismiss(); } } } LoginActivity.java public class LoginActivity extends AsyncProgressActivity implements OnClickListener { Button login_button; HttpStatus status_code; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); login_button = (Button) findViewById(R.id.btnLogin); login_button.setOnClickListener(this); ViewServer.get(this).addWindow(this); } public void onDestroy() { super.onDestroy(); ViewServer.get(this).removeWindow(this); } public void onResume() { super.onResume(); ViewServer.get(this).setFocusedWindow(this); } public void onClick(View v) { if ( v.getId() == R.id.btnLogin ) { User userobj = new User(); String result; userobj.setUsername( ((EditText) findViewById(R.id.username)).getText().toString()); userobj.setPassword(((EditText) findViewById(R.id.password)).getText().toString() ); TaskHandler handler = new TaskHandler(getString(R.string.api_staging_uri) + "Authenticate/", userobj); Log.d(this.getClass().getName(), "One"); result = handler.handleTask(); Log.d(this.getClass().getName(), "After two"); Utilities.showAlert(result, LoginActivity.this); } } Utilities.java public class Utilities { public static void showAlert(String message, Context context) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); alertDialogBuilder.setTitle("Login"); alertDialogBuilder.setMessage(message) .setCancelable(false) .setPositiveButton("OK",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.dismiss(); //dialog.cancel(); } }); alertDialogBuilder.setIcon(drawable.ic_dialog_alert); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } }

    Read the article

  • How do I search the MediaStore for a specific directory instead of entire external storage?

    - by Nick Lopez
    In my app I have an option that allows users to browse for audio files on their phone to add to the app. I am having trouble however with creating a faster way of processing the query code. Currently it searches the entire external storage and causes the phone to prompt a force close/wait warning. I would like to take the code I have posted below and make it more efficient by either searching in a specific folder on the phone or by streamlining the process to make the file search quicker. I am not sure how to do this however. Thanks! public class BrowseActivity extends DashboardActivity implements OnClickListener, OnItemClickListener { private List<Sound> soundsInDevice = new ArrayList<Sound>(); private List<Sound> checkedList; private ListView browsedList; private BrowserSoundAdapter adapter; private long categoryId; private Category category; private String currentCategoryName; private String description; // private Category newCategory ; private Button doneButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_browse); checkedList = new ArrayList<Sound>(); browsedList = (ListView) findViewById(android.R.id.list); doneButton = (Button) findViewById(R.id.doneButton); soundsInDevice = getMediaSounds(); if (soundsInDevice.size() > 0) { adapter = new BrowserSoundAdapter(this, R.id.browseSoundName, soundsInDevice); } else { Toast.makeText(getApplicationContext(), getString(R.string.no_sounds_available), Toast.LENGTH_SHORT) .show(); } browsedList.setAdapter(adapter); browsedList.setOnItemClickListener(this); doneButton.setOnClickListener(this); } private List<Sound> getMediaSounds() { List<Sound> mediaSoundList = new ArrayList<Sound>(); ContentResolver cr = getContentResolver(); String[] projection = {MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.DURATION}; final Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; Log.v("MediaStore.Audio.Media.EXTERNAL_CONTENT_URI", "" + uri); final Cursor cursor = cr.query(uri, projection, null, null, null); int n = cursor.getCount(); Log.v("count", "" + n); if (cursor.moveToFirst()) { do { String soundName = cursor .getString(cursor .getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME)); Log.v("soundName", "" + soundName); String title = cursor .getString(cursor .getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)); Log.v("title", "" + title); String path = cursor.getString(cursor .getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)); Log.v("path", "" + path); Sound browsedSound = new Sound(title, path, false, false, false, false, 0); Log.v("browsedSound", "" + browsedSound); mediaSoundList.add(browsedSound); Log.v("mediaSoundList", "" + mediaSoundList.toString()); } while (cursor.moveToNext()); } return mediaSoundList; } public class BrowserSoundAdapter extends ArrayAdapter<Sound> { public BrowserSoundAdapter(Context context, int textViewResourceId, List<Sound> objects) { super(context, textViewResourceId, objects); } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; View view = convertView; LayoutInflater inflater = getLayoutInflater(); if (view == null) { view = inflater.inflate(R.layout.list_item_browse, null); viewHolder = new ViewHolder(); viewHolder.soundNameTextView = (TextView) view .findViewById(R.id.browseSoundName); viewHolder.pathTextView = (TextView) view .findViewById(R.id.browseSoundPath); viewHolder.checkToAddSound = (CheckBox) view .findViewById(R.id.browse_checkbox); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) view.getTag(); } final Sound sound = soundsInDevice.get(position); if (sound.isCheckedState()) { viewHolder.checkToAddSound.setChecked(true); } else { viewHolder.checkToAddSound.setChecked(false); } viewHolder.soundNameTextView.setText(sound.getName()); viewHolder.pathTextView.setText(sound.getUri()); viewHolder.checkToAddSound .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { CheckBox cb = (CheckBox) v .findViewById(R.id.browse_checkbox); boolean checked = cb.isChecked(); boolean newValue = checked; updateView(position, newValue); doneButtonStatus(checkedList.size()); } }); return view; } } // Adapter view holder class private class ViewHolder { private TextView soundNameTextView; private TextView pathTextView; private CheckBox checkToAddSound; } // done button On Click @Override public void onClick(View view) { boolean status = getIntent().getBooleanExtra("FromAddCat", false); Log.v("for add category","enters in if"); if(status){ Log.v("for add category","enters in if1"); currentCategoryName = getIntent().getStringExtra("categoryName"); description = getIntent().getStringExtra("description"); boolean existCategory = SQLiteHelper.getCategoryStatus(currentCategoryName); if (!existCategory) { category = new Category(currentCategoryName, description, false); category.insert(); category.update(); Log.v("for add category","enters in if2"); } }else{ categoryId = getIntent().getLongExtra("categoryId",-1); category = SQLiteHelper.getCategory(categoryId); } for (Sound checkedsound : checkedList) { checkedsound.setCheckedState(false); checkedsound.insert(); category.getSounds().add(checkedsound); final Intent intent = new Intent(this, CategoriesActivity.class); finish(); startActivity(intent); } } @Override public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) { boolean checked = true; boolean newValue = false; CheckBox cb = (CheckBox) view.findViewById(R.id.browse_checkbox); if (cb.isChecked()) { cb.setChecked(!checked); newValue = !checked; } else { cb.setChecked(checked); newValue = checked; } updateView(position, newValue); doneButtonStatus(checkedList.size()); } private void doneButtonStatus(int size) { if (size > 0) { doneButton.setEnabled(true); doneButton.setBackgroundResource(R.drawable.done_button_drawable); } else { doneButton.setEnabled(false); doneButton.setBackgroundResource(R.drawable.done_btn_disabled); } } private void updateView(int index, boolean newValue) { System.out.println(newValue); Sound sound = soundsInDevice.get(index); if (newValue == true) { checkedList.add(sound); sound.setCheckedState(newValue); } else { checkedList.remove(sound); sound.setCheckedState(newValue); } } }

    Read the article

  • How to set message when I get Exception

    - by user1748932
    public class XMLParser { // constructor public XMLParser() { } public String getXmlFromUrl(String url) { String responseBody = null; getset d1 = new getset(); String d = d1.getData(); // text String y = d1.getYear(); // year String c = d1.getCircular(); String p = d1.getPage(); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("YearID", y)); nameValuePairs.add(new BasicNameValuePair("CircularNo", c)); nameValuePairs.add(new BasicNameValuePair("SearchText", d)); nameValuePairs.add(new BasicNameValuePair("pagenumber", p)); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); responseBody = EntityUtils.toString(entity); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // return XML return responseBody; } public Document getDomElement(String xml) { Document doc = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); doc = db.parse(is); } catch (ParserConfigurationException e) { Log.e("Error: ", e.getMessage()); return null; } catch (SAXException e) { Log.e("Error: ", e.getMessage()); // i m getting Exception here return null; } catch (IOException e) { Log.e("Error: ", e.getMessage()); return null; } return doc; } /** * Getting node value * * @param elem * element */ public final String getElementValue(Node elem) { Node child; if (elem != null) { if (elem.hasChildNodes()) { for (child = elem.getFirstChild(); child != null; child = child .getNextSibling()) { if (child.getNodeType() == Node.TEXT_NODE) { return child.getNodeValue(); } } } } return ""; } /** * Getting node value * * @param Element * node * @param key * string * */ public String getValue(Element item, String str) { NodeList n = item.getElementsByTagName(str); return this.getElementValue(n.item(0)); } } I am getting Exception in this class for parsing data. I want print this message in another class which extends from Activity. Can you please tell me how? I tried much but not able to do.. public class AndroidXMLParsingActivity extends Activity { public int currentPage = 1; public ListView lisView1; static final String KEY_ITEM = "docdetails"; static final String KEY_NAME = "heading"; public Button btnNext; public Button btnPre; public static String url = "http://dev.taxmann.com/TaxmannService/TaxmannService.asmx/GetNotificationList"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // listView1 lisView1 = (ListView) findViewById(R.id.listView1); // Next btnNext = (Button) findViewById(R.id.btnNext); // Perform action on click btnNext.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { currentPage = currentPage + 1; ShowData(); } }); // Previous btnPre = (Button) findViewById(R.id.btnPre); // Perform action on click btnPre.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { currentPage = currentPage - 1; ShowData(); } }); ShowData(); } public void ShowData() { XMLParser parser = new XMLParser(); String xml = parser.getXmlFromUrl(url); // getting XML Document doc = parser.getDomElement(xml); // getting DOM element NodeList nl = doc.getElementsByTagName(KEY_ITEM); int displayPerPage = 5; // Per Page int TotalRows = nl.getLength(); int indexRowStart = ((displayPerPage * currentPage) - displayPerPage); int TotalPage = 0; if (TotalRows <= displayPerPage) { TotalPage = 1; } else if ((TotalRows % displayPerPage) == 0) { TotalPage = (TotalRows / displayPerPage); } else { TotalPage = (TotalRows / displayPerPage) + 1; // 7 TotalPage = (int) TotalPage; // 7 } int indexRowEnd = displayPerPage * currentPage; // 5 if (indexRowEnd > TotalRows) { indexRowEnd = TotalRows; } // Disabled Button Next if (currentPage >= TotalPage) { btnNext.setEnabled(false); } else { btnNext.setEnabled(true); } // Disabled Button Previos if (currentPage <= 1) { btnPre.setEnabled(false); } else { btnPre.setEnabled(true); } // Load Data from Index int RowID = 1; ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>(); HashMap<String, String> map; // RowID if (currentPage > 1) { RowID = (displayPerPage * (currentPage - 1)) + 1; } for (int i = indexRowStart; i < indexRowEnd; i++) { Element e = (Element) nl.item(i); // adding each child node to HashMap key => value map = new HashMap<String, String>(); map.put("RowID", String.valueOf(RowID)); map.put(KEY_NAME, parser.getValue(e, KEY_NAME)); // adding HashList to ArrayList menuItems.add(map); RowID = RowID + 1; } SimpleAdapter sAdap; sAdap = new SimpleAdapter(AndroidXMLParsingActivity.this, menuItems, R.layout.list_item, new String[] { "RowID", KEY_NAME }, new int[] { R.id.ColRowID, R.id.ColName }); lisView1.setAdapter(sAdap); } } This my class where I want to Print that message

    Read the article

  • Android - passing data between Activities

    - by Bill Osuch
    (To follow along with this, you should understand the basics of starting new activities: Link ) The easiest way to pass data from one activity to another is to create your own custom bundle and pass it to your new class. First, create two new activities called Search and SearchResults (make sure you add the second one you create to the AndroidManifest.xml file!), and create xml layout files for each. Search's file should look like this: <?xml version="1.0" encoding="utf-8"?> <LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="fill_parent"     android:layout_height="fill_parent"     android:orientation="vertical">     <TextView          android:layout_width="fill_parent"      android:layout_height="wrap_content"      android:text="Name:"/>     <EditText                android:id="@+id/edittext"         android:layout_width="fill_parent"         android:layout_height="wrap_content"/>     <TextView          android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:text="ID Number:"/>     <EditText                android:id="@+id/edittext2"                android:layout_width="fill_parent"                android:layout_height="wrap_content"/>     <Button           android:id="@+id/btnSearch"          android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:text="Search" /> </LinearLayout> and SearchResult's should look like this: <?xml version="1.0" encoding="utf-8"?> <LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="fill_parent"     android:layout_height="fill_parent"     android:orientation="vertical">     <TextView          android:id="@+id/txtName"         android:layout_width="fill_parent"         android:layout_height="wrap_content"/>     <TextView          android:id="@+id/txtState"         android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:text="No data"/> </LinearLayout> Next, we'll override the OnCreate method of Search: @Override public void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.search);     Button search = (Button) findViewById(R.id.btnSearch);     search.setOnClickListener(new View.OnClickListener() {         public void onClick(View view) {                           Intent intent = new Intent(Search.this, SearchResults.class);              Bundle b = new Bundle();                           EditText txt1 = (EditText) findViewById(R.id.edittext);             EditText txt2 = (EditText) findViewById(R.id.edittext2);                                      b.putString("name", txt1.getText().toString());             b.putInt("state", Integer.parseInt(txt2.getText().toString()));                              //Add the set of extended data to the intent and start it             intent.putExtras(b);             startActivity(intent);          }     }); } This is very similar to the previous example, except here we're creating our own bundle, adding some key/value pairs to it, and adding it to the intent. Now, to retrieve the data, we just need to grab the Bundle that was passed to the new Activity and extract our values from it: @Override public void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.search_results);     Bundle b = getIntent().getExtras();     int value = b.getInt("state", 0);     String name = b.getString("name");             TextView vw1 = (TextView) findViewById(R.id.txtName);     TextView vw2 = (TextView) findViewById(R.id.txtState);             vw1.setText("Name: " + name);     vw2.setText("State: " + String.valueOf(value)); }

    Read the article

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