简体   繁体   English

Android:如何在onClick方法中将对象从一个活动传递到另一个活动,并将其用于AsyncTask类

[英]Android: How to pass an object from one activity to another in an onClick method and use it for an AsyncTask class

I have a problem that is a little hard to explain. 我有一个问题有点难以解释。 I am building an android application for trip planning. 我正在为旅行计划构建一个Android应用程序。 I have a main activity that contains the map item and some other buttons and an AsyncTask class where the communication with the server is done and the path is displayed on the map. 我有一个主活动,包含地图项和一些其他按钮和AsyncTask类,其中与服务器的通信完成,路径显示在地图上。 I am trying to make it work offline by saving the response from the server in sqllite database. 我试图通过在sqllite数据库中保存服务器的响应使其脱机工作。

I have an Activity called MainActivity. 我有一个名为MainActivity的Activity。 There, I have a method for menu items 在那里,我有一个菜单项的方法

public boolean onOptionsItemSelected(final MenuItem pItem) {        
    switch (pItem.getItemId()) {
    case R.id.recent_trips:
            startActivity(new Intent(this, recentTripsActivity.class));
            break;
    default:
             break;
        }

        return false;
    }
}

Here is the current method for calling the AsyncTask class 这是调用AsyncTask类的当前方法

btnPlanTrip.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
      tripReq = new TripRequest(MainActivity.this,activityHandler,db);
    tripReq.execute(request);
    }
     });
}

When I click on the recent_trips from the menu button, recentTripsActivity opens. 当我从菜单按钮单击recent_trips时,将打开recentTripsActivity。 Basically, in this class I retrieve some data from mysqllite database and present it on a listView through an adapter. 基本上,在这个类中,我从mysqllite数据库中检索一些数据,并通过适配器将它呈现在listView上。 There, I have a method view.setOnClickListener in which when a list item is clicked I take a certain value (res=listItem.getofflineResult();). 在那里,我有一个方法view.setOnClickListener,其中当单击列表项时,我取一个值(res = listItem.getofflineResult();)。 I would like to use that value on Main Activity (see below for more details). 我想在Main Activity上使用该值(有关详细信息,请参见下文)。 Here is the code. 这是代码。

public class recentTripsActivity extends Activity implements Serializable {
    private ImageButton stopSearch;
    private AutoCompleteTextView searchField;
    SQLiteDatabase db;
    OfflineTripRequest tripReq;
    String res;
    //db = openOrCreateDatabase("AndroidDatabase.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);


     private ListView listview;
     private ArrayList mListItem;
     ItemBO listItem;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
            setContentView(R.layout.recent_trips); 

            //open database connection
            db = openOrCreateDatabase("AndroidDatabase.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
            int i=0;
            String [] str={"id","description","offlineResult"};
            listview = (ListView) findViewById(R.id.lview_trips);

            mListItem = new ArrayList<ItemBO>();

            Cursor cursor = db.query("tbl_offlinePathResult",str, null, null, null, null, null);

            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
                i++;
                ItemBO listItem = new ItemBO(i,cursor.getString(1),cursor.getString(2));
                mListItem.add(listItem);
                cursor.moveToNext();
                if(i==10){
                    break;
                }
            }
            // Make sure to close the cursor
            cursor.close();
            i++;

            listview.setAdapter(new ListAdapter(recentTripsActivity.this, R.id.lview_trips,mListItem));
            db.close();
    }


//***ListAdapter***
 class ListAdapter extends ArrayAdapter { //--CloneChangeRequired
    private ArrayList mList; //--CloneChangeRequired
    private Context mContext;

    @SuppressWarnings("unchecked")
    public ListAdapter(Context context, int textViewResourceId,
            ArrayList list) { //--CloneChangeRequired
        super(context, textViewResourceId, list);
        this.mList = list;
        this.mContext = context;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        try {
            if (view == null) {
                LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = vi.inflate(R.layout.list_item_saved_paths, null); //--CloneChangeRequired(list_item)
            }
            final ItemBO listItem = (ItemBO) mList.get(position); //--CloneChangeRequired
            if (listItem != null) {
                // setting list_item views
                ((TextView) view.findViewById(R.id.tv_name))
                        .setText(listItem.getDescription());

                view.setOnClickListener(new OnClickListener() {
                    public void onClick(View arg0) { //--clickOnListItem
                         res=listItem.getofflineResult(); 

                    }
                });
            }
        } catch (Exception e) {
            Log.i(recentTripsActivity.ListAdapter.class.toString(), e.getMessage());
        }
        return view;
    }
 }
}

