如何将字符串从一个活动发送到另一个活动

Posted

技术标签:

【中文标题】如何将字符串从一个活动发送到另一个活动【英文标题】:How to send string from one activity to another 【发布时间】:2018-09-24 07:59:33 【问题描述】:

我正在尝试制作一个应用程序来列出我所在地区的学校,并在数据库中制作了一个表格来包含这些学校。我制作了一个带有可点击项目的列表视图以列出学校的名称,当我点击该项目以移动到另一个活动并发送点击的学校名称以列出有关学校的更多信息时,该应用程序停止工作。以下是包含此列表视图的活动之一:

package com.example.welcome.madrasti;

import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

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

public class ListOfSchoolsPublic extends AppCompatActivity 

        Intent redirect;
        Intent item;
        ListView list;
        ArrayList<String>  _sa;
        DBAdapter db;

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

            openDB();

            list= (ListView) findViewById(R.id.usersList);

            redirect = getIntent();

            Cursor cursor = db.getAllRows();

            _sa= new  ArrayList<String>();

            //cursor.moveToFirst();

            Log.d("CURSORCOUNT","Number of rows in the Cursor is = " + String.valueOf(cursor.getCount()));




            while(cursor.moveToNext()) 

                if(cursor.getString(DBAdapter.COL_SChOOL_TYPE_TABLE_2).equals("حكومية"))
                _sa.add(cursor.getString(DBAdapter.COL_SCHOOLNAME_TABLE_2));

            

            cursor.close();


            @SuppressWarnings("rawtypes")
            ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,_sa);

            list.setAdapter(new TempLyaout(ListOfSchoolsPublic.this,_sa));


           list.setOnItemClickListener(new AdapterView.OnItemClickListener()
            
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
                

                    String selectedItem = (String) arg0.getItemAtPosition(position);

                    itemInfo(selectedItem);
                
            );



    

    ///////////////////////////////////////////////////////////////

    public void itemInfo(String selectedItem)

           item = new Intent(getApplicationContext(), NewSchool.class);

           item.putExtra("schoolName",selectedItem);

           startActivity(item);

    

    ///////////////////////////////////////////////////////////////
    @Override
    protected void onDestroy() 
        super.onDestroy();
        closeDB();

    // end onDestroy method



    ///////////////////////////////////////////////////////////////

    private void openDB() 
        db = new DBAdapter(ListOfSchoolsPublic.this);
        db.open();
     // end openDB method

    //////////////////////////////////////////////////////////////

    private void closeDB() 
        db.close();
     // end closeDB method


以下是每个列表项应移动到的活动:

package com.example.welcome.madrasti;

import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class NewSchool extends AppCompatActivity 

    Intent intent;

    Intent nextPage;

    Button next;

    DBAdapter db;

    TextView t1;

    TextView t2;

    TextView t3;

    TextView t4;

    TextView t5;



    String name;


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

        t1=(TextView)findViewById(R.id.textView9) ;
        t2=(TextView)findViewById(R.id.textView11) ;
        t3=(TextView)findViewById(R.id.textView12) ;
        t4=(TextView)findViewById(R.id.textView17) ;
        t5=(TextView)findViewById(R.id.textView18) ;


        next = (Button) findViewById(R.id.button);
        intent = getIntent();

        name = intent.getStringExtra("schoolName");

        next.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                goNext();
            
        );

        Cursor cursor = db.getAllRows();

        while(cursor.moveToNext()) 

            if(cursor.getString(DBAdapter.COL_SCHOOLNAME_TABLE_2).equals(name))

                t1.setText(DBAdapter.COL_SCHOOLNAME_TABLE_2);
                t2.setText(DBAdapter.COL_FOUNDATION_DATE_TABLE_2);
                t3.setText(DBAdapter.COL_BUY_BOOKS_TABLE_2);
                t4.setText(DBAdapter.COL_HEALTH_TABLE_2);
                t5.setText(DBAdapter.COL_LOCATION_TABLE_2);

            


        

        cursor.close();


    


    public void goNext()

        nextPage = new Intent(getApplicationContext(),NewShoolAct2.class);
        nextPage.putExtra("schoolName",name);
        startActivity(nextPage);

    

    ///////////////////////////////////////////////////////////////
    @Override
    protected void onDestroy() 
        super.onDestroy();
        closeDB();

    // end onDestroy method



    ///////////////////////////////////////////////////////////////

    private void openDB() 
        db = new DBAdapter(NewSchool.this);
        db.open();
     // end openDB method

    //////////////////////////////////////////////////////////////

    private void closeDB() 
        db.close();
     // end closeDB method



以下是上一个活动的XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    android:background="@drawable/login_background"
    tools:context="com.example.welcome.madrasti.NewSchool">

    <AbsoluteLayout
        android:layout_
        android:layout_
        android:orientation="vertical"
        tools:layout_editor_absoluteX="16dp"
        tools:layout_editor_absoluteY="0dp">


        <TextView
            android:id="@+id/textView"
            android:layout_
            android:layout_
            android:layout_x="244dp"
            android:layout_y="54dp"
            android:text="إسم المدرسة:"
            android:textAlignment="center"
            android:textStyle="bold"
            tools:layout_editor_absoluteX="dp"
            tools:layout_editor_absoluteY="10dp" />

        <TextView
            android:id="@+id/textView3"
            android:layout_
            android:layout_
            android:layout_x="240dp"
            android:layout_y="127dp"
            android:text="تاريخ التأسيس:"
            android:textAlignment="center"
            android:textStyle="bold"
            tools:layout_editor_absoluteX="297dp"
            tools:layout_editor_absoluteY="144dp" />

        <TextView
            android:id="@+id/textView4"
            android:layout_
            android:layout_
            android:layout_x="231dp"
            android:layout_y="185dp"
            android:text="كيفية شراء الكتب:"
            android:textAlignment="center"
            android:textStyle="bold"
            tools:layout_editor_absoluteX="284dp"
            tools:layout_editor_absoluteY="210dp" />

        <TextView
            android:id="@+id/textView5"
            android:layout_
            android:layout_
            android:layout_x="215dp"
            android:layout_y="265dp"
            android:text="وضع المرافق الصحية:"
            android:textAlignment="center"
            android:textStyle="bold"
            tools:layout_editor_absoluteX="265dp"
            tools:layout_editor_absoluteY="288dp" />

        <TextView
            android:id="@+id/textView6"
            android:layout_
            android:layout_
            android:layout_x="244dp"
            android:layout_y="340dp"
            android:text="موقع المدرسة:"
            android:textAlignment="center"
            android:textStyle="bold"
            tools:layout_editor_absoluteX="300dp"
            tools:layout_editor_absoluteY="368dp" />

        <Button
            android:id="@+id/button"
            android:layout_
            android:layout_
            android:layout_x="133dp"
            android:layout_y="434dp"
            android:background="@drawable/button"
            android:text="التالي"
            android:textAlignment="center"
            android:textColor="#ffff"
            android:textStyle="bold"
            tools:layout_editor_absoluteX="45dp"
            tools:layout_editor_absoluteY="426dp" />

        <TextView
            android:id="@+id/textView9"
            android:layout_
            android:layout_
            android:layout_x="11dp"
            android:layout_y="77dp"
            android:text="TextView"
            tools:layout_editor_absoluteX="18dp"
            tools:layout_editor_absoluteY="59dp" />

        <TextView
            android:id="@+id/textView11"
            android:layout_
            android:layout_
            android:layout_x="12dp"
            android:layout_y="148dp"
            android:text="TextView"
            tools:layout_editor_absoluteX="12dp"
            tools:layout_editor_absoluteY="150dp" />

        <TextView
            android:id="@+id/textView12"
            android:layout_
            android:layout_
            android:layout_x="32345dp"
            android:layout_y="32418dp"
            android:text="TextView"
            tools:layout_editor_absoluteX="16dp"
            tools:layout_editor_absoluteY="235dp" />

        <TextView
            android:id="@+id/textView17"
            android:layout_
            android:layout_
            android:layout_x="15dp"
            android:layout_y="299dp"
            android:text="TextView"
            tools:layout_editor_absoluteX="21dp"
            tools:layout_editor_absoluteY="37dp" />

        <TextView
            android:id="@+id/textView18"
            android:layout_
            android:layout_
            android:layout_x="16dp"
            android:layout_y="372dp"
            android:text="TextView"
            tools:layout_editor_absoluteX="17dp"
            tools:layout_editor_absoluteY="381dp" />

        <TextView
            android:id="@+id/textView20"
            android:layout_
            android:layout_
            android:layout_x="16dp"
            android:layout_y="219dp"
            android:text="TextView"
            tools:layout_editor_absoluteX="10dp"
            tools:layout_editor_absoluteY="215dp" />
    </AbsoluteLayout>

</android.support.constraint.ConstraintLayout>

以下是应用崩溃时的日志猫:

04-13 17:57:49.245 5828-5828/? E/libprocessgroup: failed to make and chown /acct/uid_10059: Read-only file system
04-13 17:57:49.245 5828-5828/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
04-13 17:57:49.245 5828-5828/? I/art: Late-enabling -Xcheck:jni
04-13 17:57:49.435 5828-5838/? I/art: Debugger is no longer active
04-13 17:57:49.492 5828-5828/? I/InstantRun: starting instant run server: is main process
04-13 17:57:49.602 5828-5843/? W/art: Suspending all threads took: 11.737ms
04-13 17:57:49.605 5828-5843/? I/art: Background sticky concurrent mark sweep GC freed 2038(168KB) AllocSpace objects, 0(0B) LOS objects, 25% free, 832KB/1117KB, paused 13.068ms total 21.305ms
04-13 17:57:49.630 5828-5828/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
04-13 17:57:49.779 5828-5847/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
04-13 17:57:49.784 5828-5828/? D/Atlas: Validating map...
04-13 17:57:49.810 5828-5847/? D/libEGL: loaded /system/lib/egl/libEGL_emulation.so
    loaded /system/lib/egl/libGLESv1_CM_emulation.so
04-13 17:57:49.820 5828-5847/? D/libEGL: loaded /system/lib/egl/libGLESv2_emulation.so
04-13 17:57:49.848 5828-5847/? I/OpenGLRenderer: Initialized EGL, version 1.4
04-13 17:57:49.878 5828-5847/? D/OpenGLRenderer: Enabling debug mode 0
04-13 17:57:49.896 5828-5847/? W/EGL_emulation: eglSurfaceAttrib not implemented
04-13 17:57:49.896 5828-5847/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xe2c15340, error=EGL_SUCCESS

请问有什么问题吗?如何解决?

【问题讨论】:

那些日志不是你需要的。您正在寻找the stack trace from the crash,它可能全是红色的。 按照 Mike 的说法查看您的 LogCat,但要查找带有红色且以文本“Caused by”开头的消息。 【参考方案1】:

使用意图并首先阅读基本的android。已经有许多可用的选项。

【讨论】:

是的。但是,这并不能解释应用程序崩溃的原因(问题的最后一句话),这可能是学生工程想要知道的【参考方案2】:

您可以像这样将字符串存储到其他类中:

存储字符串:

String selectedItem = (String) arg0.getItemAtPosition(position);

Share.love=selectedItem ;

获取字符串:

在您的下一个活动中

Textview textview=(Textview)findviewbyid(R.id.yourname);
textview.setText(Share.love);

上课

public class Share 

public static String love = "";


【讨论】:

【参考方案3】:

尝试以下示例(它使用 putExtra() 将字符串传递给另一个活动):

Demo15.class:------------

public class Demo15 extends AppCompatActivity 

private Button b;
private EditText edt;
private final String EXTRA_TEXT_ = "extra_text_";

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.demo17);

    edt = (EditText) findViewById(R.id.edt);

    b = (Button) findViewById(R.id.b);
    b.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 
            Intent i = new Intent(Demo15.this, Demo16.class);
            if (!edt.getText().toString().isEmpty()) 
                i.putExtra(EXTRA_TEXT_, edt.getText().toString());
            
            startActivity(i);
        
    );


Demo16.class:-------

public class Demo16 extends AppCompatActivity 

private TextView tv;
private final String EXTRA_TEXT_ = "extra_text_";

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.demo18);

    tv = (TextView) findViewById(R.id.tv);

    if (getIntent() != null) 
        if (getIntent().getStringExtra(EXTRA_TEXT_) != null) 
            tv.setText(getIntent().getStringExtra(EXTRA_TEXT_));
        
    


demo17.xml:-------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_
android:layout_
android:orientation="vertical">

<EditText
    android:layout_
    android:layout_
    android:hint="Enter text to pass"
    android:id="@+id/edt"/>

<Button
    android:layout_
    android:layout_
    android:text="Start the other activity"
    android:textAllCaps="false"
    android:layout_marginTop="50dp"
    android:id="@+id/b"/>

</LinearLayout>

demo18.xml:---------

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_
android:layout_>

<TextView
    android:layout_
    android:layout_
    android:text="####"
    android:id="@+id/tv"/>

</android.support.constraint.ConstraintLayout>

【讨论】:

【参考方案4】:

使用带有意图的捆绑包作为 android 标准。 示例:

Intent intent=new Intent(CurrentActivity.this,NewActivity.class);
intent.putExtra("schoolname","Name of school");
startActivity

【讨论】:

以上是关于如何将字符串从一个活动发送到另一个活动的主要内容,如果未能解决你的问题,请参考以下文章

如何将图像从一项活动发送到另一项活动?

如何使用意图将哈希图值发送到另一个活动

Android:如何将界面从一个活动发送到另一个活动

将多个 Intent 从单个 Activity 发送到另一个 Activity

如何在android中将图像从一个活动发送到另一个活动?

如何将当前位置从一项活动发送到另一项活动?