Boshqa faoliyatdagi ro'yxatga kiritilgan qatorga EditText maydoniga kiritgan ma'lumotlarni qanday qo'shishim mumkin?

Quyida mening Android ilovalarini ishlab chiqish uchun foydalanadigan 3 ta java kurslari mavjud. "AddActivity" sahifasida saqlanishi uchun "Qo'shish" tugmasini bosgandan so'ng talaba ma'lumotlarini (ism va telefon raqamini) qo'shishni istardim. Men buni o'rganib chiqdim va bir qatorni ishlatishga harakat qildim. Lekin MenAndActivity-ga kiritilgan ma'lumotlarni MainActivity sahifasiga yuborish uchun mantiq kodi qanday bo'lishi kerakligi haqida shubhalanaman. Buni qanday amalga oshirish kerakligi haqida menga kimdir maslahat bera oladimi? Agar siz menga boshqa yo'lni ko'rsatmoqchi bo'lsam, chindan ham minnatdor bo'lar edim. Ma'lumotlarning ListView formatida MainActivity-da saqlanishini xohlayman. Keyin, "Add" menyusiga tıkladım. Umid qilamanki, kimdir meni bu yo'lda boshqarishi mumkin. Rahmat.

MainActivity.java - https://jsfiddle.net/eb1fprnn/

public class MainActivity extends AppCompatActivity {
ListView listView;
Button addStudent;
ArrayList students = new ArrayList();
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    add();
}



public void add() {
    Student student;
    addStudent = (Button) findViewById(R.id.add);
    addStudent.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, AddActivity.class);
            startActivity(intent);
        }
    });
}
}

AddActivity.java - https://jsfiddle.net/40k5mas2/

public class AddActivity extends AppCompatActivity {
EditText name, phone;
Button add;
int FphoneNumber;
String Fname;
ArrayList students;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent = getIntent();
    students = (ArrayList) getIntent().getSerializableExtra("AddNewStudent");
    setContentView(R.layout.activity_add);
    edit();
    addStudent();



}



public void edit() {
    name = (EditText) findViewById(R.id.StudentName);
    phone = (EditText) findViewById(R.id.phone);
    final Button addStudent = (Button) findViewById(R.id.AddStudent);

    name.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            addStudent.setEnabled(!name.getText().toString().trim().isEmpty());
            Fname = name.getText().toString();

            String phoneNumber = phone.getText().toString();
            FphoneNumber = Integer.parseInt(phoneNumber);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }


    });
}





public void addStudent() {

    add = (Button) findViewById(R.id.AddStudent);

    add.setOnClickListener(new View.OnClickListener() {
        @Override

        public void onClick(View v) {

            Intent intent = new Intent(AddActivity.this, MainActivity.class);
            intent.putExtra("studentName",name.getText().toString() );
            intent.putExtra("phoneNumber",phone.getText().toString());
            startActivity(intent);

            Student student = new Student(Fname, FphoneNumber);

            students.add(student);



        }
    });
}

public void addStudent(){
    add = (Button) findViewById(R.id.AddStudent);
    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(AddActivity.this,Record.class);
            startActivity(intent);
        }
    });

}

Student.java - https://jsfiddle.net/gy0g7b0s/

