Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/205.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 以片段形式读取_Android_Android Fragments_Android Activity - Fatal编程技术网

Android 以片段形式读取

Android 以片段形式读取,android,android-fragments,android-activity,Android,Android Fragments,Android Activity,我正在尝试将一个活动转换为片段。runOnUiThread上的错误标记。 关于过去: GoogleActivityV2从Activity扩展而来。在课堂上读书 执行任务。类ExecuteTask嵌套在活动上 (正常运行) 现在: GoogleActivityV2从片段扩展而来。在课堂上读书 执行任务。类ExecuteTask嵌套在活动上。(上的错误) runOnUiThread) 这是我的密码 public class GoogleActivityV2 extends SherlockMapFr

我正在尝试将一个活动转换为片段。
runOnUiThread
上的错误标记。 关于过去:

GoogleActivityV2从Activity扩展而来。在课堂上读书 执行任务。类ExecuteTask嵌套在活动上

(正常运行) 现在:

GoogleActivityV2从片段扩展而来。在课堂上读书 执行任务。类ExecuteTask嵌套在活动上。(上的错误) runOnUiThread)

这是我的密码

public class GoogleActivityV2 extends SherlockMapFragment implements OnMapClickListener , OnMapLongClickListener , OnCameraChangeListener , TextWatcher {


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View rootView = inflater.inflate(R.layout.activity_googlev2, container, false);
        Init();
        adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_dropdown_item_1line);
        textView = (AutoCompleteTextView) getView().findViewById(R.id.autoCompleteTextView1);
        return rootView;
    }

    public void onCameraChange(CameraPosition arg0){
        // TODO Auto-generated method stub
    }

    public void onMapLongClick(LatLng arg0){
        llLoc = arg0;
        stCommand = "onTouchEvent";
        lp = new ExecuteTask();
        lp.execute();
    }

    public void onMapClick(LatLng arg0){
        // TODO Auto-generated method stub
    }

    class ExecuteTask extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute(){
            super.onPreExecute();
            if(stCommand.compareTo("AutoCompleteTextView") != 0) {
                pDialog = new ProgressDialog(getActivity());
                pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading ..."));
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(false);
                pDialog.show();
            }
        }

        protected String doInBackground(String ... args){
            do something
            return null;
        }

        @Override
        protected void onPostExecute(String file_url){
            if(stCommand.compareTo("AutoCompleteTextView") != 0) pDialog.dismiss();
            runOnUiThread(new Runnable() {
                public void run(){
                    do something
                }
            });
        }
    }
    public void afterTextChanged(Editable s){
        // TODO Auto-generated method stub
    }

    public void beforeTextChanged(CharSequence s, int start, int count, int after){
        // TODO Auto-generated method stub
    }

    public void onTextChanged(CharSequence s, int start, int before, int count){
        // TODO Auto-generated method stub
    }
}
public类GoogleActivityV2扩展了SherlockMapFragment实现了OnMapClickListener、OnMapLongClickListener、OnCameraChangeListener、TextWatcher{
@凌驾
CreateView上的公共视图(布局、充气机、视图组容器、捆绑包保存状态){
视图根视图=充气机。充气(R.layout.activity\u googlev2,容器,false);
Init();
adapter=newarrayadapter(getActivity(),android.R.layout.simple\u下拉列表\u item\u 1line);
textView=(AutoCompleteTextView)getView().findViewById(R.id.autoCompleteTextView1);
返回rootView;
}
CameraChange上的公共无效(CameraPosition arg0){
//TODO自动生成的方法存根
}
在MaplongClick(LatLng arg0)上的公共无效{
llLoc=arg0;
stCommand=“onTouchEvent”;
lp=新执行任务();
lp.execute();
}
点击时的公共无效(LatLng arg0){
//TODO自动生成的方法存根
}
类ExecuteTask扩展异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
if(stCommand.compareTo(“AutoCompleteTextView”)!=0){
pDialog=newprogressdialog(getActivity());
pDialog.setMessage(Html.fromHtml(“搜索
加载…”); pDialog.setUndeterminate(假); pDialog.setCancelable(假); pDialog.show(); } } 受保护的字符串doInBackground(字符串…args){ 做点什么 返回null; } @凌驾 受保护的void onPostExecute(字符串文件\u url){ 如果(stCommand.compareTo(“AutoCompleteTextView”)!=0)pDialog.discouse(); runOnUiThread(新的Runnable(){ 公开募捐{ 做点什么 } }); } } 公共无效后文本已更改(可编辑){ //TODO自动生成的方法存根 } 更改前文本之前的公共void(字符序列s、int start、int count、int after){ //TODO自动生成的方法存根 } public void onTextChanged(字符序列、int start、int before、int count){ //TODO自动生成的方法存根 } }
错误显示:


如何修复此错误?

尝试以下操作:
getActivity().runOnUiThread(新的可运行…

这是因为:

1) 调用
runOnUiThread
中的隐式
this
指的是异步任务,而不是片段

private Handler mHandler = new Handler(Looper.getMainLooper());
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View root = inflater.inflate(R.layout.fragment_head_screen, container, false);

    dateTextView =  root.findViewById(R.id.dateView);
    hourTv = root.findViewById(R.id.hourView);

        Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(1000);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            //Calendario para obtener fecha & hora
                            Date currentTime = Calendar.getInstance().getTime();
                            SimpleDateFormat date_sdf = new SimpleDateFormat("dd/MM/yyyy");
                            SimpleDateFormat hour_sdf = new SimpleDateFormat("HH:mm a");

                            String currentDate = date_sdf.format(currentTime);
                            String currentHour = hour_sdf.format(currentTime);

                            dateTextView.setText(currentDate);
                            hourTv.setText(currentHour);
                        }
                    });
                }
            } catch (InterruptedException e) {
                Log.v("InterruptedException", e.getMessage());
            }
        }
    };
}
(二)

