我正在尝试通过他们共享的活动将文章对象从一个片段传递到另一个片段。到目前为止,对象正在被传递,但只要选择保存ArticlesFragment列表视图中的多个项目,CollectionsFragment就不会附加到ArrayList,只是覆盖它。只留下一篇文章显示在该片段中。
ArticlesFragment.java
package fragments;
/* Imports */
public class ArticlesFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
private final String urlString = "https://newsapi.org/v1/articles?source=reuters&sortBy=top&apiKey=4b240d3be86c4f69856af11e51432cbc";
private final String progressMsg = "Loading in articles...";
private SwipeRefreshLayout swipe;
private List<Article> articleList;
private ListView lvArticles;
private ArticleAdapter adapter;
private ProgressDialog progressDialog;
public ArticlesFragment() {
}
public static ArticlesFragment newInstance() {
ArticlesFragment fragment = new ArticlesFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new JSONTask().execute(urlString);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_articles, container, false);
swipe = (SwipeRefreshLayout) view.findViewById(R.id.swipeContainer);
swipe.setOnRefreshListener(this);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getContext()).build();
ImageLoader.getInstance().init(config);
return view;
}
@Override
public void onRefresh() {
new JSONTask().execute(urlString);
swipe.setRefreshing(false);
}
public class JSONTask extends AsyncTask<String, String, List<Article>> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getContext());
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.setMessage(progressMsg);
progressDialog.show();
}
@Override
protected List<Article> doInBackground(String... params) {
HttpsURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpsURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parent = new JSONObject(finalJson);
JSONArray parentArray = parent.getJSONArray("articles");
articleList = new ArrayList<>();
Gson gson = new Gson();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
Article article = gson.fromJson(finalObject.toString(), Article.class);
articleList.add(article);
}
return articleList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(List<Article> s) {
super.onPostExecute(s);
progressDialog.dismiss();
adapter = new ArticleAdapter(getContext(), R.layout.row, s);
lvArticles = (ListView) getActivity().findViewById(R.id.lvArticles);
lvArticles.setAdapter(adapter);
lvArticles.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Article item = articleList.get(position);
Intent intent1 = new Intent(getContext(), WebViewActivity.class);
intent1.putExtra("URL", item.getUrl());
getContext().startActivity(intent1);
}
});
lvArticles.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Implement article saves.
Article item = articleList.get(position);
createDialog(view, item);
return true;
}
});
}
private void createDialog(View view, final Article item) {
final Dialog d = new Dialog(getContext());
d.setContentView(R.layout.dialog);
d.setTitle("Add article?");
d.setCancelable(true);
Button b = (Button) d.findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getContext(), MainActivity.class);
intent.putExtra("Article", item);
getContext().startActivity(intent);
Toast.makeText(getContext(), "YES", Toast.LENGTH_SHORT).show();
}
});
d.show();
}
}
}
MainActivity.java
package com.fyp.chowdud.dynamo;
/* Imports */
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (savedInstanceState == null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, new ArticlesFragment())
.commit();
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
if (id == R.id.nav_home) {
fragment = new ArticlesFragment();
} else {
fragment = new CollectionsFragment();
passData(fragment);
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void passData(Fragment fragment) {
Intent intent = getIntent();
Article aitem = (Article) intent.getSerializableExtra("Article");
Bundle bundle = new Bundle();
bundle.putSerializable("Article", aitem);
fragment.setArguments(bundle);
}
}
CollectionsFragment.java
package fragments;
/* Imports */
public class CollectionsFragment extends Fragment {
private List<Article> articleList;
private ListView lvArticles;
private ArticleAdapter adapter;
Article v = null;
public CollectionsFragment() {
}
public static CollectionsFragment newInstance() {
Bundle args = new Bundle();
CollectionsFragment fragment = new CollectionsFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_collections, container, false);
if (articleList == null) {
new MyTask().execute();
}
return view;
}
private class MyTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... strings) {
Bundle bundle = getArguments();
v = (Article) bundle.getSerializable("Article");
articleList = new ArrayList<>();
articleList.add(v);
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
lvArticles = (ListView) getActivity().findViewById(R.id.lvArticles);
adapter = new ArticleAdapter(getContext(), R.layout.row, articleList);
lvArticles.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}