public class Student {

String mName;
int mPhoneNumber;


public Student (String name, int number){
    mName = name;
    mPhoneNumber = number;
};

public String getmName() {
  return mName;
}

public String getmName(String newName) {
    return (this.mName = newName);
}

public int getmPhoneNumber() {
    return this.mPhoneNumber;
}

public int getmPhoneNumber(int newPhoneNumber) {
    return (this.mPhoneNumber = newPhoneNumber);
}

@Override
public String toString() {
    return String.format("%s\t%f",this.mName, this.mPhoneNumber);
}

[1] : [Image of Main Activity Page] http://imgur.com/a/pMWt4

[2] : [Image of Add Activity Page] http://imgur.com/a/8YvVc

8
Ma'lumotlar bazasidan foydalanishni tavsiya etaman.
qo'shib qo'ydi muallif Code-Apprentice, manba
@ Ssyarin na na gudup why why not?
qo'shib qo'ydi muallif Code-Apprentice, manba
@ Ssyarin na na gudup why why not?
qo'shib qo'ydi muallif Code-Apprentice, manba
AddActivity xizmatini qanday ochasiz?
qo'shib qo'ydi muallif brijesh kumar, manba
AddActivity xizmatini qanday ochasiz?
qo'shib qo'ydi muallif brijesh kumar, manba
Ushbu ikkita faoliyat bilan arraylistni baham ko'rishni taklif qilaman va shuning uchun arraylistni AddActivity-da yangilang. Arraylistni yangilab turgach, ro'yxatni ko'rish adapterini ushbu arraylist yordamida MainActivity ning onResume() usulida o'rnating.
qo'shib qo'ydi muallif Dhruvam Gupta, manba
Ushbu ikkita faoliyat bilan arraylistni baham ko'rishni taklif qilaman va shuning uchun arraylistni AddActivity-da yangilang. Arraylistni yangilab turgach, ro'yxatni ko'rish adapterini ushbu arraylist yordamida MainActivity ning onResume() usulida o'rnating.
qo'shib qo'ydi muallif Dhruvam Gupta, manba
@ Code-Apprentice Ma'lumotlar bazasini ishlatishni rejalashtirmayman.
qo'shib qo'ydi muallif 宿命的な孤独, manba
@brijesh qimor Faoliyatimni asosiy faoliyat sahifasidan ochaman va MainActivity sahifasida "Qo'shish" tugmasini bosgandan keyin AddActivity sahifasini ochadi. Kodlarimni tahrir qilib, buni qanday qilishim mumkinligini ko'rsata olasizmi? Men qanday qilib boshlash kerakligini bilmayman.
qo'shib qo'ydi muallif 宿命的な孤独, manba
@ Code-Apprentice Ma'lumotlar bazasini ishlatishni rejalashtirmayman.
qo'shib qo'ydi muallif 宿命的な孤独, manba
Salom, siz mening kodlarimni tahrirlash orqali buni qanday qilishimni ko'rsata olasizmi? Men qanday qilib boshlash kerakligini bilmayman.
qo'shib qo'ydi muallif 宿命的な孤独, manba
Salom, siz mening kodlarimni tahrirlash orqali buni qanday qilishimni ko'rsata olasizmi? Men qanday qilib boshlash kerakligini bilmayman.
qo'shib qo'ydi muallif 宿命的な孤独, manba
@ Code-Apprentice bu maktab loyihasi va mening ma'ruzachim ma'lumotlar bazasidan foydalanish o'rniga qator yaratish uchun fayl tizimidan foydalanishni so'radi.
qo'shib qo'ydi muallif 宿命的な孤独, manba

9 javoblar

Yuqorida aytib o'tilganidek, startActivityForResult usulini ishlatish to'g'ri bo'ladi. Buni tekshiring .

Qanday qilib bu haqda gapirish mumkin? Kodni o'zgartirish:

public void add() {
    Student student;
    addStudent = (Button) findViewById(R.id.add);
    addStudent.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, AddActivity.class);
            startActivityForResult(intent,123);
        }
    });
}
}

va shu faoliyatda (MainActivity) natijani eshiting Shuningdek, sizga ob'ektlarni yuborish uchun parceler.org lib dan foydalanishni tavsiya qilaman

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode== Activity.RESULT_OK && requestCode==123){
       //perform your list addition operation here and notify the adapter for change
       //the returned data comes in 'data' parameter and would recommend you to use parcels.org lib
       //for sending parcelable pojo across activities and fragments. 
        list.add(Parcels.unwrap(data.getParcelableArrayExtra(YOUR_KEY)));
        adapter.notifyDataSetChanged();
    }
}

Va AddActivity-da, buni qo'shganda, buni bajaring.

    public void addStudent() {
// add the 'add' button view to the oncreatemethod 
//        add = (Button) findViewById(R.id.AddStudent);

        add.setOnClickListener(new View.OnClickListener() {
            @Override

            public void onClick(View v) {
//                  Do not restart the activity that opened this activty
//                  this activity is anyways on top of the MainActivity. Just finish this activty setting the result

//                Intent intent = new Intent(AddActivity.this, MainActivity.class);
//                intent.putExtra("studentName",name.getText().toString() );
//                intent.putExtra("phoneNumber",phone.getText().toString());
//                startActivity(intent);

//                How to do that? 
                Student student = new Student(Fname, FphoneNumber);
                Intent intent = new Intent();
                intent.putExtra(YOUR_KEY, Parcels.wrap(student));
               //you can also do it without the parcels lib 
//                intent.putExtra("studentName",name.getText().toString() );
//                intent.putExtra("phoneNumber",phone.getText().toString());

                setResult(123,intent);//set the result code. it should be the same one as the one your listening on in MainAcitivty

               //then just finish this activity. 
                finish();
               //this calls the onActivtyResultMethod in MainActivity which furtther does the logic 
//                students.add(student);

            }
        });
    }

Bu ish kerak! Cheers!

4
qo'shib qo'ydi
Kechirasiz, sizga teamviewer bilan yordam berishingiz mumkin, siz o'zingizning asosiy ro'yxat va adapter narsalarni topishingiz mumkin. Bu erda yaxshi qo'llanma bor
qo'shib qo'ydi muallif MadScientist, manba
ro'yxat va boshqa o'zgaruvchilar qizil bo'lgani uchun, bu o'zgaruvchilar aniqlanmasligi mumkin, bu erda ListView (yoki RecyclerView) va Uydagi hamma qavatlardagi narsalarni ko'rsatish uchun foydalanadigan yakuniy ro'yxat sizning loyihangizga ixtiyoriy ravishda qo'sha oladigan kutubxona. Adaptor, agar sizda mavjud bo'lsa, ma'lumotni RecyclerView ga bog'laydigan sinfdir. Va Activty.RESULT_OK statik o'zgaruvchilardir. qanday faoliyat bilan shug'ullanishingiz kerak emas.
qo'shib qo'ydi muallif MadScientist, manba
Menga yordam beradigan guruh kuzatuvchisi bormi? :)
qo'shib qo'ydi muallif 宿命的な孤独, manba
Salom uchun (resultCode == Activity.RESULT_OK && requestCode == 123) "Faoliyat" degani nima? Bundan tashqari, list.add (Parcels.unwrap (data.getParcelableArrayExtra (YOUR_KE & zwnj; Y))); adapter.notifyDataSetChanged (); Nima uchun "ro'yxat", "yer uchastkalari" va "adapter" qizil rangda? Belgini o'chirib bo'lmadi.
qo'shib qo'ydi muallif 宿命的な孤独, manba

Use StartActivityForResult for AddActivity and return object from here and use in MainActivity. For example see here

3
qo'shib qo'ydi
Faqat bog'lanadigan javoblar odatda Stack Overflow-da frowned on . Vaqt o'tishi bilan atrof atrofidagi ulanishlar mumkin va mavjud bo'lmay qoladi, ya'ni sizning javobingiz kelajakda foydalanuvchilar uchun foydasizdir. Javobingizning umumiy tafsilotlarini o'zingizning chop etilgan maqolangizda havolani keltirib, keltirsangiz yaxshi bo'lardi.
qo'shib qo'ydi muallif yennsarah, manba
bu yerga qarang noreferrer"> bog'laning
qo'shib qo'ydi muallif Mundroid, manba
Salom, siz menga kodlarni tahrirlashda yordam bera olasizmi va menga qanday qilib buni amalga oshirishingizni ko'rsatishingiz mumkin, chunki men aslida qanday boshlashni bilmayman ...
qo'shib qo'ydi muallif 宿命的な孤独, manba

Ma'lumotni faylda saqlaganingizdan so'ng, ma'lumotlarni qo'shish faqat faylga ma'lumotlarni yozishi kerak. Keyin asosiy faoliyat faylni har doim yangilab turishi kerak.

0
qo'shib qo'ydi
Fayllarni qanday o'qish va yozishni bilib, @ ssyūk na na gusta start
qo'shib qo'ydi muallif Code-Apprentice, manba
Menga murojaat qilish uchun sizda ba'zi havolalar bormi? :)
qo'shib qo'ydi muallif 宿命的な孤独, manba
Men qanday qilib boshlashim haqida hech qanday fikr yo'q, chunki menda hech qanday fikr yo'q ...
qo'shib qo'ydi muallif 宿命的な孤独, manba

Shogirddan ma'lumotlarni olishdan so'ng, tegishli ma'lumotlarni bir to'plamga qo'ying va faqat asosiy faoliyatga qaytish niyatidan foydalaning. So'ng asosiy faoliyatdagi ma'lumotlarni olish uchun paketlardan foydalaning.

0
qo'shib qo'ydi
Intent yourFirstAct= new Intent(firstAct.this,second.class);
yourFirstAct.putExtra("","");
startActivitForResult(yourFirstAct);

birinchi faoliyatda,

@Override
public void onAcitivityResult(....){
 super();
}

siz qilgan ikkinchi ishingizda,    narsalaringizni ikkinchi faoliyatda xohlagan narsani qiling. va uni mainActivity-ga o'tkazing

Intent yoursecAct= new Intent();
yourSecAct.putExtra("","");
setResult(yourSecAct);
finish();

Agar siz FRAGMENTdan foydalansangiz

Agar siz startActivityResult() qismini ishlasa,

fragmentingiz mainActivity() ning super() funksiyasini qaytarishi kerak

   public void onAcitivityResult(...){super()}
0
qo'shib qo'ydi

Siz boshlanadiganActivityForResultdan xuddi shunday foydalanishingiz mumkin. Agar siz hali javob topmagan bo'lsangiz, iltimos, menga xabar bering. Sizga kod beraman.

Yuqoridagilarning ko'pi bu narsani juda yaxshi shaklda belgilab qo'ygan.

0
qo'shib qo'ydi

Ma'lumotlar bazasidan foydalanishni istamasangiz statik klassdan foydalanishni taklif qilaman. Yoki biryoki faylni ishlatsangiz, keyingi faoliyatga qo'shganda va undan o'qiganingizda faylni yozish uchun juda oddiy.

Buni faqat Statik sinf yaratishingiz mumkin.

public static class MyStaticClass{
    private static ArrayList  mStudents = new ArrayList()
    public static void addStudent(Student theNewStudent){
        mSudents.add(theNewStudent);
    }
    public static List getStudents(){
        return mStudents;
    }
}

yoki fayl bilan:

public static class MyFileClass{
        private static String pathFile = "Your path";
        public static void addStudent(Student theNewStudent){
            File file = new OutputStreamWriter(new FileOutputStream(pathFile,true)); //the true is to append to the file
            file.write(/*parse your student as a string*/);
            file.close();
        }
        public static List getStudents(){
            ArrayList students = new ArrayList<>()
            File file = new File(pathFile);
            Scanner sc = new Scanner(file);

            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                //parse your line to a student object
                students.add(yourNewStudent);
            }
            sc.close();
            return students;
        }
    }

Talabalarni qo'shing va talabalarni to'g'ri sinfga quyib oling.

MyStaticClass.addStudent(student);

yoki

MyFileClass.addStudent(student);

Umid qilamanki yordam beradi. Onclick tinglovchilaringizda:

public void onClick(View v) {

    Intent intent = new Intent(AddActivity.this, MainActivity.class);
    Student student = new Student(Fname, FphoneNumber);
    MyStaticClass.addStudent(student);//yoki the FileClass
    startActivity(intent);
}

va ro'yxatni qayerdan olishni ko'rmayapman. faqat sinfning getStudents dan foydalaning.

0
qo'shib qo'ydi
Muammo yo'q, umid qilamanki.
qo'shib qo'ydi muallif Ivan, manba
Tahrirga yana bir qarang.
qo'shib qo'ydi muallif Ivan, manba
Ha, kerak. Buni Qo'shimchalar sifatida qo'shish o'rniga qo'shishni xohlagan usulda qo'shing. Va siz ro'yxatga kerak bo'lganda, faqat uni olish usuli orqali oling.
qo'shib qo'ydi muallif Ivan, manba
Tahririmga qarang.
qo'shib qo'ydi muallif Ivan, manba
Salom, shogirdni AddText tugmachasi orqali EditText qutilari bilan qo'shmoqchiman. Bu ular bilan ishlaydimi?
qo'shib qo'ydi muallif 宿命的な孤独, manba
Xullas, men uni sinab ko'raman! Muammo bo'lsa, yana sizga xabar beraman. Rahmat! :)
qo'shib qo'ydi muallif 宿命的な孤独, manba
Men uchun jsfiddledagi kodlarni tartibga solish kerakmi? Men qanday o'zgarishni bilmayman.
qo'shib qo'ydi muallif 宿命的な孤独, manba
Bunga qanday o'tishim mumkin?
qo'shib qo'ydi muallif 宿命的な孤独, manba

To kind of expand a little bit on MadScientist's answer, ListView's need adapters in order set the data in it's view. You'll need to define an ArrayAdapter for your list view to communicate with. This will need to go in your MainActivity and will be initialized in the onCreate method. Assuming you want to display both types of information, you'll need to construct your adapter with the built in layout for showing two items via android.R.layout.simple_list_item_2. If you would like to create your own layout, however, you can look up how to do that here.

public class MainActivity extends AppCompatActivity {
    Button addStudent;
    ArrayAdapter adapter;
    ArrayList students = new ArrayList();
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_2, students);
        ListView listView = (ListView) findViewById(R.id.listView);
        listView.addAdapter(adapter);
        add();
}

Call the startActivityForResult(intent, 123) in your Listener to start the new activity. Then, once you have typed in your data, add your items to the intent and call finish() in your AddActivity. Override the onActivityResult in your MainActivity to pull the items off your intent and add them to your list. Finally, notify the adapter of the changes via adapter.notifyDataSetChanged()

0
qo'shib qo'ydi

This is about communication between Activities. You can use event bus to realize this. https://github.com/JackZhangqj/EventBus

Keyin 1-ilovadagi build.grade uchun avtobusga bog'liqlik qo'shing

compile "de.greenrobot:eventbus:3.0.0
  1. Register and unregister your subscribe in the MainActivity.java

    @Override protected void onStart() { super.onStart(); EventBus.getDefault().register(this); }

    @Override protected void onStop() { super.onStop(); EventBus.getDefault().unregister(this); }

AddActivity.java-da voqea 3.Post

EventBus.getDefault().post(new Student(name.getText().toString(), phone.getText().toString()));

MainActivity-da hodisalarni boshqarish usulini qo'llang

//The student is the added student in the AddActivity.java
public void onEventMainThread(Student student) {

}
0
qo'shib qo'ydi