0

我需要能够从活动中拨打电话。所以这是我的一个活动,它显示了人们的详细信息,我有一个通话按钮。但是当我调用 setOnClickListener(...) 时出现 nullPointerError。为什么?谢谢任何帮助。

package com.AndroidApp.pagine;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.AndroidApp.ApplicationController;
import com.AndroidApp.R;
import com.AndroidApp.XMLFunctions;
import com.AndroidApp.Login.LoginActivity;
import com.AndroidApp.domain.Anagrafica;



public class DettagliPagina extends ListActivity {

    public Anagrafica anagrafica;
    public ArrayList<HashMap<String, String>> mylist;
    private boolean paused, newIntentSelected = false;  
    private ProgressDialog progressDialog;
    private SharedPreferences mPreferences;
    public ApplicationController ac;

    private Button bCall;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ac = (ApplicationController)getApplication();

        mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
        String nome = mPreferences.getString("nome", "Errore");
        String cognome = mPreferences.getString("cognome", "Errore");
        setTitle("Sessione di : " + nome + " " + cognome);

        new BackgroundAsyncTask().execute();
    }


    @Override
    protected void onStart() {
        super.onStart();


        bCall = (Button) findViewById(R.id.bCall);

        // add PhoneStateListener
        PhoneCallListener phoneListener = new PhoneCallListener();
        TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);

        // add button listener
        bCall.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {

                    Intent callIntent = new Intent(Intent.ACTION_CALL);
                    callIntent.setData(Uri.parse("tel:3492395504"));
                    startActivity(callIntent);

                }
        }); 

    }



    @Override
    protected void onPause() {
        super.onPause();
        paused = true;
        ac.setOraAttuale(Calendar.getInstance());
        ac.oraAttuale.add(Calendar.MINUTE, 1);
        ac.setOraScadenza(ac.getOraAttuale());
        Log.d("DettagliPAgina scadenza", ac.getOraScadenza().getTime().toString());
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (ac.isKill) {
            finish();
        }
        if (paused && !newIntentSelected){
            if (Calendar.getInstance().after(ac.getOraScadenza())){
                //torna al login con toast sessione scaduta
                ac.setSessioneTerminata(true);
                Toast.makeText(getApplicationContext(), "Sessione Scaduta", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(DettagliPagina.this, LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        }
    }


    public class BackgroundAsyncTask extends
            AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {

        @Override
        protected ArrayList<HashMap<String, String>> doInBackground(
                String... paths) {
            mylist = new ArrayList<HashMap<String, String>>();

            String xml = XMLFunctions.getXML();
            Document doc = XMLFunctions.xmlFromString(xml);
            int numResults = XMLFunctions.numResults(doc);

            if ((numResults <= 0)) {
                Log.i("doInBack", "nussun risultato");
                DettagliPagina.this.runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(), "Nessun risultato trovato", Toast.LENGTH_LONG).show();
                    }
                });

                Intent intent = new Intent(DettagliPagina.this, FiltriAnagraficaPagina.class);
                startActivity(intent);
            }

            Bundle extras = getIntent().getExtras();
            int id = 0;
            System.out.print(id);
            if (extras != null) {
                id = extras.getInt("id");
            }

            Log.i("Dettagli", "D1");
            Set<Anagrafica> anagrafici = new HashSet<Anagrafica>();
            NodeList nodes = doc.getElementsByTagName("anagrafica");    

            Element e = (Element) nodes.item(id);
            anagrafica = new Anagrafica();
            anagrafica.setId(XMLFunctions.getValue(e, "idAnagrafica"));
            anagrafica.setNome(XMLFunctions.getValue(e, "nome"));
            anagrafica.setCognome(XMLFunctions.getValue(e, "cognome"));
            anagrafica.setIndirizzo(XMLFunctions.getValue(e, "indirizzo"));
            anagrafica.setDataDiNascita(XMLFunctions.getValue(e, "dataDiNascita"));
            anagrafica.setEmail(XMLFunctions.getValue(e, "email"));
            anagrafica.setTipologiaUtente(XMLFunctions.getValue(e, "tipologieUtente"));
            anagrafica.setAziendaCollegata(XMLFunctions.getValue(e, "aziendaCollegata"));
            anagrafica.setTelefono(XMLFunctions.getValue(e, "telefono"));
            anagrafica.setCellulare(XMLFunctions.getValue(e, "cellulare"));
            anagrafica.setInteressi(XMLFunctions.getValue(e, "interessi"));
            anagrafica.setRiferimenti(XMLFunctions.getValue(e, "riferimenti"));
            anagrafici.add(anagrafica);

            HashMap<String, String> map = new HashMap<String, String>();
            map.put("idAnagrafica",anagrafica.getId());
            map.put("nomeCognome",anagrafica.getNome() + " " + anagrafica.getCognome());
            map.put("indirizzo", "Indirizzo: " + anagrafica.getIndirizzo());
            map.put("dataDiNascita", "Data Nascita: " + anagrafica.getDataDiNascita());
            map.put("email", "Email: " + anagrafica.getEmail());
            map.put("tipologieUtente", "Tipologie Utente: " + anagrafica.getTipologiaUtente());
            map.put("aziendaCollegata", "Azienda Collegata: " + anagrafica.getAziendaCollegata());
            map.put("telefono", "Telefono: " + anagrafica.getTelefono());
            map.put("cellulare", "Cellulare: " + anagrafica.getCellulare());
            map.put("interessi", "Interessi: " + anagrafica.getInteressi());
            map.put("riferimenti", "Riferimenti" + anagrafica.getRiferimenti());

            mylist.add(map);
            Log.i("Dettagli", "D2");
            return mylist;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(DettagliPagina.this);
            progressDialog.setCancelable(true);
            progressDialog.setMessage("Loading...");
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setProgress(0);
            progressDialog.show();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }

        protected void onPostExecute(ArrayList<HashMap<String, String>> result) {

            final ListAdapter adapter = new SimpleAdapter(DettagliPagina.this,  mylist, R.layout.dettagli,
                    new String[] { "nomeCognome", "dataDiNascita",
                            "tipologieUtente", "aziendaCollegata", "email",
                            "telefono", "cellulare", "interessi", "indirizzo",
                            "riferimenti" },
                    new int[] { R.id.tvNomeCognome, R.id.tvDataDiNascita,
                            R.id.tvTipologiaUtente, R.id.tvAziendaCollegata,
                            R.id.tvEmail, R.id.tvTelefono, R.id.tvCellulare,
                            R.id.tvInteressi, R.id.tvIndirizzo, R.id.tvRiferimenti });

            setListAdapter(adapter);

            final ListView lv = getListView();
            lv.setTextFilterEnabled(true);
            lv.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    @SuppressWarnings("unchecked")
                    HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
                    Toast.makeText(getApplicationContext(), "ID '" + o.get("idAnagrafica") + "' was clicked.",
                            Toast.LENGTH_LONG).show();

                }
            });

            progressDialog.dismiss();
        }
    }


    public class PhoneCallListener extends PhoneStateListener {

        private boolean isPhoneCalling = false;

        String LOG_TAG = "LOGGING 123";

        @Override
        public void onCallStateChanged(int state, String incomingNumber) {

            if (TelephonyManager.CALL_STATE_RINGING == state) {
                // phone ringing
                Log.i(LOG_TAG, "RINGING, number: " + incomingNumber);
            }

            if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
                // active
                Log.i(LOG_TAG, "OFFHOOK");

                isPhoneCalling = true;
            }

            if (TelephonyManager.CALL_STATE_IDLE == state) {
                // run when class initial and phone call ended, need detect flag
                // from CALL_STATE_OFFHOOK
                Log.i(LOG_TAG, "IDLE");

                if (isPhoneCalling) {

                    Log.i(LOG_TAG, "restart app");

                    // restart app
                    Intent i = getBaseContext().getPackageManager()
                            .getLaunchIntentForPackage(
                                    getBaseContext().getPackageName());
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);

                    isPhoneCalling = false;
                }

            }
        }
    }
}

这是详细的xml代码:

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

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <TextView
                android:id="@+id/tvNomeCognome"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:drawableLeft="@drawable/icon"
                android:drawablePadding="10dp"
                android:padding="7dp"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textSize="24dp" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical"
            android:padding="4dp" >

            <TextView
                android:id="@+id/tvTipologiaUtente"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:textSize="20dp" />

            <TextView
                android:id="@+id/tvDataDiNascita"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:textSize="18dp" />

            <TextView
                android:id="@+id/tvEmail"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:autoLink="email"
                android:linksClickable="true"
                android:padding="2dp"
                android:textSize="18dp" />

            <TextView
                android:id="@+id/tvTelefono"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:autoLink="phone"
                android:linksClickable="true"
                android:padding="2dp"
                android:textSize="18dp" />

            <TextView
                android:id="@+id/tvCellulare"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:autoLink="phone"
                android:linksClickable="true"
                android:padding="2dp"
                android:textSize="18dp" />

            <TextView
                android:id="@+id/tvInteressi"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:textSize="18dp" />

            <TextView
                android:id="@+id/tvAziendaCollegata"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:textSize="18dp" />

            <TextView
                android:id="@+id/tvIndirizzo"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:textSize="18dp" />

            <TextView
                android:id="@+id/tvRiferimenti"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:padding="2dp"
                android:textSize="18dp" />

            <Button
                android:id="@+id/bCall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="@string/chiama" />
        </LinearLayout>
    </LinearLayout>

</ScrollView>
4

5 回答 5

1

好像你忘了调用setContentView(R.layout.your_layout);你的onCreate方法

于 2012-05-03T14:41:08.167 回答
0

请尝试使用 onItemClikListener,而不是使用 OnClickListener。

您在 ListActivity 中,所以我认为(也许我错了)您想要的是使用选定的行进行调用。所以删除 bCall 及其 onClickListener 并尝试

getListView().setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:3492395504"));
            startActivity(callIntent);

        }
    });
于 2012-05-03T14:58:22.537 回答
0

您正在获得 NPE,因为您正在尝试这样做:

bCall = (Button) findViewById(R.id.bCall);

当您尚未设置屏幕布局时。

该按钮位于列表行布局中,因此您需要在列表适配器中设置它的功能。

于 2012-05-03T15:28:03.577 回答
0

该按钮可能不是 ListView 的一部分,只是该 Activity 的主要布局。

如果我明白你在说什么,你有一个包含 ListView 和 Button 的主视图。如果该确认是正确的,那么您需要使用 Activity 而不是 ListActivity 或使用:

mActivity= this ;
Button button = new Button(this);
button.setText("push me");
button.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
button.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
            Toast.makeText(mActivity, "push", Toast.LENGTH_SHORT).show();
        }
    });
getListView().addFooterView(button);

一定要提前addFooterView(View v)打电话setAdapter(ListAdapter adapter)

于 2012-05-03T15:38:58.620 回答
0

如果我理解你的代码,你正在启动一个AsyncTaskin onCreate,它设置了listAdaper它的onPostExecute方法。另外,在onStart您尝试获取 button 时bCall

但是,如果onStart在后台任务完成之前执行,那么您还没有设置适配器,因此您的按钮将不存在并且您的调用(Button) findViewById(R.id.bCall) 将返回null

于 2012-05-03T15:56:38.240 回答