JSON数据输出不更新片段视图

时间:2018-10-03 20:11:00

标签: java android android-recyclerview

目前,我正在尝试解决问题。当我打开我的应用程序时,它必须显示JSON输出数据,但是JSON需要1-2秒来完成加载,在此之后,仍然不会更新片段视图。

我尝试过的方法:
1 -使用notifyDataSetChanged()
2 -在真实的移动设备上测试应用
3 -在创建此线程之前要进行大量搜索。

此刻没有任何帮助。

MainActivity.java

package etes.xdda.music;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

    private DrawerLayout nDrawerLayout;
    private ActionBarDrawerToggle mToggle;
    private Handler mHandler = new Handler();
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private viewPagerAdapter adapter;
    public LinearLayout menu_dialog;
    public LinearLayout menu_dialog2;
    public TextView song_detail;
    public TextView time1;
    public TextView time2;
    private String player_status = "playing";
    private ImageButton player_img;

    public static SeekBar seekBar;

    public static MediaPlayer mediaPlayer;

    @SuppressLint("RestrictedApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        nDrawerLayout = findViewById(R.id.drawer);

        menu_dialog = findViewById(R.id.menu_dialog);
        menu_dialog.setVisibility(View.GONE);

        menu_dialog2 = findViewById(R.id.menu_dialog2);
        menu_dialog2.setVisibility(View.GONE);

        song_detail = findViewById(R.id.song_detail);
        song_detail.setVisibility(View.GONE);

        time1 = findViewById(R.id.time_1);
        time2 = findViewById(R.id.time_2);

        seekBar = findViewById(R.id.seekBar);

        mToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close);
        nDrawerLayout.addDrawerListener(mToggle);
        getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        tabLayout = findViewById(R.id.tablayout_id);
        viewPager = findViewById(R.id.viewpager_id);
        //viewPager.setLayoutParams(new ViewPager.LayoutParams(0, 0));
        //setMarginBottom(viewPager, 0);
        setMargins(viewPager, 0, 0, 0, 0);

        adapter = new viewPagerAdapter(getSupportFragmentManager());

        //Add fragments here
        adapter.addFragment(new fragmentList(), ""); //Lista de música
        adapter.addFragment(new fragmentFrequent(), ""); //Frequentes
        adapter.addFragment(new fragmentPlayList(), ""); //Playlist

        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);


        tabLayout.getTabAt(0).setIcon(R.drawable.ic_music_note_black_24dp); //Lista de música
        tabLayout.getTabAt(1).setIcon(R.drawable.ic_filter_list_black_24dp); // Frequentes
        tabLayout.getTabAt(2).setIcon(R.drawable.ic_queue_music_black_24dp); // Playlist

        final Runnable mRunnable = new Runnable() {
            @Override
            public void run() {
                if (mediaPlayer != null) {
                    int CurrentPosition = mediaPlayer.getCurrentPosition();
                    int Duration = mediaPlayer.getDuration();

                    int progress = (getProgressPercentage(CurrentPosition, Duration));
                    seekBar.setProgress(progress);

                    String m_1;
                    String s_1;
                    //Toast.makeText(getApplicationContext(), "Current: " + CurrentPosition + " - Duration: " + mediaPlayer.getDuration(), Toast.LENGTH_LONG).show();

                    final int minutes_1 = (CurrentPosition / 1000) / 60;
                    final int seconds_1 = ((CurrentPosition / 1000) % 60);

                    if (minutes_1 < 10) {
                        m_1 = "0" + minutes_1;
                    } else {
                        m_1 = "" + minutes_1;
                    }

                    if (seconds_1 < 10) {
                        s_1 = "0" + seconds_1;
                    } else {
                        s_1 = "" + seconds_1;
                    }
                    time1.setText(m_1 + ":" + s_1);


                    String m_2;
                    String s_2;
                    final int minutes_2 = (Duration / 1000) / 60;
                    final int seconds_2 = ((Duration / 1000) % 60);

                    if (minutes_2 < 10) {
                        m_2 = "0" + minutes_2;
                    } else {
                        m_2 = "" + minutes_2;
                    }

                    if (seconds_2 < 10) {
                        s_2 = "0" + seconds_2;
                    } else {
                        s_2 = "" + seconds_2;
                    }

                    time2.setText(m_2 + ":" + s_2);

                }
                mHandler.postDelayed(this, 1000);
            }
        };
        mRunnable.run();

        player_img = findViewById(R.id.playorpause);
        player_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //setMargins(viewPager, 0,0,0,110);
                if (player_status == "playing") {
                    player_img.setImageResource(R.drawable.ic_play_arrow_black_24dp);
                    pauseAudio();
                    mHandler.removeCallbacks(mRunnable);// essencial para economizar bateria;
                    player_status = "paused";
                } else {
                    player_img.setImageResource(R.drawable.ic_pause_black_24dp);
                    startAudio();
                    mHandler.postDelayed(mRunnable, 1000); // essencial para economizar bateria;
                    player_status = "playing";
                }
            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (mediaPlayer != null && fromUser) {

                    //int _progress = (getProgressPercentage(progress*10000, mediaPlayer.getDuration()));
                    //Toast.makeText(getApplicationContext(), String.valueOf(_progress), Toast.LENGTH_LONG).show();
                    //mediaPlayer.seekTo(progress);

                    int _progress = (progress * mediaPlayer.getDuration())/100;
                    mediaPlayer.seekTo(_progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        registerReceiver(broadcastReceiver, new IntentFilter("my-permission-response-action"));
        registerReceiver(broadcastReceiver2, new IntentFilter("my-permission-response-quit"));

       }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
            killMediaPlayer();
        }
    };
    BroadcastReceiver broadcastReceiver2 = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            killMediaPlayer();
            Toast.makeText(context, "OK2", Toast.LENGTH_LONG).show();
        }
    };

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mToggle.syncState();
    }

    public static void setMargins (View v, int l, int t, int r, int b) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(l, t, r, b);
            v.requestLayout();
        }
    }

    public void initAudio(final Context context, String url) {
        if (mediaPlayer == null) {
            try {
                url = url.replace(" ", "%20");
                mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
            }
            catch (Exception e) {
                Toast.makeText(context, "Falha ao iniciar o áudio", Toast.LENGTH_LONG).show();
                killMediaPlayer();
            }
        }
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                killMediaPlayer();
                updateLayout();
                clearNotificationBar();
            }
        });
        seekBar.setMax(100);
        mediaPlayer.start();
    }

    public void updateNotificationBar(String title, String author) {
        NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

        if (notificationManager != null) {
            Notification.MediaStyle style = new Notification.MediaStyle();

            Bitmap notificationLargeIconBitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_play_circle_filled_black_24dp);

            Intent intent = new Intent(this, ActionReceiver.class);
            intent.putExtra("action","action1");

            Intent intent2 = new Intent(this, updateNotificationReceiver.class);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            PendingIntent pendingIntent2 = PendingIntent.getBroadcast(this, 1, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
            Notification.Builder builder = new Notification.Builder(this)
                    .setVisibility(Notification.VISIBILITY_PUBLIC)
                    .setSmallIcon(R.drawable.ic_play_circle_outline_black_40dp)
                    .setLargeIcon(notificationLargeIconBitmap)
                    .setContentTitle(title)
                    .setContentText(author)
                    .setContentIntent(pendingIntent)
                    .setDeleteIntent(pendingIntent2)
                    .setColor(this.getResources().getColor(R.color.colorPrimary))
                    .setPriority(Notification.PRIORITY_MAX)
                    //.setOngoing(true) // n vai fechar a notificação
                    .addAction(R.drawable.ic_skip_previous_black_24dp, "Prev", pendingIntent)
                    .addAction(R.drawable.ic_pause_black_24dp, "PlayOrPause", pendingIntent)
                    .addAction(R.drawable.ic_skip_next_black_24dp, "Next", pendingIntent)

                    .setStyle(style);
            notificationManager.notify(0, builder.build());
        }
    }

    public void killMediaPlayer() {
        if (mediaPlayer != null) {
            try {
                mediaPlayer.reset();
                mediaPlayer.release();
                mediaPlayer = null;
                clearNotificationBar();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public int getProgressPercentage(long currentDuration, long totalDuration){
        Double percentage = (double) 0;

        long currentSeconds = (int) (currentDuration / 100);
        long totalSeconds = (int) (totalDuration / 100);

        // calculando porcentagem
        percentage =(((double)currentSeconds)/totalSeconds)*100;

        // retornando porcentagem
        return percentage.intValue();
    }

    private void updateLayout() {
        try {
            menu_dialog.setVisibility(View.GONE);
            menu_dialog2.setVisibility(View.GONE);
            song_detail.setVisibility(View.GONE);
            setMargins(viewPager.findViewById(R.id.viewpager_id), 0,0,0,0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void pauseAudio() {
        if (!(mediaPlayer == null)) {
            mediaPlayer.pause();
        }
    }
    public static void startAudio() {
        if (!(mediaPlayer == null)) {
            mediaPlayer.start();
        }
    }

    public void clearNotificationBar() {
        NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(0);
    }

}

fragmentList.java

package etes.xdda.music;

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;

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

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

public class fragmentList extends Fragment {

    View v;
    private RecyclerView myrecyclerview;
    private List<mList> lstContact;

    private String URL_JSON = "http://ntcdn.stream/audio/";
    private JsonArrayRequest ArrayRequest;
    private RequestQueue requestQueue ;

    public fragmentList() {
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.list_fragment,container,false);
        myrecyclerview = v.findViewById(R.id.list_recyclerview);
        RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter((MainActivity)getActivity(), lstContact);
        myrecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        myrecyclerview.setAdapter(recyclerViewAdapter);
        return v;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstaceState) {
        super.onCreate(savedInstaceState);
        _JSONcall();
    }


    public void _JSONcall() {

        lstContact = new ArrayList<>();
        ArrayRequest = new JsonArrayRequest(URL_JSON, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {

                JSONObject jsonObject = null;

                for (int i = 0 ; i<response.length();i++) {
                    try {

                        jsonObject = response.getJSONObject(i);

                        lstContact.add(new mList(jsonObject.getString("name"), jsonObject.getString("description"), jsonObject.getString("link"), R.drawable.ic_play_circle_filled_black_24dp));
                    }
                    catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(getActivity(), "Error 1!",
                                Toast.LENGTH_LONG).show();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getActivity(), "Error 3!",
                        Toast.LENGTH_LONG).show();
            }
        });

        requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
        requestQueue.add(ArrayRequest);
    }
}

viewPagerAdapter.java

package etes.xdda.music;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

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

public class viewPagerAdapter extends FragmentPagerAdapter {

    private final List<Fragment> lstFragment = new ArrayList<>();
    private final List<String> lstTitles = new ArrayList<>();


    public viewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return lstFragment.get(position);
    }

    @Override
    public int getCount() {
        return lstTitles.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return lstTitles.get(position);
    }

    public void addFragment(Fragment fragment, String title) {
        lstFragment.add(fragment);
        lstTitles.add(title);
    }

}

你能帮我吗?我真的不知道该怎么办才能解决此问题,并让系统在JSON完成加载后更新视图

2 个答案:

答案 0 :(得分:1)

解决方案:

请遵循以下步骤:

第1步:

进行以下操作:将RecyclerViewAdapter recyclerViewAdapter作为全局对象,以便您可以在整个Fragment中访问它。

第二步:

添加以下行:recyclerviewadapter.notifyDataSetChanged()方法中的for循环之后的onResponse()

尝试一下,希望它能工作。

答案 1 :(得分:0)

尝试在声明了它的片段中初始化数组列表

private List<mList> listContact= new ArrayList<>();

并在您的片段中尝试notifyDataSetChanged();

在片段中创建适配器的实例,然后 检查您的适配器是否为null

if(adapter != null){    
  adapter.notifyDataSetChanged();
} else {
  adapter = new Adapter(getContext, listContact);
  recyclerView.setAdapter(adapter);
}