I would like to pass the data mentioned above(res=listItem.getofflineResult() to MainActivity. After doing that I would like to call an AsyncTask class and pass that data to that class. How can I do all this by clicking on the listItem? As I said before the map is on MainActivity but the click will happen from a different Activity. I hope I made my self clear enough, If you have any questions please ask me 我想将上面提到的数据(res = listItem.getofflineResult()传递给MainActivity。 之后我想调用AsyncTask类并将该数据传递给该类。如何通过单击listItem来完成所有这些操作。 ?正如我之前所说的那样,地图是在MainActivity上,但点击将在不同的活动中发生。我希望我自己清楚,如果你有任何问题请问我

I generally use a singleton method when passing data in an android app. 我通常在Android应用程序中传递数据时使用单例方法。 If you are unfamiliar, it is basically a static class that always returns the same instance. 如果你不熟悉,它基本上是一个静态类,总是返回相同的实例。 This allows you to create multiple 'instances' of the class that all share the same data. 这允许您创建所有共享相同数据的类的多个“实例”。

Singleton Design Pattern 单身设计模式

Well you can pass the res (String?) in many ways, the simple is throw preferences: 那么你可以通过多种方式传递res(String?),简单就是throw首选项:

SharedPreferences settings = context.getSharedPreferences(APPNAME, 0);
SharedPreferences.Editor editor = settings.edit();
    editor.putString("res", res);
    editor.commit();

and then in MainActiviy get: 然后在MainActiviy获得:

SharedPreferences settings = context.getSharedPreferences(APPNAME, 0);
res = settings.getString("res","");

You can also save in the local database, or like "tkcsam" says using a static and abstract variable. 您也可以保存在本地数据库中,或者像“tkcsam”那样使用静态和抽象变量。

public abstract Global{
 public static String res;
}

and you can acess in any Activity like : 你可以在任何活动中访问:

Global.res = "A"

First, you need to override onListItemClick in your list. 首先,您需要覆盖列表中的onListItemClick。 You will then need to put the needed information into a bundle and end the activity. 然后,您需要将所需信息放入一个包中并结束活动。 This bundle gets "returned" to the calling activity in that activity's onActivityReuslt method (which you will need to override). 该包被“返回”到该活动的onActivityReuslt方法中的调用活动(您需要覆盖该方法)。 See: 看到:

Passing Data Between Activities 在活动之间传递数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在android Kotlin中将对象从一个活动传递到另一个活动? - how to pass object from one activity to another activity in android Kotlin? 使用 Parcelable 将对象从一个 android 活动传递到另一个 - Use Parcelable to pass an object from one android activity to another Android-如何从Java类传递另一个活动应用程序上下文将片段扩展到asynctask? - Android - How to pass another activity application context from java class extends fragments to asynctask? 如何在同一活动android中将变量从一种方法传递到另一种方法 - How to pass a variable from one method to another in the same activity android Android从另一个类使用OnClick方法 - Android Use OnClick Method From Another Class 如何在Android上将原始对象(不复制)从一项活动传递到另一项活动 - How to pass an origin object(NOT COPY) from one activity to another on Android 如何在Android中将对象列表从一个活动传递到另一个活动? - How to pass object list from one activity to another in android? 如何在Android上将对象从一个活动传递到另一个活动 - How to pass an object from one activity to another on Android 如何使用一个AsyncTask类在Android中应用不同的Activity - How to use one AsyncTask Class to apply different Activity in Android 如何将asynctask传递给android中的另一个活动? - How to pass asynctask to another activity in android?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM