如何将Android.database.sqlite表数据加载到spinner中? (表有数据但未加载)

问题描述 投票:0回答:1

我正在使用以下代码将 sqlite 数据库表信息加载到微调器中。我通过保存数据活动来保存表中的数据,并尝试在获取数据活动的微调器中获取保存的数据。当我打开从将数据库表的数据获取到微调器中获取数据活动时,微调器中没有显示任何内容。我不明白为什么数据没有进入微调器。我对我的代码的这种方法有一些疑问。--- public void GetGroup() --- 有人可以帮忙解决这个问题吗?

 public class ContactsList extends BaseActivity implements AdapterView.OnItemClickListener {
private static final String TAG = ContactsList.class.getSimpleName();
public ListView j;
public Spinner k;
public ContactsListViewAdapter l;
public ArrayList<ContactsListModel> m = new ArrayList<>();
/* access modifiers changed from: private */
public ProgressDialog mProgress;
public ArrayList<ContactsListModel> n = new ArrayList<>();
public LinearLayout o;
public List<String> p = new ArrayList();
public List<String> q = new ArrayList();
public List<String> r = new ArrayList();
public String s = "";
public String t = "";
public String u = "";
public boolean v = false;
public boolean w = false;
public String x;
private Cursor fetchAllBatchDetails;
private String group_id;

public class LoadData extends AsyncTask<Void, Void, Boolean> {
    public LoadData() {
        ContactsList.this.mProgress.show();
    }

    @SuppressLint("Range")
    public Boolean doInBackground(Void... voidArr) {
        ContactsList.this.n.clear();
        ContactsDetailsDbAdapter contactsDetailsDbAdapter = new ContactsDetailsDbAdapter(ContactsList.this);
        contactsDetailsDbAdapter.open();
        Cursor fetchAllDetails = ContactsList.this.t.equals("") ? contactsDetailsDbAdapter.fetchAllDetails() : contactsDetailsDbAdapter.fetchAllDetails(ContactsList.this.t);
        while (fetchAllDetails.moveToNext()) {
            ContactsList.this.n.add(new ContactsListModel(fetchAllDetails.getString(fetchAllDetails.getColumnIndex(ContactsDetailsDbAdapter.CONTACT_ID)), fetchAllDetails.getString(fetchAllDetails.getColumnIndex(ContactsDetailsDbAdapter.CONTACT_NAME)), fetchAllDetails.getString(fetchAllDetails.getColumnIndex(ContactsDetailsDbAdapter.CONTACT_NUMBER)), fetchAllDetails.getString(fetchAllDetails.getColumnIndex(ContactsDetailsDbAdapter.CONTACT_NUMBER)), fetchAllDetails.getString(fetchAllDetails.getColumnIndex(ContactsDetailsDbAdapter.CONTACT_NUMBER)), fetchAllDetails.getString(fetchAllDetails.getColumnIndex(ContactsDetailsDbAdapter.CONTACT_NUMBER))));
        }
        contactsDetailsDbAdapter.close();
        return Boolean.TRUE;
    }

    @SuppressLint("WrongConstant")
    public void onPostExecute(Boolean bool) {
        LinearLayout linearLayout;
        ContactsList.this.m.clear();
        ContactsList contactsList = ContactsList.this;
        contactsList.m.addAll(contactsList.n);
        ContactsList.this.l.notifyDataSetChanged();
        ContactsList.this.j.invalidateViews();
        ContactsList.this.mProgress.dismiss();
        int i = 0;
        if (ContactsList.this.l.getCount() > 0) {
            Context applicationContext = ContactsList.this.getApplicationContext();
            Toast.makeText(applicationContext, ContactsList.this.l.getCount() + " contacts displayed", Toast.LENGTH_SHORT).show();
            linearLayout = ContactsList.this.o;
            i = 8;
        } else {
            linearLayout = ContactsList.this.o;
        }
        linearLayout.setVisibility(i);
    }
}

public class SaveVCFContacts extends AsyncTask<Void, Void, Integer> {
    public SaveVCFContacts() {
        ContactsList.this.mProgress.show();
    }

    public Integer doInBackground(Void... voidArr) {
        int i;
        Exception e;
        int i2 = 0;
        try {
            ArrayList<ContactsListModel> arrayList = ContactsList.this.l.groupData;
            i = 0;
            while (i2 < arrayList.size()) {
                try {
                    ContactsListModel contactsListModel = arrayList.get(i2);
                    if (!MyFunctions.contactExists(ContactsList.this, contactsListModel.getContactNumber())) {
                        i++;
                        String contactName = contactsListModel.getContactName();
                        if (contactName.equals("Unknown")) {
                            contactName = ContactsList.this.u + AnalyticsConstants.DELIMITER_MAIN + i;
                        }
                        ContactsList.this.addContact(contactName, contactsListModel.getContactNumber());
                    }
                    i2++;
                } catch (Exception e2) {
                    e = e2;
                    e.printStackTrace();
                    return Integer.valueOf(i);
                }
            }
        } catch (Exception e3) {
            e = e3;
            i = 0;
            e.printStackTrace();
            return Integer.valueOf(i);
        }
        return Integer.valueOf(i);
    }

    public void onPostExecute(Integer num) {
        ContactsList.this.mProgress.dismiss();
        Context applicationContext = ContactsList.this.getApplicationContext();
        Toast.makeText(applicationContext, num + " contacts are saved successfully", Toast.LENGTH_SHORT).show();
    }
}

public class ShareContacts extends AsyncTask<Void, Void, File> {
    public ShareContacts() {
        ContactsList.this.mProgress.show();
    }

    public File doInBackground(Void... voidArr) {
        File file;
        IOException e;
        file = new File(ContactsList.this.getApplicationContext().getFilesDir(), ContactsList.this.x);
        try {
            PrintStream printStream = new PrintStream(file);
            ArrayList<ContactsListModel> arrayList = ContactsList.this.l.groupData;
            for (int i = 0; i < arrayList.size(); i++) {
                ContactsListModel contactsListModel = arrayList.get(i);
                printStream.println(contactsListModel.getContactName() + "," + contactsListModel.getContactNumber());
            }
            printStream.flush();
            printStream.close();
        } catch (IOException e2) {
            e = e2;
            e.printStackTrace();
            return file;
        }
        return file;
    }

    public void onPostExecute(File file) {
        ContactsList.this.mProgress.dismiss();
        Intent intent = new Intent("android.intent.action.SEND");
        Uri uriForFile = Build.VERSION.SDK_INT >= 24 ? FileProvider.getUriForFile(ContactsList.this, "com.invotech.whatspromo.provider", file) : Uri.fromFile(file);
        if (file.exists()) {
            intent.setType("text/*");
            intent.putExtra("android.intent.extra.STREAM", uriForFile);
            ContactsList.this.startActivity(Intent.createChooser(intent, "Share File"));
        }
    }
}

public class ShareVCFContacts extends AsyncTask<Void, Void, File> {
    public ShareVCFContacts() {
        ContactsList.this.mProgress.show();
    }

    public File doInBackground(Void... voidArr) {
        File file = null;
        File file2 = new File(ContactsList.this.getApplicationContext().getFilesDir(), "whatspromo.vcf");
        try {
            FileWriter fileWriter = new FileWriter(file2);
            ArrayList<ContactsListModel> arrayList = ContactsList.this.l.groupData;
            for (int i = 0; i < arrayList.size(); i++) {
                ContactsListModel contactsListModel = arrayList.get(i);
                fileWriter.write("BEGIN:VCARD\r\n");
                fileWriter.write("VERSION:2.1\r\n");
                fileWriter.write("N:" + contactsListModel.getContactID() + ";" + contactsListModel.getContactName() + ";;;\r\n");
                fileWriter.write("FN:" + contactsListModel.getContactName() + " " + contactsListModel.getContactID() + "\r\n");
                StringBuilder sb = new StringBuilder();
                sb.append("TEL;CELL:");
                sb.append(contactsListModel.getContactNumber());
                sb.append("\r\n");
                fileWriter.write(sb.toString());
                fileWriter.write("END:VCARD\r\n");
            }
            fileWriter.close();
            return file2;
        } catch (IOException e) {
            e = e;
            file = file2;
            e.printStackTrace();
            return file;
        }
    }

    public void onPostExecute(File file) {
        ContactsList.this.mProgress.dismiss();
        Intent intent = new Intent("android.intent.action.SEND");
        Uri uriForFile = Build.VERSION.SDK_INT >= 24 ? FileProvider.getUriForFile(ContactsList.this, "com.invotech.whatspromo.provider", file) : Uri.fromFile(file);
        if (file.exists()) {
            intent.setType("text/*");
            intent.putExtra("android.intent.extra.STREAM", uriForFile);
            ContactsList.this.startActivity(Intent.createChooser(intent, "Share File"));
        }
    }
}


public void Shake(View view) {
    RotateAnimation rotateAnimation = new RotateAnimation(-5.0f, 5.0f, 1, 0.5f, 1, 0.5f);
    rotateAnimation.setDuration(250);
    rotateAnimation.setStartOffset(50);
    rotateAnimation.setRepeatMode(2);
    rotateAnimation.setInterpolator(new CycleInterpolator(5.0f));
    view.startAnimation(rotateAnimation);
}


public void addContact(String str, String str2) {
    ArrayList arrayList = new ArrayList();
    arrayList.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI).withValue("account_type", (Object) null).withValue("account_name", (Object) null).build());
    if (str != null) {
        arrayList.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference("raw_contact_id", 0).withValue("mimetype", "vnd.android.cursor.item/name").withValue("data1", str).build());
    }
    if (str2 != null) {
        arrayList.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference("raw_contact_id", 0).withValue("mimetype", "vnd.android.cursor.item/phone_v2").withValue("data1", str2).withValue("data2", 2).build());
    }
    try {
        getContentResolver().applyBatch("com.android.contacts", arrayList);
    } catch (Exception e) {
        e.printStackTrace();
        Context applicationContext = getApplicationContext();
        StringBuilder u2 = ContactsList.this.u("Exception: ");
        u2.append(e.getMessage());
        Toast.makeText(applicationContext, u2.toString(), Toast.LENGTH_SHORT).show();
    }
}

private StringBuilder u(String s) {
    return null;
}


public void showContacts() {
    if (Build.VERSION.SDK_INT < 23 || checkSelfPermission("android.permission.WRITE_CONTACTS") == PackageManager.PERMISSION_GRANTED) {
        new SaveVCFContacts().execute(new Void[0]);
    } else {
        requestPermissions(new String[]{"android.permission.WRITE_CONTACTS"}, PointerIconCompat.TYPE_COPY);
    }
}

@SuppressLint("ResourceType")
public void AddContactDialog() {
    final Dialog dialog = new Dialog(this);
    dialog.requestWindowFeature(1);
    dialog.setCancelable(false);
    dialog.setContentView(R.layout.dialog_add_contact);
    ArrayAdapter arrayAdapter = new ArrayAdapter(this, 17367048, this.q);
    arrayAdapter.setDropDownViewResource(R.layout.drpdown_item);
    final Spinner spinner = (Spinner) dialog.findViewById(R.id.groupSpinner);
    spinner.setAdapter(arrayAdapter);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long j) {
            ContactsList contactsList = ContactsList.this;
            contactsList.s = "";
            contactsList.u = "";
            contactsList.s = contactsList.p.get(i);
            ContactsList contactsList2 = ContactsList.this;
            contactsList2.u = contactsList2.q.get(i);
        }

        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    });
    spinner.setSelection(this.p.indexOf(this.t));
    if (this.w) {
        spinner.setEnabled(false);
    }
    final CountryCodePicker countryCodePicker = (CountryCodePicker) dialog.findViewById(R.id.ccp);
    final TextInputEditText textInputEditText = (TextInputEditText) dialog.findViewById(R.id.contactname_edit_text);
    final TextInputEditText textInputEditText2 = (TextInputEditText) dialog.findViewById(R.id.contactnumber_edit_text);
    countryCodePicker.registerCarrierNumberEditText(textInputEditText2);
    textInputEditText.requestFocus();
    ((Switch) dialog.findViewById(R.id.subscribeSW)).setVisibility(View.GONE);
    ((ImageView) dialog.findViewById(R.id.closeImageView)).setOnClickListener(view -> dialog.dismiss());
    final Dialog dialog2 = dialog;
    ((Button) dialog.findViewById(R.id.saveButton)).setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            if (ContactsList.this.s.equals("")) {
                ContactsList.this.Shake(spinner);
                Toast.makeText(ContactsList.this.getApplicationContext(), "Please Select Group", Toast.LENGTH_SHORT).show();
            } else if (ContactsList.this.L(textInputEditText, "")) {
                textInputEditText.setError("Enter Name");
            } else if (ContactsList.this.L(textInputEditText2, "")) {
                textInputEditText2.setError("Enter Number");
            } else {
                ContactsDetailsDbAdapter contactsDetailsDbAdapter = new ContactsDetailsDbAdapter(ContactsList.this);
                contactsDetailsDbAdapter.open();
                ContentValues contentValues = new ContentValues();
                contentValues.put(ContactsDetailsDbAdapter.CONTACT_NAME, textInputEditText.getText().toString());
                contentValues.put(ContactsDetailsDbAdapter.CONTACT_NUMBER, countryCodePicker.getFullNumberWithPlus());
                contentValues.put(ContactsDetailsDbAdapter.CONTACT_GROUP_ID, ContactsList.this.s);
                contentValues.put(ContactsDetailsDbAdapter.CONTACT_GROUP_NAME, ContactsList.this.u);
                contentValues.put(ContactsDetailsDbAdapter.CONTACT_ADD_DATETIME, MyFunctions.getDateTime());
                contactsDetailsDbAdapter.insertData(contentValues);
                contactsDetailsDbAdapter.close();
                dialog2.dismiss();
                new LoadData().execute(new Void[0]);
            }
        }
    });
    Window window = dialog.getWindow();
    window.setLayout(-1, -2);
    window.setBackgroundDrawableResource(17170445);
    dialog.show();
}

