2016-06-27 15 views
2

私はリストビューから連絡先を選択してその番号を.csvファイルに書き込む必要があるAndroidのアクティビティに取り組んでいます。リストビューから連絡先を選択し、Androidで電話番号を取得

しかし、私はボタンクリックで連絡先からすべての連絡先番号を書き込むことができました。しかし今、私はListViewから連絡先を選択したいのですが、クリックすると、選択した連絡先のみがファイルに書き込まれます。

私は自分のコードを提供しています。親切に私はこれをどのように達成できますか?

upload_contacts.java:私はリストビューから選択した連絡先を取得し、ファイルを.csvにだけ自分の番号を書くことができるように

public class Upload_Contacts extends ListActivity { 

private String[] arraySpinner; 
Spinner spin ; 
String adi; 


ToggleButton rdb; 

private Cursor cursor; 
private boolean csv_status = false; 

    Button btn; 
    public String[] Contacts = {}; 
    public int[] to = {}; 
    public ListView myListView; 

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.p_contacts); 

     btn=(Button)findViewById(R.id.btvc); 
     rdb=(ToggleButton)findViewById(R.id.rdb); 



      btn.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 



        createCSV();// here I can write all contacts to file. I want only selected contacts to write, and also if all contacts selected they should also be written in file//// 



          String selected = ""; 



          int cntChoice = myListView.getCount(); 

          SparseBooleanArray sparseBooleanArray = myListView.getCheckedItemPositions(); 

          for(int i = 0; i < cntChoice; i++){ 

           if(sparseBooleanArray.get(i)) { 

            selected += myListView.getItemAtPosition(i).toString() + "\n"; 



           } 

          } 



          Toast.makeText(Upload_Contacts.this, 

    selected, //android.content.ContentResolver [email protected] 
      // here i want to show number against the contact selected . 


            Toast.LENGTH_LONG).show(); 


       } 
      }); 



      Cursor mCursor = getContacts(); 
      startManagingCursor(mCursor); 


     // here showing contacts in listview with check box.. 

      ListAdapter adapter2 = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, mCursor, 
        Contacts = new String[] {ContactsContract.Contacts.DISPLAY_NAME }, 
        to = new int[] { android.R.id.text1 }); 
        setListAdapter(adapter2); 
        myListView = getListView(); 
        myListView.setItemsCanFocus(false); 
        myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 




        // here I checked all the contacts in list view 
        rdb.setOnClickListener(new View.OnClickListener() { 
          public void onClick(View v) { 
          // Toast.makeText(InCallScreen.this, "selected all", Toast.LENGTH_SHORT).show(); 
          if(rdb.isChecked()){ 
            rdb.setBackgroundColor(Color.parseColor("#FBE039")); 

            rdb.setTextColor(Color.parseColor("#000000")); 

            for (int i = 0; i < myListView.getCount(); i++) 
            myListView.setItemChecked(i, true); 



          } 
            else{ 
             rdb.setBackgroundColor(Color.parseColor("#333333")); 
             rdb.setTextColor(Color.parseColor("#ffffff")); 




             for (int i = 0; i < myListView.getCount(); i++) 
             myListView.setItemChecked(i, false); 



            } 
          } 
         }); 


} 


// here showing contacts name in listview.. 
private Cursor getContacts() { 
    // Run query 
    Uri uri = ContactsContract.Contacts.CONTENT_URI; 
    String[] projection = new String[] { ContactsContract.Contacts._ID, 
            ContactsContract.Contacts.DISPLAY_NAME}; 
    String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '" 
      + ("1") + "'"; 
    String[] selectionArgs = null; 
    String sortOrder = ContactsContract.Contacts.DISPLAY_NAME 
      + " COLLATE LOCALIZED ASC"; 

    return managedQuery(uri, projection, selection, selectionArgs, 
      sortOrder); 
} 



