TextView没有保留我给它的值

时间:2016-06-23 09:38:21

标签: java android json android-fragments view

在我的应用中,我从php脚本中获取JSON数据。当我获取数据时,我的Fragment中有一个onClick()方法,它将TextView更改为已解析的JSON。

但是,当我滑动到另一个片段(它是一个滑动/标签式活动)时,TextView不会保留我给它的值,它会更改为原始值。

我希望它保留价值。

MainActivity.java(我不认为这很重要)

package me.anshsehgal.lunchmenu;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;

import android.app.FragmentManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {
    String JSON_STRING;
    Toolbar toolbar;
    TabLayout tabLayout;
    ViewPager viewPager;
    ViewPagerAdapter viewPagerAdapter;  //make all the variables

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

        toolbar = (Toolbar)findViewById(R.id.toolBar);
        setSupportActionBar(toolbar);
        tabLayout = (TabLayout)findViewById(R.id.tabLayout);
        viewPager = (ViewPager)findViewById(R.id.viewPager); //reference them
        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPagerAdapter.addFragments(new HomeFragment(),"Mon");
        viewPagerAdapter.addFragments(new MondayFragment(),"Tue");
        viewPagerAdapter.addFragments(new TuesdayFragment(),"Wed");
        viewPagerAdapter.addFragments(new WednesdayFragment(), "Thu");
        viewPagerAdapter.addFragments(new ThursdayFragment(), "Fri");   //adding fragments to view page adapter


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

        HomeFragment frag = (HomeFragment)getSupportFragmentManager().findFragmentById(R.id.homeFragment);

    }

HomeFragment.java(这是出错的地方)

package me.anshsehgal.lunchmenu;


import android.os.AsyncTask;
import android.os.Bundle;
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.Button;
import android.widget.TextView;
import android.widget.RelativeLayout;
import android.widget.Toast;

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

import java.lang.Void;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment implements View.OnClickListener {
    String JSON_STRING;
    String  jsonData;
    TextView txt;
    String day;
    String soup;
    String non_veg_main;
    String non_veg_side;
    String veg_main;
    String veg_side;
    String MondayMenu;
    public HomeFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        txt = (TextView) view.findViewById(R.id.textJSON);
        Button btn = (Button) view.findViewById(R.id.buttonGetJSON);
        btn.setOnClickListener(this);
        new BackgroundTask().execute();


        return view;

    }

    @Override
    public void onClick(View v) {
        MainActivity activity = (MainActivity) getActivity();


        try{
            //JSON parsing
            JSONObject parentObject = new JSONObject(jsonData);
            JSONArray parentArray = parentObject.getJSONArray("server_response");
            JSONObject finalObject = parentArray.getJSONObject(0);

            //JSON data assigning to variables
             day = finalObject.getString("day");
             soup = finalObject.getString("soup");
             non_veg_main = finalObject.getString("non_veg_main");
            non_veg_side = finalObject.getString("non_veg_side");
            veg_main = finalObject.getString("veg_main");
            veg_side = finalObject.getString("veg_side");

        }catch (JSONException e){
            e.printStackTrace();
        }

        MondayMenu = "Soup: "+soup+"\n"+"Non Veg Main: "+non_veg_main+"\n"+"Non Veg Side: "+non_veg_side+"\n"+"Veg Main: "+veg_main+"\n"+"Veg Side: "+veg_side;
        txt.setText(MondayMenu);
    }

    class BackgroundTask extends AsyncTask<Void,Void,String>{


            String json_url;
            @Override
            protected void onPreExecute() {
                json_url="http://192.168.0.12/json_get_data.php";
            }

            @Override
            protected String doInBackground(Void... params) {
                try {
                    URL url = new URL(json_url);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    InputStream inputStream = httpURLConnection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    StringBuilder stringBuilder = new StringBuilder();
                    while ((JSON_STRING = bufferedReader.readLine()) != null) {
                        stringBuilder.append(JSON_STRING + "\n");
                    }
                    bufferedReader.close();
                    inputStream.close();
                    httpURLConnection.disconnect();
                    return stringBuilder.toString().trim();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onProgressUpdate(Void... values) {
                super.onProgressUpdate(values);
            }

            @Override
            protected void onPostExecute(String result) {

                 jsonData = result;

            }
        }
    }

2 个答案:

答案 0 :(得分:0)

这是因为每次从一个页面切换到另一个页面时都会调用getView。因此正在重新创建TextView。使用该文本创建一个ViewHolder,将其设置在ViewHolder类的创建者上,这样当您重新绘制片段时,您将不会丢失该值。 Official viewHolder tutorial

答案 1 :(得分:0)

由于您只想在不同选项卡之间切换时保持片段的状态,您可以按照以下实现进行操作:

TextView vstup;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.whatever);
    vstup = (TextView)findViewById(R.id.whatever);
    /* (...) */
}

@Override
public void onSaveInstanceState(Bundle state) {
    super.onSaveInstanceState(state);
    state.putCharSequence(App.VSTUP, vstup.getText());
}

@Override
public void onRestoreInstanceState(Bundle state) {
    super.onRestoreInstanceState(state);
    vstup.setText(state.getCharSequence(App.VSTUP));
}

希望这可以解决您的问题。