我是Android的新手,从昨天开始面对这个问题。在查看列表项的详细信息后按后退按钮时,我的列表项会重复。我正在使用片段列表。此外,我正在以JSON格式从api加载数据。
下面是我的ListFragment代码,我把它命名为BlankFragment
package com.equity99.equity99.learningrestjsonwithlistfragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import com.equity99.equity99.learningrestjsonwithlistfragment.Download_data.download_complete;
/**
* A simple {@link Fragment} subclass.
*/
public class BlankFragment extends Fragment implements download_complete{
public ListView list;
public ArrayList<SinglePost> countries = new ArrayList<SinglePost>();
public ListAdapter adapter;
private OnListFragmentInteractionListener mListener;
public BlankFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
if (rootView instanceof View) {
list = (ListView) rootView.findViewById(R.id.list);
adapter = new ListAdapter(this, this.countries, mListener);
list.setAdapter(adapter);
Download_data download_data = new Download_data((Download_data.download_complete) this);
download_data.download_data_from_link("http://www.websitesdemo.net/Equity99_app_wp/wp-json/wp/v2/posts");
}
return rootView;
}
public void get_data(String data)
{
try {
JSONArray data_array=new JSONArray(data);
for (int i = 0 ; i < data_array.length() ; i++)
{
JSONObject obj=new JSONObject(data_array.get(i).toString());
SinglePost add=new SinglePost();
JSONObject titleObject = obj.getJSONObject("title");
add.slug = titleObject.getString("rendered");
add.id = obj.getString("id");
countries.add(add);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
//countries = new ArrayList<SinglePost>();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString() + " must implement OnListFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
// TODO: Update argument type and name
void onListFragmentInteraction(SinglePost item);
}
}
这是我的DetailsFragment代码:
package com.equity99.equity99.learningrestjsonwithlistfragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
*/
public class DetailsFragment extends Fragment {
public DetailsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_details, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.full_item_detailss);
Bundle bundle = this.getArguments();
String itemDetails = bundle.getString("slug");
textView.setText(itemDetails);
return rootView;
}
}
这是我的ListAdapter:
package com.equity99.equity99.learningrestjsonwithlistfragment;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import com.equity99.equity99.learningrestjsonwithlistfragment.BlankFragment.OnListFragmentInteractionListener;
public class ListAdapter extends BaseAdapter {
Fragment main;
private ArrayList<SinglePost> countries = null;
private final OnListFragmentInteractionListener mListener;
ViewHolderItem holder = null;
public ListAdapter(Fragment m, ArrayList<SinglePost> countriesRecieved, OnListFragmentInteractionListener listener)
{
main = m;
countries = countriesRecieved;
mListener = listener;
}
@Override
public int getCount() {
return countries.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
public class ViewHolderItem {
public TextView slug;
public TextView id;
public SinglePost singlePost;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
Log.d("bbbbbbbbbbbbb","bbbbbbbbbbbbb");
if (convertView == null) {
holder = new ViewHolderItem();
holder.singlePost = countries.get(position);
LayoutInflater inflater = (LayoutInflater) main.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cell, null);
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null != mListener) {
mListener.onListFragmentInteraction(holder.singlePost);
}
}
});
holder.slug = (TextView) convertView.findViewById(R.id.slug);
holder.id = (TextView) convertView.findViewById(R.id.id);
holder.singlePost = countries.get(position);
convertView.setTag(holder);
}
else
{
holder = (ViewHolderItem) convertView.getTag();
}
holder.slug.setText(countries.get(position).slug);
holder.id.setText(countries.get(position).id);
holder.singlePost = countries.get(position);
return convertView;
}
}
MainActivity代码:
package com.equity99.equity99.learningrestjsonwithlistfragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity implements BlankFragment.OnListFragmentInteractionListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BlankFragment updates = new BlankFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.main_container, updates).commit();
}
public void onListFragmentInteraction(SinglePost item) {
DetailsFragment detailsFragment = new DetailsFragment();
Bundle bundle = new Bundle();
bundle.putString("itemDetails", item.slug);
Log.d("Rakkkjjj", item.slug);
detailsFragment.setArguments(bundle);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, detailsFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
Download_data class:
package com.equity99.equity99.learningrestjsonwithlistfragment;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
public class Download_data implements Runnable {
public download_complete caller;
public interface download_complete
{
public void get_data(String data);
}
Download_data(download_complete caller) {
this.caller = caller;
}
private String link;
public void download_data_from_link(String link)
{
this.link = link;
Thread t = new Thread(this);
t.start();
}
public void run() {
// caller.get_data(download(this.link));
threadMsg(download(this.link));
}
private void threadMsg(String msg) {
if (!msg.equals(null) && !msg.equals("")) {
Message msgObj = handler.obtainMessage();
Bundle b = new Bundle();
b.putString("message", msg);
msgObj.setData(b);
handler.sendMessage(msgObj);
}
}
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
String Response = msg.getData().getString("message");
caller.get_data(Response);
}
};
public static String download(String url) {
URL website;
StringBuilder response = null;
try {
website = new URL(url);
HttpURLConnection connection = (HttpURLConnection) website.openConnection();
connection.setRequestProperty("charset", "utf-8");
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
} catch (Exception e) {
return "";
}
return response.toString();
}
}
最后是SinglePost类:
package com.equity99.equity99.learningrestjsonwithlistfragment;
public class SinglePost {
String slug;
String id;
}
请问我从昨天起就被困在这里,无法想到其他任何事情。试过很多解决方案但是因为我是新手,我无法让它发挥作用。谢谢你的帮助!
答案 0 :(得分:0)
发布此问题后,我在一小时内找到了解决方案。问题出在file:BlankFragment上 在这个方法里面:
public void get_data(String data)
我需要清除变量国家/地区以前的JSON数据。因此,当我恢复片段时,它以明确的数据开始。我试图通过添加以下内容来清除变量:
countries = null;
不知道我在想什么,它完全取消变量而不是清除变量,以清除我使用的数据
countries .clear();
它有效!