简体   繁体   English

从另一个活动更新ListView

[英]Updating ListView from another Activity

Activity 1: Contains ListView. 活动1:包含ListView。

Acitivity 2: Contains SeekBar that changes a SharedPreferences variable which used by the ListView. Acitivity 2:包含SeekBar,它可以更改ListView使用的SharedPreferences变量。 After changing the SeekBar and returning to Activity 1, the ListView need to be updated and refreshed. 更改SeekBar并返回到活动1后,需要更新和刷新ListView。

After I update the SeekBar at Activity 2 I use the following code to return to Activity 1: 在活动2中更新SeekBar之后,我使用以下代码返回活动1:

        toolbar.setNavigationIcon(R.drawable.ic_arrow_forward_white_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//I need to update the list here, There may be a new data!
                onBackPressed();

            }
        });

my Activity 1 remains the same ListView unupdated. 我的活动1保持未更新的相同ListView。

I can't find a good way to refresh my list in Activity 1 after changing the Seekbar, since the adapter available only at Activity 1. I was trying to pass it as intent, but I noticed it's impossible to pass adapters as extras. 更改Seekbar之后,我找不到在活动1中刷新列表的好方法,因为适配器仅在活动1中可用。我试图将其作为意图进行传递,但我注意到无法将适配器作为附加传递。

Any help? 有什么帮助吗?

Code I use to update the ListView in Activity 1: 我在活动1中用于更新ListView的代码:

mainListView = (ListView) findViewById(R.id.main_listview);
                    // 5. Set this activity to react to list items being pressed
                    //mainListView.setOnItemClickListener(MainActivity.this);
                    // 10. Create a JSONAdapter for the ListView
                    mJSONAdapter = new JSONAdapter(MainActivity.this, getLayoutInflater());
                    // Set the ListView to use the ArrayAdapter
                    mainListView.setAdapter(mJSONAdapter);

Logcat error after trying Udi's solution: 尝试Udi解决方案后出现Logcat错误:

08-27 12:58:29.400    1595-1595/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: il.co.test.test, PID: 1595
    java.lang.RuntimeException: Unable to resume activity {il.co.test.test/il.co.test.test.MainActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2788)
            at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2817)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at il.co.test.test.MainActivity.onResume(MainActivity.java:334)
            at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1192)
            at android.app.Activity.performResume(Activity.java:5310)
            at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2778)
            at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2817)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)

EDIT 2: FULL CODE HOW I UPDATE MY LIST - AFTER GPS TRACKING. 编辑2:完整代码如何在GPS跟踪后更新我的列表。 Placed in MainActivity.java. 放在MainActivity.java中。 Called in TabFragment1.java (code below) 在TabFragment1.java中调用(下面的代码)

public void getUpdates()
{
    // Access the device's key-value storage
    mSharedPreferences = getSharedPreferences(PREFS, MODE_PRIVATE);
    searchDistance = mSharedPreferences.getInt(PREF_DISTANCE, 0);
    if (searchDistance == 0)
        searchDistance = DEFAULT_SEARCH_DISTANCE;

        gpsDialog = new ProgressDialog(this);
        gpsDialog.setMessage("Checking your location..");
        gpsDialog.setCancelable(false);

        gpsDialog.show();

        MyLocation.LocationResult locationResult = new MyLocation.LocationResult() {
            @Override
            public void gotLocation(Location location) {
                gpsDialog.dismiss();
                //If we find a location, We will go to the list layout.
                //setContentView(R.layout.fb_list);
                // 4. Access the ListView
                mainListView = (ListView) findViewById(R.id.main_listview);
                // 5. Set this activity to react to list items being pressed
                //mainListView.setOnItemClickListener(MainActivity.this);
                // 10. Create a JSONAdapter for the ListView
                mJSONAdapter = new JSONAdapter(MainActivity.this, getLayoutInflater());
                // Set the ListView to use the ArrayAdapter
                mainListView.setAdapter(mJSONAdapter);
                double lat = location.getLatitude();
                double lon = location.getLongitude();
                query(lat, lon, searchDistance);
            }
        };
        MyLocation myLocation = new MyLocation(this);
        myLocation.getLocation(this, locationResult);
}

Calling this method from my Fragment: 从片段中调用此方法:

    public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final View v = inflater.inflate(R.layout.fb_list, container, false);
    MainActivity king = (MainActivity)getActivity();
    king.getUpdates();
    return v;
}

When I add this: 当我添加此:

@Override
protected void onResume() {
    super.onResume();

    //if the data has changed
    mJSONAdapter.notifyDataSetChanged();
}

app crashes becuase it can't find the json adapter (since it's initalized only after gps location) 应用程序崩溃,因为它找不到json适配器(因为仅在gps位置之后才初始化)

If the adapater's backing data is changed, you should notify the adapter. 如果adapater的后备数据已更改,则应通知适配器。 In your scenario what you might consider is adding a check in onResume method if the data has changed, and if it did change notify the adapter: 在您的方案中,您可能会考虑在onResume方法中添加一个检查,如果数据已更改,并且如果确实更改了,则通知适配器:

@Override
protected void onResume() {
    super.onResume();

    //if the data has changed
    mJSONAdapter.notifyDataSetChanged(); 
}

This is just a Issue of Null Pinter Exception. 这只是一个空品特例外问题。 But the basic steps are as follows 但是基本步骤如下

Create the Adapter and keep it. 创建适配器并保留它。 Keep a reference to the List of items that you pass into the Adapter also, When you come from the Activity 2 As Udi I you can clear the list of Items and Add the new items to it (Do not add the items as a new List, If you do that, you have to reinstantiate the Adapter again and reset the Adapter). 还保留对传递给适配器的项目列表的引用,当您从活动2来时,作为Udi我可以清除项目列表并向其中添加新项目(不要将项目添加为新列表) ,如果这样做,则必须重新实例化适配器并重置适配器)。 And then call the notifyDataSetChanged() on the adapter. 然后在适配器上调用notifyDataSetChanged()

EDIT1: 编辑1:

I suggest you to look into the Activity life-cycle more and communication between Activity and Fragment. 我建议您更多地研究“活动”生命周期以及“活动”和“片段”之间的通信。 I assume that you toggle fragments (TabFragment1) inside Activity 1. 我假设您在活动1中切换片段(TabFragment1)。

I do not recommend this, But you can try this, 我不建议这样做,但是您可以尝试一下,

@Override
protected void onRestart() {
    super.onRestart();
    getUpdates();
    mainListView.setAdapter(mJSONAdapter);
}

But you have to make sure that, 但是您必须确保

// 10. Create a JSONAdapter for the ListView
                mJSONAdapter = new JSONAdapter(MainActivity.this, getLayoutInflater());

this mJsonAdapter is not null. 此mJsonAdapter不为null。

I solved it by replacing this: 我通过替换它解决了这个问题:

        toolbar.setNavigationIcon(R.drawable.ic_arrow_forward_white_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//I need to update the list here, There may be a new data!
                onBackPressed();

            }
        });

with this: 有了这个:

toolbar.setNavigationIcon(R.drawable.ic_arrow_forward_white_24dp);
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent refresh = new Intent(Settings.this, MainActivity.class);
                    Settings.this.startActivity(refresh);
                }
            });

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM