1

I am trying to store a phone number that is chosen from the contacts into a string or anything so that I can call it from the different class... This is my code for contact button

@Override
protected void onCreate(Bundle savedInstanceState)
{
    // initialize
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu);
    //vi1 = (TextView) findViewById (R.id.textView1);
    co1 = (Button) findViewById (R.id.button3);
    co1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            startActivityForResult(intent, PICK_CONTACT);
        }
    });

}

And this is for the onActivityResult to show it to the textview

@Override  
protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    if (resultCode == RESULT_OK) {  
        switch (requestCode) {  
        case PICK_CONTACT:
        final TextView vi1 = (TextView) findViewById(R.id.textView1);
        Cursor cursor = null;  
        String phoneNumber = "";
        List<String> allNumbers = new ArrayList<String>();
        int phoneIdx = 0;
        try {  
            Uri result = data.getData();  
            String id = result.getLastPathSegment();  
            cursor = getContentResolver().query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + "=?", new String[] { id }, null);  
            phoneIdx = cursor.getColumnIndex(Phone.DATA);
            if (cursor.moveToFirst()) {
                while (cursor.isAfterLast() == false) {
                phoneNumber = cursor.getString(phoneIdx);
                allNumbers.add(phoneNumber);
                cursor.moveToNext();}
             } else {
                    //no results actions
                }  
            } catch (Exception e) {  
               //error actions
            } finally {  
                if (cursor != null) {  
                    cursor.close();
                }

                final CharSequence[] items = allNumbers.toArray(new String[allNumbers.size()]);
                AlertDialog.Builder builder = new AlertDialog.Builder(MenuActivity.this);
                builder.setTitle("Choose a number");
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        String selectedNumber = items[item].toString();
                        selectedNumber = selectedNumber.replace("-", "");
                        vi1.setText(selectedNumber);
                    }
                });
                AlertDialog alert = builder.create();
                if(allNumbers.size() > 1) {
                    alert.show();
                } else {
                    String selectedNumber = phoneNumber.toString();
                    selectedNumber = selectedNumber.replace("-", "");
                    vi1.setText(selectedNumber);
                }

                if (phoneNumber.length() == 0) {  
                    //no numbers found actions  
                }  
            }  
            break;  
        }  
    } else {
       //activity result error actions
    }  
}

I wanted to store the output on the textview into a string or any type of other forms so that I can call it on a different class. Please help me. Thank you!

user2349228
  • 19
  • 1
  • 6

1 Answers1

4

There are couple of ways by which you can access variable in other classes or Activity.

  1. Database
  2. shared prefrences.
  3. Object serialization.
  4. A class which can hold common data can be named as Common Utilities it depends on you.

It depend upon your project needs.

A. Database

SQLite is an Open Source Database which is embedded into Android. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements.

Tutorials -- http://www.vogella.com/articles/AndroidSQLite/article.html

B. Shared Preferences

Suppose you want to store username. So there will be now two thing a Key Username, Value Value.

How to store

 // Create object of SharedPreferences.
 SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
 //now get Editor
 SharedPreferences.Editor editor = sharedPref.edit();
 //put your value
 editor.putString("userName", "stackoverlow");

 //commits your edits
 editor.commit();

Using putString(),putBoolean(),putInt(),putFloat(),putLong() you can save your desired dtatype.

How to fetch

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref.getString("userName", "Not Available");

http://developer.android.com/reference/android/content/SharedPreferences.html

C. Object Serialization

Object serlization is used if we want to save an object state to send it over network or you can use it for your purpose also.

Use java beans and store in it as one of his fields and use getters and setter for that

JavaBeans are Java classes that have properties. Think of properties as private instance variables. Since they're private, the only way they can be accessed from outside of their class is through methods in the class. The methods that change a property's value are called setter methods, and the methods that retrieve a property's value are called getter methods.

public class VariableStorage implements Serializable  {

    private String inString ;

    public String getInString() {
        return inString;
    }

    public void setInString(String inString) {
        this.inString = inString;
    }


}

Set the variable in you mail method by using

VariableStorage variableStorage = new VariableStorage();
variableStorage.setInString(inString);

Then use object Serialzation to serialize this object and in your other class deserialize this object.

In serialization an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

If you want tutorial for this refer this link

http://javawithswaranga.blogspot.in/2011/08/serialization-in-java.html

Get variable in other classes

D. CommonUtilities

You can make a class by your self which can contain common data which you frequently need in your project.

Sample

public class CommonUtilities {

    public static String className = "CommonUtilities";

}
Community
  • 1
  • 1
Nikhil Agrawal
  • 26,128
  • 21
  • 90
  • 126