private boolean L(TextInputEditText textInputEditText, String s) {
    return false;
}

@SuppressLint("ResourceType")
public void EditGroupDialog(final String str, String str2) {
    final Dialog dialog = new Dialog(this);
    dialog.requestWindowFeature(1);
    dialog.setCancelable(false);
    dialog.setContentView(R.layout.dialog_edit_group);
    final TextInputEditText textInputEditText = (TextInputEditText) dialog.findViewById(R.id.groupname_edit_text);
    textInputEditText.setText(str2);
    textInputEditText.requestFocus();
    ((ImageView) dialog.findViewById(R.id.closeImageView)).setOnClickListener(view -> dialog.dismiss());
    ((Button) dialog.findViewById(R.id.saveButton)).setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            if (ContactsList.this.L(textInputEditText, "")) {
                textInputEditText.setError("Enter Group Name");
                return;
            }
            GroupDetailsDbAdapter groupDetailsDbAdapter = new GroupDetailsDbAdapter(ContactsList.this);
            groupDetailsDbAdapter.open();
            ContentValues contentValues = new ContentValues();
            contentValues.put(GroupDetailsDbAdapter.GROUP_NAME, textInputEditText.getText().toString());
            groupDetailsDbAdapter.updateBATCHDetails(str, contentValues);
            groupDetailsDbAdapter.close();
            dialog.dismiss();
            Toast.makeText(ContactsList.this.getApplicationContext(), "Updated Successfully", Toast.LENGTH_SHORT).show();
            ContactsList.this.finish();
        }
    });
    Button button = (Button) dialog.findViewById(R.id.deleteButton);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Toast.makeText(ContactsList.this.getApplicationContext(), "Long Press to Delete", Toast.LENGTH_SHORT).show();
        }
    });
    button.setOnLongClickListener(new View.OnLongClickListener() {
        public boolean onLongClick(View view) {
            GroupDetailsDbAdapter groupDetailsDbAdapter = new GroupDetailsDbAdapter(ContactsList.this);
            groupDetailsDbAdapter.open();
            groupDetailsDbAdapter.deleteData(str);
            groupDetailsDbAdapter.close();
            ContactsDetailsDbAdapter contactsDetailsDbAdapter = new ContactsDetailsDbAdapter(ContactsList.this);
            contactsDetailsDbAdapter.open();
            contactsDetailsDbAdapter.deleteGroupData(str);
            contactsDetailsDbAdapter.close();
            dialog.dismiss();
            Toast.makeText(ContactsList.this.getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
            ContactsList.this.finish();
            return true;
        }
    });
    ((Button) dialog.findViewById(R.id.deleteButton2)).setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent intent = new Intent(ContactsList.this, DeleteContactsActivity.class);
            intent.putExtra("GROUP_ID", str);
            ContactsList.this.startActivity(intent);
            dialog.dismiss();
        }
    });
    Window window = dialog.getWindow();
    window.setLayout(-1, -2);
    window.setBackgroundDrawableResource(17170445);
    dialog.show();
}