请注意,
Activity
如果已经在主线程上,则只执行
Runnable
,否则它使用
处理程序。在你的片段中,如果你不想担心
这个
的上下文,其实很简单:

// A class instance
private Handler mHandler = new Handler(Looper.getMainLooper());

// anywhere else in your code
mHandler.post(<your runnable>);
// ^ this will always be run on the next run loop on the main thread.
//类实例
私有处理程序mHandler=新处理程序(Looper.getMainLooper());
//代码中的任何其他地方
mHandler.post();
//^这将始终在主线程的下一个运行循环中运行。
编辑:@rciovati是对的,你在
onPostExecute
,这已经在主线程上了。

在Xamarin.Android中

对于片段:

this.Activity.RunOnUiThread(() => { yourtextbox.Text="Hello"; });
关于活动:

RunOnUiThread(() => { yourtextbox.Text="Hello"; });

快乐编码:-)

我用它来获取片段中的日期和时间

private Handler mHandler = new Handler(Looper.getMainLooper());
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    View root = inflater.inflate(R.layout.fragment_head_screen, container, false);

    dateTextView =  root.findViewById(R.id.dateView);
    hourTv = root.findViewById(R.id.hourView);

        Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                while (!isInterrupted()) {
                    Thread.sleep(1000);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            //Calendario para obtener fecha & hora
                            Date currentTime = Calendar.getInstance().getTime();
                            SimpleDateFormat date_sdf = new SimpleDateFormat("dd/MM/yyyy");
                            SimpleDateFormat hour_sdf = new SimpleDateFormat("HH:mm a");

                            String currentDate = date_sdf.format(currentTime);
                            String currentHour = hour_sdf.format(currentTime);

                            dateTextView.setText(currentDate);
                            hourTv.setText(currentHour);
                        }
                    });
                }
            } catch (InterruptedException e) {
                Log.v("InterruptedException", e.getMessage());
            }
        }
    };
}

您还可以使用任何其他线程的视图发布runnable。但请确保视图不为空:

 tView.post(new Runnable() {
                    @Override
                    public void run() {
                        tView.setText("Success");
                    }
                });
根据文件:

“布尔post(可运行操作) 导致将Runnable添加到消息队列。Runnable将在用户界面线程上运行。“

使用Kotlin扩展函数 然后,在任何
Fragment
中,您可以调用
runOnUiThread
。这使调用在活动和片段之间保持一致

runOnUiThread {
    // Call your code here
}
注意:如果
片段
不再附加到
活动
,则不会调用回调,也不会引发异常

如果要从任何位置访问此样式,可以添加公共对象并导入方法:

object ThreadUtil {
    private val handler = Handler(Looper.getMainLooper())

    fun runOnUiThread(action: () -> Unit) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            handler.post(action)
        } else {
            action.invoke()
        }
    }
}

对于片段上的Kotlin,只需这样做

activity?.runOnUiThread(Runnable {
        //on main thread
    })

在onPostExecute中编写的代码已经在主线程中运行。另一方面,您不需要在PostExecute()中包含runUnuithRead()。@rciovati“do something”在PostExecute中的输入和输出是不同的。有时getActivity()。runUnuithRead会导致NullPointerException。你能解释一下吗?@developer1011当片段从活动中分离时会发生这种情况。这在异步任务中很常见,因为该活动可能在长时间运行的操作中被销毁,因此它不再存在于
get
中。总是先检查空值。谢谢。我用
if(isAdded())
包围了
getActivity()fine@bclymer如果这个答案是Google上对UI线程片段的实际引用,那么最后一节(如何实现完成相同任务的处理程序)中的更多细节就更好了!我绝对喜欢kotlin扩展函数。