-2

大きな問題があります。SMSの一覧を取得して保存したいのですが、list viewできません!Google で検索すると、試したすべてのコードでエラーが発生し、強制終了します。手伝って頂けますか?これは私のコードです。リストビューで SMS を表示するコードの書き方を教えてください。caricaMessaggi() メソッドで SMS を読み込みます。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

ここに、受信トレイからすべてのSMSを取得するためのコードがあります。

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" />

ListView用途を作成したい場合は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 に答える