Export data in android

Source: Internet
Author: User

The idea is simple:

1. Read the database data and process it as needed.

2. Write Data to the SD card

The following uses the export system contact as an example:

MainActivity:

Package com. home. exportcontact; import java. io. file; import java. io. fileWriter; import java. io. IOException; import android. app. activity; import android. app. alertDialog; import android. content. context; import android. content. dialogInterface; import android. database. cursor; import android. OS. bundle; import android. OS. environment; import android. OS. handler; import android. OS. message; import android. provider. contac TsContract; import android. provider. contactsContract. commonDataKinds. phone; import android. provider. contactsContract. commonDataKinds. structuredName; import android. provider. contactsContract. contacts. data; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. textView; public class MainActivity extends Activity implements OnClickListener {pr Ivate Button exportBtn; // export Button private TextView showText; // display progress text // export the location of the txt file private final static String OUTPUT_PATH = Environment. getExternalStorageDirectory () + "/my contacts .txt"; private static final int OUTPUT_FAIL = 0; // export Failure Identification private static final int OUTPUT_SUCCESS = 1; // export success identification private static int count; // export the Contact Count private Thread mOutputThread; // export the contact Thread // space private static final String SPACE_1 =" "; Private static final String SPACE_2 = SPACE_1 + SPACE_1; private static final String SPACE_4 = SPACE_2 + SPACE_2; private static final String SPACE_8 = SPACE_4 + SPACE_4; private static final String SPACE_11 = SPACE_8 + SPACE_2 + SPACE_1; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); exportBtn = (Button) findViewById (R. Id. main_btn_export); exportBtn. setOnClickListener (this); showText = (TextView) findViewById (R. id. main_ TV _show) ;}@ Overridepublic void onClick (View v) {if (v = exportBtn) {outputContact ();}} /*** export contact entry */private void outputContact () {File file = new File (OUTPUT_PATH); if (! File. exists () {startOutputContact ();} else {createDialog (this, "warning", "my contact .txt already exists, overwrite? ") ;}}/*** Create prompt dialog box ** @ param context * @ param title * @ param message */private void createDialog (Context context, String title, String message) {AlertDialog. builder builder = new AlertDialog. builder (context); builder. setTitle (title); builder. setMessage (message); builder. setPositiveButton ("OK", new DialogInterface. onClickListener () {public void onClick (DialogInterface dialog, int whichButton) {startOu TputContact () ;}}); builder. setNeutralButton ("cancel", new DialogInterface. onClickListener () {public void onClick (DialogInterface dialog, int whichButton) {dialog. cancel () ;}}); builder. show ();}/*** enable the export contact subthread */private void startOutputContact () {setOutputWidgetEnabled (false); showText. setText ("exporting contact... "); if (mOutputThread! = Null) {mOutputThread. interrupt (); mOutputThread = null;} mOutputThread = new Thread (new OutputRunnable (this); if (mOutputThread! = Null) {mOutputThread. start () ;}}/*** set the availability of the exported component */private void setOutputWidgetEnabled (boolean enabled) {exportBtn. setEnabled (enabled); if (! Enabled) {showText. setText ("") ;}} class OutputRunnable implements Runnable {private Context context; public OutputRunnable (Context context) {this. context = context ;}@ Overridepublic void run () {boolean result = doOutputContact (context); if (result) {handler. sendEmptyMessage (OUTPUT_SUCCESS);} else {handler. sendEmptyMessage (OUTPUT_FAIL) ;}}/ *** handle UI prompts */private Handler handler = new Handler () {public Void handleMessage (Message msg) {if (msg. what = OUTPUT_SUCCESS) {showText. setText (String. format ("% d contact records exported successfully", count); setOutputWidgetEnabled (true);} else if (msg. what = OUTPUT_FAIL) {showText. setText ("failed to import the contact"); setOutputWidgetEnabled (true );}}}; /*** export the contact from the database ** @ param context * @ return indicates whether the contact is successful */private boolean doOutputContact (Context context) {count = 0; try {String result = readFromConta CtDatabase (context); writeFile (OUTPUT_PATH, result);} catch (Exception e) {return false;} return true ;} /*** read contact information from the database ** @ param context * @ return information result */private String readFromContactDatabase (Context context) {StringBuilder resultBuilder = new StringBuilder (); cursor cursor = context. getContentResolver (). query (ContactsContract. data. CONTENT_URI, new String [] {StructuredName. DISPLAY_NAME, Data. RA W_CONTACT_ID}, Data. MIMETYPE + "=? ", New String [] {StructuredName. CONTENT_ITEM_TYPE}, null); while (cursor. moveToNext () {// obtain the name and the IDString displayName = cursor of each row. getString (0); int id = cursor. getInt (1); // get the Cursor mobileCursor = context of the phone number. getContentResolver (). query (ContactsContract. data. CONTENT_URI, new String [] {Phone. NUMBER}, Data. RAW_CONTACT_ID + "=" + id + "AND" + Data. DATA2 + "=" + 2, null, null); String mobileNum = ""; If (mobileCursor. moveToNext () {mobileNum = mobileCursor. getString (0);} mobileCursor. close (); // obtain the home phone number Cursor homeCursor = context. getContentResolver (). query (ContactsContract. data. CONTENT_URI, new String [] {Phone. NUMBER}, Data. RAW_CONTACT_ID + "=" + id + "AND" + Data. DATA2 + "=" + 1, null, null); String homeNum = ""; if (homeCursor. moveToNext () {homeNum = homeCursor. getString (0);} homeCursor. Close (); if (displayName! = Null &&! "". Equals (displayName) {String result = displayName + SPACE_4; if ("". equals (mobileNum) {result + = SPACE_11;} else {result + = mobileNum;} result + = SPACE_8 + homeNum + '\ n'; String checkString = resultBuilder. toString (); if (! CheckString. contains (result) & ("". equals (mobileNum) |! CheckString. contains (mobileNum) {resultBuilder. append (result); count ++ ;}} cursor. close (); return resultBuilder. toString ();}/*** write the contact information to SD ** @ param path * @ param info */private void writeFile (String path, String info) {try {File file = new File (path); FileWriter writer = new FileWriter (file, false); writer. write (info); writer. close ();} catch (IOException e) {e. printStackTrace ();}}}

Layout:

     
      
  
 

Permission:

 
  
  
 




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.