-2

我有一个大问题。我想得到一个短信列表并将它们保存在一个list view但我做不到!我在谷歌上搜索,我尝试的所有代码都给我错误并强制关闭。你能帮助我吗?这是我的代码。你能帮我如何编写代码以在列表视图中显示短信吗?我在 caricaMessaggi() 方法中加载短信。然后,我调用方法caricaMessaggi()onResume()更新它们。

/**
 * Copyright 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.media9.dizionarioalbhed;

import java.util.ArrayList;

import android.app.ActionBar;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends FragmentActivity {
     /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments representing each object in a collection. We use a
     * {@link android.support.v4.app.FragmentStatePagerAdapter} derivative,
     * which will destroy and re-create fragments as needed, saving and
     * restoring their state in the process. This is important to conserve
     * memory and is a best practice when allowing navigation between objects in
     * a potentially large collection.
     */
    CollectionPagerAdapter mCollectionPagerAdapter;
    boolean avviato = false; 
    /**
     * The {@link android.support.v4.view.ViewPager} that will display the
     * object collection.
     */
    ViewPager mViewPager;
    EditText txtIt_AL;
    EditText txtAl_AL;
    EditText txtIt;
    EditText txtAl;
    private EditText etInput;
    private Button btnAdd;
    private ListView lvItem;
    private ArrayList<String> itemArrey;
    private ArrayAdapter<String> itemAdapter;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Create an adapter that when requested, will return a fragment
        // representing an object in
        // the collection.
        //
        // ViewPager and its adapters use support library fragments, so we must
        // use
        // getSupportFragmentManager.
        mCollectionPagerAdapter = new CollectionPagerAdapter(
            getSupportFragmentManager());

        // Set up action bar.
        final ActionBar actionBar = getActionBar();

        // Specify that the Home button should show an "Up" caret, indicating
        // that touching the
        // button will take the user one step up in the application's hierarchy.
        actionBar.setDisplayHomeAsUpEnabled(true);

        // Set up the ViewPager, attaching the adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mCollectionPagerAdapter);
    }
    @Override
    protected void onStart() {
        super.onStart();
        // The activity is about to become visible.
    }
    @Override
    protected void onResume() {
        super.onResume();
        // The activity has become visible (it is now "resumed").
    }
    @Override
    protected void onPause() {
        super.onPause();
        // Another activity is taking focus (this activity is about to be "paused").
    }
    @Override
    protected void onStop() {
        super.onStop();
        // The activity is no longer visible (it is now "stopped")
    }

    /**
     * A {@link android.support.v4.app.FragmentStatePagerAdapter} that returns a
     * fragment representing an object in the collection.
     */
    public class CollectionPagerAdapter extends FragmentStatePagerAdapter {

    final int NUM_ITEMS = 4; // number of tabs

    public CollectionPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {
        Fragment fragment = new TabFragment();
        Bundle args = new Bundle();
        args.putInt(TabFragment.ARG_OBJECT, i);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getCount() {
        return NUM_ITEMS;
    }

    @Override
    public CharSequence getPageTitle(int position) {

        String tabLabel = null;
        switch (position) {
        case 0:
        tabLabel = getString(R.string.label1);
        break;
        case 1:
        tabLabel = getString(R.string.label2);
        break;
        case 2:
        tabLabel = getString(R.string.label3);
        break;
        case 3:
        tabLabel = getString(R.string.label4);
        break;
        }
        return tabLabel;
    }
    }


    /**
     * A dummy fragment representing a section of the app, but that simply
     * displays dummy text.
     */
    public static class TabFragment extends Fragment {

    public static final String ARG_OBJECT = "object";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

        Bundle args = getArguments();
        int position = args.getInt(ARG_OBJECT);

        int tabLayout = 0;
        switch (position) {
        case 0:
        tabLayout = R.layout.tab1;
        break;
        case 1:
        tabLayout = R.layout.tab2;
        break;
        case 2:
        tabLayout = R.layout.tab3;
        break;
        case 3:
        tabLayout = R.layout.tab4;
        break;
        }

        View rootView = inflater.inflate(tabLayout, container, false);

        return rootView;
    }

    }


    public void btnTraduzione_onClick(View view)
    {
        txtIt = (EditText) findViewById(R.id.txtIt);
        txtAl = (EditText) findViewById(R.id.txtAlb);
        txtAl.setText(FunzioniGenerali.italiano2albhed(txtIt));
    }



    public void btnInvia_onClick(View view)
    {
        txtAl = (EditText) findViewById(R.id.txtAlb);
        String shareBody = txtAl.getText().toString();
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        //sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
        startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.share_using)));




        /**txtAl = (EditText) findViewById(R.id.txtAlb);
        Intent smsIntent = new Intent(Intent.ACTION_VIEW);
        smsIntent.setType("text/plain");
        //smsIntent.putExtra("address", "12125551212");
        smsIntent.putExtra("sms_body",txtAl.getText().toString());
        startActivity(smsIntent);*/
    }


    public void btnTraduzioneAl_onClick(View view)
    {
        txtIt_AL = (EditText) findViewById(R.id.txtIt_AL);
        txtAl_AL = (EditText) findViewById(R.id.txtAlb_AL);
        txtAl_AL.setText(FunzioniGenerali.albhed2Italiano(txtIt_AL));

    }
    Uri uri;
    String[] body;
    String[] number;
    @SuppressWarnings("deprecation")
    public void caricaMessaggi()
    {
        Cursor c = null;
        uri = Uri.parse("content://sms/inbox");
        c= getContentResolver().query(uri, null, null ,null,null);
        c.requery();
        startManagingCursor(c);
        body = new String[c.getCount()];
        number = new String[c.getCount()]; 
        if(c.moveToFirst()){
                for(int i=0;i<10;i++){//c.getCount()
                        body[i]= c.getString(c.getColumnIndexOrThrow("body")).toString();
                        number[i]=c.getString(c.getColumnIndexOrThrow("address")).toString();
                        c.moveToNext();
                }
        }
        /**for(int i=0; i<10; i++)
        {
            AlertDialog.Builder miaAlert = new AlertDialog.Builder(this);
            miaAlert.setTitle(number[i]);
            miaAlert.setMessage(body[i]);
            AlertDialog alert = miaAlert.create();
            alert.show();
        }*/
    }  
}
4

