使用先前选择的数据错误重新加载活动

时间:2018-10-11 05:59:57

标签: java android json sharedpreferences android-spinner

因此,我开发了一个android新闻应用程序。工具栏上有一个微调器项目,并且根据微调器的选择重新加载数据。但是,当数据重新加载时,对于某些项目,它直接加载相关内容,而对于另一些项目,则加载先前选择的微调器数据。当前项目的当前数据仅在使用我已实现的滑动刷新功能重新加载相同的微调器数据后显示。我希望与该选择相关的正确数据能够在第一次加载时自动加载,而不必一直刷新。

下面是我的MainActivity,调用了所有这些函数。

package com.example.app.activities;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.messaging.FirebaseMessaging;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import com.example.app.Config;
import com.example.app.R;
import com.example.app.fragment.FragmentCategory;
import com.example.app.fragment.FragmentFavorite;
import com.example.app.fragment.FragmentProfile;
import com.example.app.fragment.FragmentRecent;
import com.example.app.fragment.FragmentVideo;
import com.example.app.utils.AppBarLayoutBehavior;
import com.example.app.utils.Constant;
import com.example.app.utils.GDPR;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;

public class MainActivity extends AppCompatActivity {


String URL="url" //outputs JSON data

private long exitTime = 0;
MyApplication myApplication;
View view;
private BottomNavigationView navigation;
public ViewPager viewPager;
private Toolbar toolbar;
MenuItem prevMenuItem;
int pager_number = 5;
BroadcastReceiver broadcastReceiver;
Spinner mySpinner;
ArrayList<String> spinnerConstituencyName;
int spinConstID;
private PrefManager prefManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //Set Font
    CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
            .setDefaultFontPath("fonts/Arkhip_font.ttf")
            .setFontAttrId(R.attr.fontPath)
            .build());
    setContentView(R.layout.activity_main);
    view = findViewById(android.R.id.content);

    if (Config.ENABLE_RTL_MODE) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
        }
    }

    AppBarLayout appBarLayout = findViewById(R.id.tab_appbar_layout);
    ((CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams()).setBehavior(new AppBarLayoutBehavior());

    myApplication = MyApplication.getInstance();

    toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setTitle(R.string.app_name);

    spinnerConstituencyName = new ArrayList<>();
    mySpinner = findViewById(R.id.mySpinner);
    prefManager = new PrefManager(MainActivity.this);
    loadSpinnerData(URL);

    mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        int check = 0;
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            /*String spinConstituency = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();
            Toast.makeText(getApplicationContext(), spinConstituency, Toast.LENGTH_LONG).show();*/

            if (++check > 1) {
                Intent intent = getIntent(); //MainActivity
                String itemSelected = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();
                //TODO: DONE
                //intent.putExtra("NAME_KEY", itemSelected);
                prefManager.spinWriteString(itemSelected);
                Toast.makeText(getApplicationContext(), "Constituency News Now Showing", Toast.LENGTH_SHORT).show();
                startActivity(intent);
                finish();
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }

    });

    viewPager = findViewById(R.id.viewpager);
    viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
    viewPager.setOffscreenPageLimit(pager_number);

    navigation = findViewById(R.id.navigation);
    navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    viewPager.setCurrentItem(0);
                    return true;
                case R.id.navigation_category:
                    viewPager.setCurrentItem(1);
                    return true;
                case R.id.navigation_video:
                    viewPager.setCurrentItem(2);
                    return true;
                case R.id.navigation_favorite:
                    viewPager.setCurrentItem(3);
                    return true;
                case R.id.navigation_profile:
                    viewPager.setCurrentItem(4);
                    return true;
            }
            return false;
        }
    });

    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            if (prevMenuItem != null) {
                prevMenuItem.setChecked(false);
            } else {
                navigation.getMenu().getItem(0).setChecked(false);
            }
            navigation.getMenu().getItem(position).setChecked(true);
            prevMenuItem = navigation.getMenu().getItem(position);

            if (viewPager.getCurrentItem() == 1) {
                toolbar.setTitle(getResources().getString(R.string.title_nav_category));
            } else if (viewPager.getCurrentItem() == 2) {
                toolbar.setTitle(getResources().getString(R.string.title_nav_video));
            } else if (viewPager.getCurrentItem() == 3) {
                toolbar.setTitle(getResources().getString(R.string.title_nav_favorite));
            } else if (viewPager.getCurrentItem() == 4) {
                toolbar.setTitle(getResources().getString(R.string.title_nav_favorite));
            } else {
                toolbar.setTitle(R.string.app_name);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    if (Config.ENABLE_RTL_MODE) {
        viewPager.setRotationY(180);
    }

    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            // checking for type intent filter
            if (intent.getAction().equals(Constant.REGISTRATION_COMPLETE)) {
                // now subscribe to global topic to receive app wide notifications
                FirebaseMessaging.getInstance().subscribeToTopic(Constant.TOPIC_GLOBAL);

            } else if (intent.getAction().equals(Constant.PUSH_NOTIFICATION)) {
                // new push notification is received
                String message = intent.getStringExtra("message");
                Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();
            }
        }
    };

    Intent intent = getIntent();
    final String message = intent.getStringExtra("message");
    final String imageUrl = intent.getStringExtra("image");
    final long nid = intent.getLongExtra("id", 0);
    final String link = intent.getStringExtra("link");

    if (message != null) {

        LayoutInflater layoutInflaterAndroid = LayoutInflater.from(MainActivity.this);
        View mView = layoutInflaterAndroid.inflate(R.layout.custom_dialog_notif, null);

        final AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
        alert.setView(mView);

        final TextView notification_title = mView.findViewById(R.id.news_title);
        final TextView notification_message = mView.findViewById(R.id.news_message);
        final ImageView notification_image = mView.findViewById(R.id.news_image);

        if (imageUrl.endsWith(".jpg") || imageUrl.endsWith(".jpeg") || imageUrl.endsWith(".png") || imageUrl.endsWith(".gif")) {
            notification_title.setText(message);
            notification_message.setVisibility(View.GONE);
            Picasso.with(MainActivity.this)
                    .load(imageUrl.replace(" ", "%20"))
                    .placeholder(R.drawable.ic_thumbnail)
                    .resize(200, 200)
                    .centerCrop()
                    .into(notification_image);

            alert.setPositiveButton(R.string.dialog_read_more, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(getApplicationContext(), ActivityNotificationDetail.class);
                    intent.putExtra("id", nid);
                    startActivity(intent);
                }
            });
            alert.setNegativeButton(R.string.dialog_dismiss, null);

        } else {
            notification_title.setText(getResources().getString(R.string.app_name));

            notification_message.setVisibility(View.VISIBLE);
            notification_message.setText(message);

            notification_image.setVisibility(View.GONE);

            //Toast.makeText(getApplicationContext(), "link : " + link, Toast.LENGTH_SHORT).show();

            if (!link.equals("")) {
                alert.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent open = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
                        startActivity(open);
                    }
                });
                alert.setNegativeButton(R.string.dialog_dismiss, null);
            } else {
                alert.setPositiveButton(R.string.dialog_ok, null);
            }
        }

        alert.setCancelable(false);
        alert.show();

    }

    GDPR.updateConsentStatus(this);

}