private void createCSV() { 
     CSVWriter writer = null; 
     try { 
      writer = new CSVWriter(new FileWriter(Environment.getExternalStorageDirectory().getAbsolutePath() + "/my_test_contact.csv")); 
     } catch (IOException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } 
     String displayName; 
     String number; 
     long _id; 
     String columns[] = new String[]{ ContactsContract.Contacts._ID, 
        ContactsContract.Contacts.DISPLAY_NAME }; 
     writer.writeColumnNames(); // Write column header 
     Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, 
        columns,     
        null,    
        null,    
        ContactsContract.Data.DISPLAY_NAME + " COLLATE LOCALIZED ASC"); 
     startManagingCursor(cursor); 

     if(cursor.moveToFirst()) { 
      do { 
       _id = Long.parseLong(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID))); 
       //displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)).trim(); 
       number = getPrimaryNumber(_id); 

       // Log.d("numbers", number+" "); 

       writer.writeNext((/*displayName + */ "/" + number).split("/")); 
      } while(cursor.moveToNext()); 

      csv_status = true; 

     } else { 
      csv_status = false; 

     } 
     try { 
      if(writer != null) 
       writer.close(); 

     } catch (IOException e) { 
      Log.w("Test", e.toString()); 
     } 

    }// Method close. 


    private void exportCSV() { 
     if(csv_status == true) { 
      //CSV file is created so we need to Export that ... 
      final File CSVFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/my_test_contact.csv"); 
      //Log.i("SEND EMAIL TESTING", "Email sending"); 
      Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); 
      emailIntent.setType("text/csv"); 
      emailIntent .putExtra(android.content.Intent.EXTRA_SUBJECT, "Test contacts ");   
      emailIntent .putExtra(android.content.Intent.EXTRA_TEXT, "\n\nAdroid developer\n Adnan"); 
      emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + CSVFile.getAbsolutePath())); 
      emailIntent.setType("message/rfc822"); // Shows all application that supports SEND activity 
      try { 
       startActivity(Intent.createChooser(emailIntent, "Send mail...")); 
      } catch (android.content.ActivityNotFoundException ex) { 
       Toast.makeText(getApplicationContext(), "Email client : " + ex.toString(), Toast.LENGTH_SHORT); 
      } 
     } else { 
      Toast.makeText(getApplicationContext(), "Information not available to create CSV.", Toast.LENGTH_SHORT).show(); 
     } 
    } 
     /** 
     * Get primary Number of requested id. 
     * 
     * @return string value of primary number. 
     */ 
     private String getPrimaryNumber(long _id) { 
      String primaryNumber = null; 
      try { 
       Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
         new String[]{Phone.NUMBER, Phone.TYPE}, 
         ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ _id, // We need to add more selection for phone type 
         null, 
         null); 
       if(cursor != null) { 
        while(cursor.moveToNext()){ 
         switch(cursor.getInt(cursor.getColumnIndex(Phone.TYPE))){ 
          case Phone.TYPE_MOBILE : 
           primaryNumber = cursor.getString(cursor.getColumnIndex(Phone.NUMBER)); 
           break; 
          case Phone.TYPE_HOME : 
           primaryNumber = cursor.getString(cursor.getColumnIndex(Phone.NUMBER)); 
           break; 
          case Phone.TYPE_WORK : 
           primaryNumber = cursor.getString(cursor.getColumnIndex(Phone.NUMBER)); 
           break; 
          default: 
           primaryNumber = cursor.getString(cursor.getColumnIndex(Phone.NUMBER)); 
         } 
         if(primaryNumber != null) 
          break; 

        } 
       }  
      } catch (Exception e) { 
       Log.i("test", "Exception " + e.toString()); 
      } finally { 
       if(cursor != null) { 
        cursor.deactivate(); 
        cursor.close();    
       } 
      } 
      return primaryNumber; 
     } 

} 

私はcreate.csv方法で何をすべき?

編集は:

私は、問題を解決しました。

ここではカスタムアダプタを使用してタスクを実行します。今アクティビティに電話連絡先のリストがあり、チェックボックスから連絡先を選択し、その番号を.csvファイルに書き込むことができます。ここでは、CSVライタークラス:

CSVwriter.java:

public class CSVWriter { 

    private PrintWriter pw; 
    private char separator; 
    private char quotechar; 
    private char escapechar; 
    private String lineEnd; 

    /** The character used for escaping quotes. */ 
    public static final char DEFAULT_ESCAPE_CHARACTER = '\u0000'; 

    /** The default separator to use if none is supplied to the constructor. */ 
    public static final char DEFAULT_SEPARATOR = '\n'; 

    /** 
    * The default quote character to use if none is supplied to the 
    * constructor. 
    */ 
    public static final char DEFAULT_QUOTE_CHARACTER = '\u0000'; 

    /** The quote constant to use when you wish to suppress all quoting. */ 
    public static final char NO_QUOTE_CHARACTER = '\u0000'; 

    /** The escape constant to use when you wish to suppress all escaping. */ 
    public static final char NO_ESCAPE_CHARACTER = '\u0000'; 

    /** Default line terminator uses platform encoding. */ 
    public static final String DEFAULT_LINE_END = "\n"; 

    /** Default column name. */ 
    public static final String DEFAULT_COLUMN_NAME = "Phone Number"; 

    /** 
    * Constructs CSVWriter using a comma for the separator. 
    * 
    * @param writer 
    *   the writer to an underlying CSV source. 
    */ 
    public CSVWriter(Writer writer) { 
     this(writer, DEFAULT_SEPARATOR, DEFAULT_QUOTE_CHARACTER, 
      DEFAULT_ESCAPE_CHARACTER, DEFAULT_LINE_END); 
    } 

    /** 
    * Constructs CSVWriter with supplied separator, quote char, escape char and line ending. 
    * 
    * @param writer 
    *   the writer to an underlying CSV source. 
    * @param separator 
    *   the delimiter to use for separating entries 
    * @param quotechar 
    *   the character to use for quoted elements 
    * @param escapechar 
    *   the character to use for escaping quotechars or escapechars 
    * @param lineEnd 
    *     the line feed terminator to use 
    */ 
    public CSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd) { 
     this.pw = new PrintWriter(writer); 
     this.separator = separator; 
     this.quotechar = quotechar; 
     this.escapechar = escapechar; 
     this.lineEnd = lineEnd; 
    } 

    /** 
    * Writes the next line to the file. 
    * 
    * @param nextLine 
    *   a string array with each comma-separated element as a separate 
    *   entry. 
    */ 
    public void writeNext(String[] nextLine) { 

     if (nextLine == null) 
       return; 

     StringBuffer sb = new StringBuffer(); 
     for (int i = 0; i < nextLine.length; i++) { 

      if (i != 0) { 
       sb.append(separator); 
      } 

      String nextElement = nextLine[i]; 
      if (nextElement == null) 
       continue; 
      if (quotechar != NO_QUOTE_CHARACTER) 
       sb.append(quotechar); 
      for (int j = 0; j < nextElement.length(); j++) { 
       char nextChar = nextElement.charAt(j); 
       if (escapechar != NO_ESCAPE_CHARACTER && nextChar == quotechar) { 
         sb.append(escapechar).append(nextChar); 
       } else if (escapechar != NO_ESCAPE_CHARACTER && nextChar == escapechar) { 
         sb.append(escapechar).append(nextChar); 
       } else { 
        sb.append(nextChar); 
       } 
      } 
      if (quotechar != NO_QUOTE_CHARACTER) 
       sb.append(quotechar); 
     } 

     sb.append(lineEnd); 
     pw.write(sb.toString()); 

    } 

    public void writeColumnNames() { 
     writeNext(DEFAULT_COLUMN_NAME.split(",")); 
    } 

    /** 
    * Flush underlying stream to writer. 
    * 
    * @throws IOException if bad things happen 
    */ 
    public void flush() throws IOException { 
     pw.flush(); 
    } 

    /** 
    * Close the underlying stream writer flushing any buffered content. 
    * 
    * @throws IOException if bad things happen 
    * 
    */ 
    public void close() throws IOException { 
     pw.flush(); 
     pw.close(); 
    } 

} 
+0

チェック[この回答](http://stackoverflow.com/questions/11341931/how-to-create-a- csv-on-android)または[this one](http://stackoverflow.com/questions/27772011/how-to-export-data-to-csv-file-in-android)を参照してください。 CSV作成に関する質問と回答がいくつかあります。 – comrade

+0

ああ、データを.csvファイルにエクスポートするのではなく、既にそれがうまくいて、私はこれで成功です。私の問題は私のすべての連絡先が.csvファイルにエクスポートされていることです。私が望むのは、.csvファイルに書き込む連絡先を選択することです。ありがとう。私はcsvファイルにそれらを書くことができるようにリストビューの選択項目とその番号を得ることができません –

+0

あなたのようにあなたのすべてのあなたの連絡先の名前を表示しているリストビューがあります。リストから4〜5のランダムな連絡先を選択します。ボタンをクリックしたときに表示されます。選択した連絡先の番号のみを含む.csvを作成する必要があります。ありがとうございました。 –

答えて

0

カスタムアダプタが、ここで使用され、最終的にはそれが完璧に動作しています。私の次の動きは、その中のすべてのチェックボックスのチェックボタンを実装することです。

Upload_contact.java

public class disusa extends ListActivity implements OnItemClickListener{ 

    List<String> name1 = new ArrayList<String>(); 
    List<String> phno1 = new ArrayList<String>(); 
    MyAdapter ma ; 
    Button select; 
    private boolean csv_status = false; 
    ToggleButton rdb; 
    ListView lv; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.disp); 

     getAllContacts(this.getContentResolver()); 
     rdb=(ToggleButton)findViewById(R.id.all); 
     //lv= (ListView) findViewById(R.id.); 
     lv = getListView(); 

     ma = new MyAdapter(); 
      lv.setAdapter(ma); 
      lv.setOnItemClickListener(this); 
      lv.setItemsCanFocus(false); 
      lv.setTextFilterEnabled(true); 
      // adding 
      select = (Button) findViewById(R.id.button1); 


      select.setOnClickListener(new OnClickListener() 
      { 
      @Override 
      public void onClick(View v) { 
        StringBuilder checkedcontacts= new StringBuilder(); 
       //System.out.println(".............."+ma.mCheckStates.size()); 
       for(int i = 0; i < name1.size(); i++){ 

        if(ma.mCheckStates.get(i)==true) 
        { 
         checkedcontacts.append(phno1.get(i).toString()); 
         checkedcontacts.append("\n"); 

         CSVWriter writer = null; 

         try { 

          writer = new CSVWriter(new FileWriter(Environment.getExternalStorageDirectory().getAbsolutePath() + "/my_test_contact.csv")); 

         } catch (IOException e1) { 
          // TODO Auto-generated catch block 
          e1.printStackTrace(); 
         } 

         writer.writeColumnNames(); // Write column header 

         if(phno1!=null) { 

         writer.writeNext((checkedcontacts.toString().split("\n"))); 

         csv_status = true; 

         } else { 

         csv_status = false; 

         } 

         try { 
          if(writer != null) 
           writer.close(); 

         } catch (IOException e) { 
          Log.w("Test", e.toString()); 
         } 

        } 
        else 
        { 
         System.out.println("Not Checked......"+name1.get(i).toString()); 
        } 


       } 

       Toast.makeText(disusa.this, checkedcontacts,1000).show(); 
      }  
     }); 


     rdb.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 



      if(rdb.isChecked()){ 
        rdb.setBackgroundColor(Color.parseColor("#FBE039")); 
        rdb.setTextColor(Color.parseColor("#000000")); 
        for (int i = 0; i < lv.getChildCount(); i++) 
         getListView().setItemChecked(i, true); 
        Toast.makeText(disusa.this, "adios",1000).show(); 

      } 
      else{ 
        rdb.setBackgroundColor(Color.parseColor("#333333")); 
        rdb.setTextColor(Color.parseColor("#ffffff")); 
        for (int i = 0; i < lv.getCount(); i++) 
         getListView().setItemChecked(i, false); 

        Toast.makeText(disusa.this,"soida",1000).show(); 
       } 
      } 
     }); 




    } 
    @Override 
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { 
     // TODO Auto-generated method stub 
     ma.toggle(arg2); 
    } 

    public void getAllContacts(ContentResolver cr) { 

     Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null); 
     while (phones.moveToNext()) 
     { 
      String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); 
      String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
     // System.out.println(".................."+phoneNumber); 
      name1.add(name); 
      phno1.add(phoneNumber); 
     } 

     phones.close(); 
    } 





    class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener 
    { private SparseBooleanArray mCheckStates; 
     LayoutInflater mInflater; 
     TextView tv1,tv; 
     CheckBox cb; 
     MyAdapter() 
     { 
      mCheckStates = new SparseBooleanArray(name1.size()); 
      mInflater = (LayoutInflater)disusa.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     } 
     @Override 
     public int getCount() { 
      // TODO Auto-generated method stub 
      return name1.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 0; 
     } 

     @Override 
     public View getView(final int position, View convertView, ViewGroup parent) { 
      // TODO Auto-generated method stub 
      View vi=convertView; 
      if(convertView==null) 
      vi = mInflater.inflate(R.layout.row, null); 
      TextView tv= (TextView) vi.findViewById(R.id.contact_name); 
      tv1= (TextView) vi.findViewById(R.id.phone_number); 
      cb = (CheckBox) vi.findViewById(R.id.checkBox_id); 
      tv.setText("Name :"+ name1.get(position)); 
      tv1.setText("Phone No :"+ phno1.get(position)); 
      cb.setTag(position); 
      cb.setChecked(mCheckStates.get(position, false)); 
      cb.setOnCheckedChangeListener(this); 

      return vi; 
     } 
     public boolean isChecked(int position) { 
       return mCheckStates.get(position, false); 
      } 

      public void setChecked(int position, boolean isChecked) { 
       mCheckStates.put(position, isChecked); 
       System.out.println("hello..........."); 
       notifyDataSetChanged(); 
      } 

      public void toggle(int position) { 
       setChecked(position, !isChecked(position)); 
      } 
     @Override 
     public void onCheckedChanged(CompoundButton buttonView, 
       boolean isChecked) { 
      // TODO Auto-generated method stub 

      mCheckStates.put((Integer) buttonView.getTag(), isChecked);   
     } 
     public View getView2(int arg0, View arg1, ViewGroup arg2) { 
      // TODO Auto-generated method stub 
      return null; 
     } 
    } 
} 

参照= "Displaying Contact Number and Contact Name in a custom list view"

関連する問題