0

Думаю, что через Bundle, но не совсем знаком с его реализацией. Буду благодарен за любую помощь

MainActivity - откуда передаём

package com.genius.project.passwordhelper;

import android.app.DialogFragment;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    private SQLiteDatabase dataBaseMain;
    private Cursor displayMainCursor;
    SQLiteOpenHelper dbHelper;
    DialogFragment dialogAddPass;
    ListView listViewPasswords;
    FloatingActionButton fab;
    public Bundle tempBundle;

    public void updateMainList() {                                          //через SimpleCursorAdapter - оптимальная работа (?)
        listViewPasswords = (ListView) findViewById(R.id.listPasswords);
        try{
            dbHelper = new PasswordDatabaseHelper(this);
            dataBaseMain = dbHelper.getReadableDatabase();
            displayMainCursor = dataBaseMain.query("DATAPASS", new String[]{"_id", "SITE"}, null, null, null, null, null);
            CursorAdapter cusrorDisplay = new SimpleCursorAdapter(this,
                    android.R.layout.simple_list_item_1,
                    displayMainCursor,
                    new String[]{"SITE"},
                    new int[]{android.R.id.text1}, 0);
            listViewPasswords.setAdapter(cusrorDisplay);
        } catch(SQLiteException e) {
            Snackbar.make(fab, R.string.database_error, Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        dialogAddPass = new CustomDialogFragment();                     //инициализиуем фрагмент AddPass

        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogAddPass.show(getFragmentManager(), "enterPass");
            }
        });

        updateMainList();

        listViewPasswords.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> listView, View v, int position, long id) {       //брать Position для идентификации номера пароля!
                DialogFragment dialogShowPass = new DetailedPassFragment();                 //инициализируем фрагмент ShowPass

                    backDb backTask = new backDb();     //запуск асинхронного класса поиска пароля и передача его в Bundle воспроизводимому фрагменту
                    backTask.execute(position);

                    dialogShowPass.setArguments(tempBundle);
                    dialogShowPass.show(getFragmentManager(), "editPass");
            }
        });

        listViewPasswords.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View v,
                                           int index, long arg3) {

                Toast.makeText(MainActivity.this,listViewPasswords.getItemAtPosition(index).toString(), Toast.LENGTH_LONG).show();
                return false;
            }
        });
    }

    class backDb extends AsyncTask<Integer, Void, Bundle> {                   //выводим курсор для поиска значений, выданного кнопкой editPass в отдельный потом

        String site;
        String pass;
        String info;
        String[] out;
        String debugInfo;                                             //DB

        @Override
        protected Bundle doInBackground(Integer... id) {

            debugInfo = String.valueOf(id.length);                        //DB
            PasswordDatabaseHelper helper = new PasswordDatabaseHelper(MainActivity.this);
            SQLiteDatabase dbShowPass = helper.getReadableDatabase();
            Cursor cursorShowPass = dbShowPass.query("DATAPASS",
                    new String[]{"SITE", "PASS", "INFO"},
                    "_id = ?",
                    new String[]{Arrays.toString(id)},
                    null, null, null);

            if(cursorShowPass.moveToFirst()) {
                tempBundle = new Bundle();
                tempBundle.putString("site", cursorShowPass.getString(0));
                tempBundle.putString("pass", cursorShowPass.getString(1));
                tempBundle.putString("info", cursorShowPass.getString(2));
                return tempBundle;
            } else {
                dbShowPass.close();
                cursorShowPass.close();
                return tempBundle = new Bundle();
            }
        }

        @Override
        protected void onPostExecute(Bundle result) {
            if(!result.isEmpty()) {
                Toast.makeText(MainActivity.this, "Data send into Bundle"+" "+debugInfo+" "+out[0], Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "Data NOT send"+" "+debugInfo+" "+out[0], Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {                             //создание списка меню
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {                       //обработчик списка меню
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            Intent intentSettings = new Intent(MainActivity.this, SettingsActivity.class);
            startActivity(intentSettings);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onResume() {
        super.onResume();
        Snackbar.make(fab, R.string.dataUpdated, Snackbar.LENGTH_LONG)
                .setAction("Action", null).show();
        updateMainList();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dataBaseMain.close();
        displayMainCursor.close();
    }
}

DetailedPassFragment - куда передаём

package com.genius.project.passwordhelper;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

public class DetailedPassFragment extends DialogFragment implements DialogInterface.OnClickListener {

    EditText siteForm;
    EditText passForm;
    EditText infoForm;
    Bundle inputBundle;

    @Override
    public void onClick(DialogInterface dialogInterface, int buttonId) {
        Dialog editForm = (Dialog) dialogInterface;
        switch (buttonId) {
            case(Dialog.BUTTON_POSITIVE): {
                editForm.dismiss();
                break;
            }
            case(Dialog.BUTTON_NEGATIVE): {
                editForm.dismiss();
                break;
            }
        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        View detailedForm = getActivity().getLayoutInflater().inflate(R.layout.passdetail, null);

        siteForm = (EditText) detailedForm.findViewById(R.id.site);                     //работа с данными в EditText только в onCreateDialog
        passForm = (EditText) detailedForm.findViewById(R.id.pass);
        infoForm = (EditText) detailedForm.findViewById(R.id.info);

        inputBundle = getArguments();

        siteForm.setText(inputBundle.getString("site"));
        passForm.setText(inputBundle.getString("pass"));
        infoForm.setText(inputBundle.getString("info"));

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
                .setTitle(R.string.editPassLayer)
                .setView(detailedForm)
                .setPositiveButton(R.string.deleteItem, this)
                .setNegativeButton(R.string.enterPass_button, this);

        return builder.create();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return getActivity().getLayoutInflater().inflate(R.layout.passdetail, null);
    }

    @Override
    public void onStop() {                      //обновляет представление mainActivity
        super.onStop();
        MainActivity main = (MainActivity)getActivity();
        main.updateMainList();
    }

    /*@Override
    public void onDestroy() {
        super.onDestroy();
    }*/
}

1 ответ 1

2

Вы в диалог прокидываете аргумет dialogShowPass.setArguments(tempBundle); Вот туда данные положите нужные, а в диалоге сделайте this.getArguments()

2
  • Кхм, а не подскажите, почему при запуске программы, в процессе работы кода из MainActivity, при первом щелчке по пункту списка (и срабатывании асинхронного процесса, передается всегда первым результатом null? Причем дальше передает данные со смещением на -1 шаг
    – GeniusRUS
    28 ноя 2016 в 19:51
  • 1
    null потому что вы запускаете поток и идете дальше. На момент вызова метода dialogShowPass.setArguments(tempBundle) объекта tempBundle еще не существует
    – pavel163
    28 ноя 2016 в 20:03

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.