**@SuppressLint({"Range"})
public void GetGroup() {
    this.p.clear();
    this.q.clear();
    this.r.clear();
    GroupDetailsDbAdapter groupDetailsDbAdapter = new GroupDetailsDbAdapter(this);
    groupDetailsDbAdapter.open();
    Cursor fetchAllBatchDetails = groupDetailsDbAdapter.fetchAllBatchDetails();
    while (fetchAllBatchDetails.moveToNext()) {
        ContactsList.this.G(fetchAllBatchDetails, "group_id", this.p);
        ContactsList.this.G(fetchAllBatchDetails, GroupDetailsDbAdapter.GROUP_NAME, this.q);
        ContactsList.this.G(fetchAllBatchDetails, GroupDetailsDbAdapter.GROUP_NAME, this.r);
    }
    groupDetailsDbAdapter.close();
    if (this.p.size() == 0) {
        Toast.makeText(this, "No Group found", Toast.LENGTH_SHORT).show();
        groupNotFoundAlert();
    }
}
private void G(Cursor fetchAllBatchDetails, String group_id, List<String> p) {
    this.fetchAllBatchDetails = fetchAllBatchDetails;
    this.group_id = group_id;
    this.p = p;
}**


public void groupNotFoundAlert() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setCancelable(false);
    builder.setTitle((CharSequence) "Group Not Found");
    builder.setMessage((CharSequence) "Please create a group first");
    builder.setPositiveButton((CharSequence) "OK", (DialogInterface.OnClickListener) new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialogInterface, int i) {
            ContactsList.this.startActivity(new Intent(ContactsList.this, GroupList.class));
            ContactsList.this.finish();
        }
    });
    builder.create().show();
}

