将数据从一个列表视图传递到另一个

时间:2018-09-19 14:01:05

标签: android

单击复选框后,我一直试图将联系人数据从第二个活动的列表视图传递到我的主要活动的列表视图。但是,数据不会被传输。我该如何解决?

MainActivity.java

<factory>
    <client-window-factory>my.package.factoryimpl</client-window-factory>
</factory>

}

contacts.java

package com.example.artist.sender;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;

import static android.R.id.input;
import static android.app.AlertDialog.*;

public class MainActivity extends AppCompatActivity {

EditText itemText;
Button addButton;
Button sendText;
TextView text;
Button contact;

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


    itemText = (EditText) findViewById(R.id.editText);
    addButton = (Button) findViewById(R.id.button1);
    text=(TextView) findViewById(R.id.textView);


    addButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (TextUtils.isEmpty(itemText.getText())||(itemText.getText().length()<10)||(itemText.getText().length()>10)) {
                itemText.setError("The number is not valid.");
                return;
            } else {
                text.setText(itemText.getText().toString());
                itemText.setText("");
                return;
            }
        }
    });
    Button delete;
    delete = (Button) findViewById(R.id.btn2);
    delete.setOnClickListener(new AdapterView.OnClickListener() {
                                  @Override
                                  public void onClick(View view) {
                                      int con=text.getLineCount();
                                      if(con==0)
                                          Toast.makeText(MainActivity.this, "No number available to delete", Toast.LENGTH_SHORT).show();
                                     else
                                         text.setText("");
                                  }
                              });
    sendText=(Button) findViewById(R.id.btn3);
    sendText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String phoneno = text.getText().toString();
            int count = text.getLineCount();
            SmsManager smsMgrVar = SmsManager.getDefault();
            if (count == 0) {
                Toast.makeText(MainActivity.this, "No number available", Toast.LENGTH_SHORT).show();
            }
            else
                    if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED)
                    {
                        try{

                            smsMgrVar.sendTextMessage(phoneno, null, "Hey There!", null, null);
                            Toast.makeText(MainActivity.this, "Message Sent",Toast.LENGTH_LONG).show();
                        }
                        catch (Exception ErrVar)
                        {
                            Toast.makeText(MainActivity.this, "Message Sending Failed", Toast.LENGTH_SHORT).show();
                            ErrVar.printStackTrace();
                        }
                    }
                    else
                    {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                        {
                            requestPermissions(new String[]{Manifest.permission.SEND_SMS}, 10);
                        }
                    }

                }
    });
    contact =(Button) findViewById(R.id.btn4);

    contact.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            {
                startActivity(new Intent(MainActivity.this,contacts.class));
            }

        }
    });
    String tempholder=getIntent().getStringExtra("Listviewclickvalue");
    text.setText(tempholder);
}

}

logcat

package com.example.artist.sender;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.util.ArrayList;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import static android.Manifest.permission.READ_CONTACTS;

public class contacts extends MainActivity {
private static final int REQUEST_READ_CONTACTS = 444;
private ListView mListView;
private ProgressDialog pDialog;
private Handler updateBarHandler;

ArrayList<String> contactList;
Cursor cursor;
int counter;
ListView list;
String temp;
TextView itemText;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    pDialog = new ProgressDialog(contacts.this);
    pDialog.setMessage("Reading contacts...");
    pDialog.setCancelable(false);
    pDialog.show();

    mListView = (ListView) findViewById(R.id.list);
    updateBarHandler = new Handler();

    // Since reading contacts takes more time, let's run it on a separate thread.
    new Thread(new Runnable() {

        @Override
        public void run() {
            getContacts();
        }
    }).start();

    // Set onclicklistener to the list item.
    mListView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            //TODO Do whatever you want with the list data
            Toast.makeText(getApplicationContext(), "item clicked : \n" + contactList.get(position), Toast.LENGTH_SHORT).show();
        }
    });
}

private boolean mayRequestContacts() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        return true;
    }
    if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
        return true;
    }
    if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
        requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
    } else {
        requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
    }
    return false;
}

/**
 * Callback received when a permissions request has been completed.
 */
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                       int[] grantResults) {
    if (requestCode == REQUEST_READ_CONTACTS) {
        if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            getContacts();
        }
    }
}

public void getContacts() {

    if (!mayRequestContacts()) {
        return;
    }

    contactList = new ArrayList<String>();

    String phoneNumber = null;
    // String email = null;

    Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
    String _ID = ContactsContract.Contacts._ID;
    String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
    String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;

    Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
    String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;

   /* Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
    String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
    String DATA = ContactsContract.CommonDataKinds.Email.DATA;*/

    StringBuffer output;

    ContentResolver contentResolver = getContentResolver();

    cursor = contentResolver.query(CONTENT_URI, null, null, null, null);

    // Iterate every contact in the phone
    if (cursor.getCount() > 0) {

        counter = 0;
        while (cursor.moveToNext()) {
            output = new StringBuffer();

            // Update the progress message
            updateBarHandler.post(new Runnable() {
                public void run() {
                    pDialog.setMessage("Reading contacts : " + counter++ + "/" + cursor.getCount());
                }
            });

            String contact_id = cursor.getString(cursor.getColumnIndex(_ID));
            String name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));

            int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(HAS_PHONE_NUMBER)));

            if (hasPhoneNumber > 0) {

                output.append("\n First Name:" + name);


                //This is to read multiple phone numbers associated with the same contact
                Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[]{contact_id}, null);

                while (phoneCursor.moveToNext()) {
                    phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
                    output.append("\n Phone number:" + phoneNumber);

                }

                phoneCursor.close();

               /* // Read every email id associated with the contact
                Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?", new String[]{contact_id}, null);

                while (emailCursor.moveToNext()) {

                    email = emailCursor.getString(emailCursor.getColumnIndex(DATA));

                    output.append("\n Email:" + email);

                }

                emailCursor.close();

                String columns[] = {
                        ContactsContract.CommonDataKinds.Event.START_DATE,
                        ContactsContract.CommonDataKinds.Event.TYPE,
                        ContactsContract.CommonDataKinds.Event.MIMETYPE,
                };*/

                String where = ContactsContract.CommonDataKinds.Event.TYPE + "=" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY +
                        " and " + ContactsContract.CommonDataKinds.Event.MIMETYPE + " = '" + ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE + "' and " + ContactsContract.Data.CONTACT_ID + " = " + contact_id;

                String[] selectionArgs = null;
                String sortOrder = ContactsContract.Contacts.DISPLAY_NAME;

                /*Cursor birthdayCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, columns, where, selectionArgs, sortOrder);
                Log.d("BDAY", birthdayCur.getCount()+"");
                if (birthdayCur.getCount() > 0) {
                    while (birthdayCur.moveToNext()) {
                        String birthday = birthdayCur.getString(birthdayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE));
                        output.append("Birthday :" + birthday);
                        Log.d("BDAY", birthday);
                    }
                }
                birthdayCur.close();
            }*/

                // Add the contact to the ArrayList
                contactList.add(output.toString());
            }

            // ListView has to be updated using a ui thread
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.contact_text, R.id.text1, contactList);
                    mListView.setAdapter(adapter);
                }
            });

            // Dismiss the progressbar after 500 millisecondds
            updateBarHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    pDialog.cancel();
                }
            }, 500);
        }

    }


    //passing the number to the mainactivity's textview through intent
    list=(ListView) findViewById(R.id.list);
    final String listview[] = new String[list.getCount()];
    for (int j = 0; j < list.getCount(); j++) {
        View v = list.getChildAt(j);
        TextView tv = (TextView) v.findViewById(R.id.text1);
        listview[j] = (String) tv.getText();
    }
    itemText = (TextView) findViewById(R.id.text1);
    final String number = itemText.getText().toString();
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, listview);
    list.setAdapter(adapter);
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                        if ((number.matches("[0-9]+"))&&(number.length()==10))
                                            temp = listview[position].toString();
                                        Intent intent = new Intent(contacts.this, MainActivity.class);
                                        intent.putExtra("Listviewclickvalue", temp);
                                        startActivity(intent);

                                    }
                                }
    );
}

这是错误的日志。它不断显示setitemOnClickListener一直在引用一个空对象,而我已经将listview分配给了其各自的id。

编辑:**通过将通讯录类中的 setContentView(R.layout.activity_main); 重命名为 setContentView(R),我已修复了部分错误。 layout.contacts); 但是在此之后,它显示了此错误** java.lang.NullPointerException:尝试在其上调用虚拟方法'android.view.View android.view.View.findViewById(int)'空对象引用

1 个答案:

答案 0 :(得分:0)

如果数据库或其他存储中的数据分别仅传递_id或位置。

实际上,Android方法不是传递许多附加功能,而是Parcable。这里是Vogella

的不错的教程

公共类TestModel实现了Parcelable {

String name;
String phoneNumber;

//.....

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(this.name);
    dest.writeString(this.phoneNumber);    
}

public static final Parcelable.Creator<TestModel> CREATOR = new Parcelable.Creator<TestModel>() {
    @Override
    public TestModel createFromParcel(Parcel source) {
        return new TestModel(source);
    }

    @Override
    public TestModel[] newArray(int size) {
        return new TestModel[size];
    }
};
}