public class MyAdapter extends FragmentPagerAdapter {

    private MyAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                return new FragmentRecent();
            case 1:
                return new FragmentCategory();
            case 2:
                return new FragmentVideo();
            case 3:
                return new FragmentFavorite();
            case 4:
                return new FragmentProfile();
        }
        return null;
    }

    @Override
    public int getCount() {
        return pager_number;
    }


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
    switch (menuItem.getItemId()) {

        case R.id.search:
            Intent intent = new Intent(getApplicationContext(), ActivitySearch.class);
            startActivity(intent);
            return true;

        default:
            return super.onOptionsItemSelected(menuItem);
    }
}

@Override
public void onBackPressed() {
    if (viewPager.getCurrentItem() != 0) {
        viewPager.setCurrentItem((0), true);
    } else {
        exitApp();
    }
}

public void exitApp() {
    if ((System.currentTimeMillis() - exitTime) > 2000) {
        Toast.makeText(this, getString(R.string.press_again_to_exit), Toast.LENGTH_SHORT).show();
        exitTime = System.currentTimeMillis();
    } else {
        finish();
    }
}

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

private int getIndex(Spinner spinner, String myString){

    int index = 0;

    for (int i=0;i < spinner.getCount(); i++) {
        if (spinner.getItemAtPosition(i).equals(myString)) {
            index = i;
        }
    }
    return index;
}

private void loadSpinnerData(String url) {
    RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            //TODO DONE
            String name = prefManager.spinReadString();

            try{
                JSONObject jsonObject=new JSONObject(response);

                if(jsonObject.getString("status").equals("ok")){
                    JSONArray jsonArray=jsonObject.getJSONArray("constituencies");

                    for(int i = 0; i < jsonArray.length(); i++){
                        JSONObject jsonObject1=jsonArray.getJSONObject(i);
                        String spinConstituency=jsonObject1.getString("constituency_name");
                        //TODO DONE
                        if (spinConstituency.equals(name))
                            spinConstID = jsonObject1.getInt("const_id");
                            spinnerConstituencyName.add(spinConstituency);
                    }
                    //TODO DONE
                    prefManager.writeString("" + spinConstID);
                }

                ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(MainActivity.this,
                        R.layout.custom_spinner_item, spinnerConstituencyName){
                    @Override
                    public View getDropDownView(int position, View convertView,
                                                ViewGroup parent) {
                        View view = super.getDropDownView(position, convertView, parent);
                        TextView tv = (TextView) view;
                        if(position % 2 == 1) {
                            // Set the item background color
                            tv.setBackgroundColor(Color.parseColor("#910D3F"));
                        }
                        else {
                            // Set the alternate item background color
                            tv.setBackgroundColor(Color.parseColor("#41061C"));
                        }
                        return view;
                    }
                };

                mySpinner.setPrompt("Select Your Constituency");
                myAdapter.setDropDownViewResource(R.layout.custom_spinner_item);
                mySpinner.setAdapter(myAdapter);

                //RECEIVE DATA VIA INTENT
                mySpinner.setSelection(getIndex(mySpinner, name));

            }catch (JSONException e){e.printStackTrace();}
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });


    int socketTimeout = 30000;
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    stringRequest.setRetryPolicy(policy);
    requestQueue.add(stringRequest);
}

}

1 个答案:

答案 0 :(得分:0)

我发现从API级别3开始,可以在具有布尔值的Activity上使用onUserInteraction(),从而确定用户的互动。

在下面的链接中找到文档。

http://developer.android.com/reference/android/app/Activity.html#onUserInteraction()

@Override
public void onUserInteraction() {
     super.onUserInteraction();
     userInteracts = true;
}

我的调整也是如此,在MainActivity.java

mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        int check = 0;
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            if (IsInteracting) {
                Intent intent = getIntent(); //MainActivity
                String itemSelected = mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()).toString();

                //TODO: DONE
                prefManager.spinWriteString(itemSelected);
                Toast.makeText(getApplicationContext(), "Constituency News Now Showing", Toast.LENGTH_SHORT).show();
                startActivity(intent);
                finish();
            }
        }