public void onActivityResult(int i, int i2, Intent intent) {
    super.onActivityResult(i, i2, intent);
    if (i == 10 && i2 == -1) {
        new LoadData().execute(new Void[0]);
    }
}

public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView((int) R.layout.activity_contacts_list);
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        this.t = extras.getString("GROUP_ID");
        this.u = extras.getString("GROUP_NAME");
        this.w = true;
    }
    //setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
    setTitle("Contacts List");
    getSharedPreferences(PreferencesConstants.APP_MAIN_PREF, 0);
    ProgressDialog progressDialog = new ProgressDialog(this);
    this.mProgress = progressDialog;
    progressDialog.setTitle("Loading");
    this.mProgress.setMessage(getResources().getString(R.string.please_wait));
    try {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    } catch (NullPointerException unused) {
        Log.e("SearchActivity Toolbar", "You have got a NULL POINTER EXCEPTION");
    }
    this.k = (Spinner) findViewById(R.id.groupSpinner);
    this.o = (LinearLayout) findViewById(R.id.placeHolderLayout);
    this.j = (ListView) findViewById(R.id.groupListview);
    ContactsListViewAdapter contactsListViewAdapter = new ContactsListViewAdapter(this, this.m);
    this.l = contactsListViewAdapter;
    this.j.setAdapter(contactsListViewAdapter);
    this.j.setOnItemClickListener(this);
    ((Button) findViewById(R.id.add_button)).setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            ContactsList.this.MoreOptionDialog();
        }
    });
    GetGroup();
    @SuppressLint("ResourceType") ArrayAdapter arrayAdapter = new ArrayAdapter(this, 17367048, this.r);
    arrayAdapter.setDropDownViewResource(R.layout.drpdown_item);
    this.k.setAdapter(arrayAdapter);
    this.k.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long j) {
            ContactsList contactsList = ContactsList.this;
            contactsList.t = "";
            contactsList.u = contactsList.q.get(i);
            ContactsList contactsList2 = ContactsList.this;
            contactsList2.t = contactsList2.p.get(i);
            if (ContactsList.this.v) {
                new LoadData().execute(new Void[0]);
            }
            ContactsList.this.v = true;
        }

        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    });
    if (this.w) {
        this.k.setSelection(this.p.indexOf(this.t));
        this.k.setEnabled(false);
    }
}


public void onItemClick(AdapterView<?> adapterView, View view, int i, long j2) {
    TextView textView = (TextView) view.findViewById(R.id.contactNameTextView);
    Intent intent = new Intent(this, ContactDetailActivity.class);
    intent.putExtra("CONTACT_ID", ((TextView) view.findViewById(R.id.contactIdTextView)).getText().toString());
    startActivity(intent);
}


public void onPause() {
    super.onPause();
}

public void onResume() {
    super.onResume();
    new LoadData().execute(new Void[0]);
}

}

java android database sqlite listview
1个回答
0
投票

而不是这样做

@SuppressLint("ResourceType") ArrayAdapter arrayAdapter = new ArrayAdapter(this, 17367048, this.r);
arrayAdapter.setDropDownViewResource(R.layout.drpdown_item);
this.k.setAdapter(arrayAdapter);

改成这样

首先在 Logcat 中检查 this.r 是否正在获取值。

Log.e("tag", "this.r = " + this.r);

如果 this.r 有值,则使用以下代码作为微调适配器。

// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, this.r);      
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(arrayAdapter);
© www.soinside.com 2019 - 2024. All rights reserved.