2 回答 2

0

在这里,您有从收件箱中获取所有短信的代码:

ArrayList<String> arr = new ArrayList<String>();

StringBuilder smsBuilder = new StringBuilder();
       final String SMS_URI_INBOX = "content://sms/inbox"; 
        final String SMS_URI_ALL = "content://sms/";  
        try {  
            Uri uri = Uri.parse(SMS_URI_INBOX);  
            String[] projection = new String[] { "_id", "address", "person", "body", "date", "type" };  
            Cursor cur = getContentResolver().query(uri, projection, "address=123456789", null, "date desc");
             if (cur.moveToFirst()) {  
                int index_Address = cur.getColumnIndex("address");  
                int index_Person = cur.getColumnIndex("person");  
                int index_Body = cur.getColumnIndex("body");  
                int index_Date = cur.getColumnIndex("date");  
                int index_Type = cur.getColumnIndex("type");         
                do {  
                    String strAddress = cur.getString(index_Address);  
                    int intPerson = cur.getInt(index_Person);  
                    String strbody = cur.getString(index_Body);  
                    long longDate = cur.getLong(index_Date);  
                    int int_Type = cur.getInt(index_Type);  

                    smsBuilder.append("[ ");  
                    smsBuilder.append(strAddress + ", ");  
                    smsBuilder.append(intPerson + ", ");  
                    smsBuilder.append(strbody + ", ");  
                    smsBuilder.append(longDate + ", ");  
                    smsBuilder.append(int_Type);  
                    smsBuilder.append(" ]\n\n"); 

arr.add(smsBuilder.toString());
                } while (cur.moveToNext());  

                if (!cur.isClosed()) {  
                    cur.close();  
                    cur = null;  
                }  
            } else {  
                smsBuilder.append("no result!");  
            } // end if  
            }
        } catch (SQLiteException ex) {  
            Log.d("SQLiteException", ex.getMessage());  
        } 

您必须在清单中拥有此权限:

<uses-permission android:name="android.permission.READ_SMS" />

如果要创建ListViewuse ListActivity,请创建如下布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/mylist"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout> 

并使用适配器:

ListView listView = (ListView) findViewById(R.id.mylist); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, arr);

现在应该没问题。如果您有更多问题,请在评论中写下。如果我的问题对您有帮助,请给我投票并接受我的回答。

于 2013-01-29T18:10:46.960 回答
0

除了Ty221响应:在查询子句中我认为字符串地址格式是正确的

Cursor cur = getContentResolver().query(uri, projection, "address=\"123456789\"", null, "date desc");
于 2013-10-02T02:15:32.407 回答