如何在Async Task类完成后更改textview(片段中)的值?

时间:2016-09-30 21:08:46

标签: android android-fragments android-intent android-asynctask

我是Android编程的初学者,这是我迄今为止最大的项目。请尝试在你的答案中非常具体,因为这对我来说都是新的。 我想要做的是在OneFragment中的textview中显示天气(描述)的值。

这是MainActivity

package com.example.dell.myop;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;


import android.os.Bundle;
import android.support.design.widget.TabLayout;
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 com.example.dell.myop.R;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


import com.example.dell.myop.fragments.OneFragment;

import com.example.dell.myop.fragments.ThreeFragment;
import com.example.dell.myop.fragments.TwoFragment;

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    String description;

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

        DownloadTask task = new DownloadTask();
        task.execute("http://api.openweathermap.org/data/2.5/weather?q=hamirpur,india&appid=41352ca35dd1be72cc7d9f47351d1b41");

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new OneFragment(), "Today");
        adapter.addFragment(new TwoFragment(), "Tomorrow");
        adapter.addFragment(new ThreeFragment(), "Day After");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

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

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

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

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

DownloadTask

package com.example.dell.myop;

import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

import com.example.dell.myop.fragments.OneFragment;

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

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

import static android.support.v4.app.ActivityCompat.startActivity;

public class DownloadTask extends AsyncTask<String,Void,String> {

    @Override
    protected String doInBackground(String... urls) {

        String result = "";
        URL url;
        HttpURLConnection urlConnection= null;

        try {
            url = new URL(urls[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = urlConnection.getInputStream();
            InputStreamReader reader = new InputStreamReader(in);
            int data = reader.read();
            while(data!=-1){
                char current = (char)data;
                result += current;
                data = reader.read();
            }
            return  result;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }    

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        try {
            JSONObject jObject = new JSONObject(result);
            JSONArray jArray = jObject.getJSONArray("weather");
            for (int i=0; i < jArray.length(); i++)
            {
                try {
                    JSONObject oneObject = jArray.getJSONObject(i);
                    // Pulling items from the array
                    String main = oneObject.getString("main");
                    String description = oneObject.getString("description");
                    Log.i("main",main);
                    Log.i("description",description);

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

这是OneFragment

package com.example.dell.myop.fragments;

/**
 * Created by Dell on 13-09-2016.
 */
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;

import com.example.dell.myop.DownloadTask;
import com.example.dell.myop.MainActivity;
import com.example.dell.myop.R;

import com.example.dell.myop.R;


public class OneFragment extends Fragment{

    public OneFragment() {

    }

    @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_one, container, false);
        TextView textView = (TextView) view.findViewById(R.id.textView);

        textView.setText(description);
        return view;
    }    
}

2 个答案:

答案 0 :(得分:1)

我建议你在你的frargment中移动downloadTask的逻辑,如果你只是在这个中使用它。 这将非常容易,只需获得描述并设置:

textView.setText(description); in your fragment,

如果您想在活动的其他组件上使用此downloadTask,则必须在您的活动上实现一些CallBack,并在任何片段上使用它们来更新UI。 所以,在你的Activity中你要声明一些接口

 interface OnDownloadTaskFinish {
 onFinish(String description);
 }

中使用它
 onPostExecute(...){
 //...some logic here 
 getFragment..... .onFinish(description);
} 
在你的片段中你应该实现这个界面和

 void onFinish(String description){
 textView.setText(description);
 }

答案 1 :(得分:0)

1)在interfaceDownloadTasksetter

中创建notification code
private Listener listener;

public void setListener(Listener listener){
    this.listener = listener;
}

public interface Listener{
    onCompleted(String description);
}

@Override
protected void onPostExecute(String result) {
    // Your Current Code

    if(listener != null) listener.onCompleted(description);
}

2)在OneFragment

中实施此界面
public class OneFragment extends Fragment implements DownloadTask.Listener{

     private TextView textView;

     @Override
     onCompleted(String description){
         if(description != null && textView !=null)
             textView.setDescription(description);
     }

     // Other code
}

3)创建global referenceOneFragment并将Listener设为DownloadTask {/ 1}}

MainActivity

4)将private OneFragment oneFragment = new OneFragment(); 替换为adapter.addFragment(new OneFragment(), "Today");

5)将Listener设置为

adapter.addFragment(oneFragment, "Today");

6)DownloadTask task = new DownloadTask(); task.setListener(oneFragment); task.execute("http://api.openweathermap.org/data/2.5/weather?q=hamirpur,india&appid=41352ca35dd1be72cc7d9f47351d1b41");

之后的execute DowloadTask会更好