分离文件中的AsyncTask和MainActivity

时间:2015-02-19 13:54:32

标签: java android android-asynctask

我试图通过将我们的AsyncTask类和MainActivity类放在其他文件中来分离它们。 这是我的全面工作计划:

package com.example.kamilh.pierwsza;

import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Locale;


public class MainActivity extends ActionBarActivity {
    String region = null;

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


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void getRegion()
    {
        TextView textView = (TextView) findViewById(R.id.textView3);
        Criteria cr = new Criteria();
        LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
        Location loc = lm.getLastKnownLocation(lm.getBestProvider(cr, true));
        double lat = loc.getLatitude();
        double lon = loc.getLongitude();

        new Region().execute(lat, lon);
        textView.setText(region);
    }

    public void count(View view) throws IOException {
        EditText editText = (EditText) findViewById(R.id.editText);
        EditText editText2 = (EditText) findViewById(R.id.editText2);

        double cost = 5.25;
        double petrol = Double.valueOf(editText.getText().toString());
        double distance = Double.valueOf(editText2.getText().toString());

        double result = Math.round(cost*(distance/100)*petrol);
        //textView.setText("The cost of your trip is: "+String.valueOf(result)+" zł");

        getRegion();
    }

    private class Region extends AsyncTask<Double, Void, String> {

        @Override
        public String doInBackground(Double... params) {
            URL url = null;
            BufferedReader in = null;
            try {
                url = new URL("https://maps.googleapis.com/maps/api/geocode/json?latlng="+params[0]+","+params[1]);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            try {
                if (url != null) {
                    in = new BufferedReader(new InputStreamReader(url.openStream()));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            String line = null;
            String x = null;
            for (int i = 0; i<31; i++){
                if (in != null) {
                    try {
                        line = in.readLine();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return line;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            region = result;
        }
}

现在,我希望能够清理一下我的代码,所以我决定将这两个类分开。我看到了这个例子(上图),我试图在我的项目中实现这个解决方案,但我失败了。 Android: How to run asynctask from different class file?

以下是我的MainActivity类:

package com.example.kamilh.pierwsza;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.io.IOException;


public class MainActivity extends ActionBarActivity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void getRegion(String result)
    {
        TextView textView = (TextView) findViewById(R.id.textView3);
        textView.setText(result);
    }

    public void count(View view) throws IOException {
        EditText editText = (EditText) findViewById(R.id.editText);
        EditText editText2 = (EditText) findViewById(R.id.editText2);

        double cost = 5.25;
        double petrol = Double.valueOf(editText.getText().toString());
        double distance = Double.valueOf(editText2.getText().toString());

        double result = Math.round(cost*(distance/100)*petrol);
        //textView.setText("The cost of your trip is: "+String.valueOf(result)+" zł");

        Criteria cr = new Criteria();
        LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
        Location loc = lm.getLastKnownLocation(lm.getBestProvider(cr, true));
        double lat = loc.getLatitude();
        double lon = loc.getLongitude();

        new Region(this).execute(lat, lon);
    }
}

这是我的Region类:

package com.example.kamilh.pierwsza;

import android.content.Context;
import android.os.AsyncTask;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by KamilH on 2015-02-19.
 */
class Region extends AsyncTask<Double, Void, String> {
    private Context context;
    MainActivity activity;

    public Region (Context context){
        this.context = context;
    }

    @Override
    public String doInBackground(Double... params) {
        URL url = null;
        BufferedReader in = null;
        try {
            url = new URL("https://maps.googleapis.com/maps/api/geocode/json?latlng="+params[0]+","+params[1]);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            if (url != null) {
                in = new BufferedReader(new InputStreamReader(url.openStream()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        String line = null;
        String x = null;
        for (int i = 0; i<31; i++){
            if (in != null) {
                try {
                    line = in.readLine();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return line;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        activity.getRegion(result);
    }
}

在我使用分开的文件运行应用程序后,我得到了这些错误:

02-19 14:42:39.793  13842-13842/com.example.kamilh.pierwsza E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.kamilh.pierwsza, PID: 13842
    java.lang.NullPointerException
            at com.example.kamilh.pierwsza.Region.onPostExecute(Region.java:57)
            at com.example.kamilh.pierwsza.Region.onPostExecute(Region.java:15)
            at android.os.AsyncTask.finish(AsyncTask.java:632)
            at android.os.AsyncTask.access$600(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5867)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
            at dalvik.system.NativeStart.main(Native Method)

请问,请告诉我如何修复它?

4 个答案:

答案 0 :(得分:1)

将您的Region类更改为:

package com.example.kamilh.pierwsza;

import android.os.AsyncTask;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by KamilH on 2015-02-19.
 */
class Region extends AsyncTask<Double, Void, String> {
    private MainActivity activity;

    public Region (MainActivity activity){
        this.activity = activity;
    }

    @Override
    public String doInBackground(Double... params) {
        URL url = null;
        BufferedReader in = null;
        try {
            url = new URL("https://maps.googleapis.com/maps/api/geocode/json?latlng="+params[0]+","+params[1]);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            if (url != null) {
                in = new BufferedReader(new InputStreamReader(url.openStream()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        String line = null;
        String x = null;
        for (int i = 0; i<31; i++){
            if (in != null) {
                try {
                    line = in.readLine();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return line;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        activity.getRegion(result);
    }
}

为什么呢?好。您在getRegion的{​​{1}}上致电activity。但onPostExecute从未初始化。并且由于您希望它在您执行activity的MainActivity中调用该方法,因此必须更改构造函数。由于您未使用new Region(this),我们会将其删除并替换为Context,并确保它为您班级中的MainActivity字段提供值。

请注意,activityActivity的子类。活动中的Context是活动,因此也是上下文。不是你需要它。

查看回调例程也可能很好。这是你在这里做的,但可以通过使用界面来完成。然后重新使用您的代码会更容易。

答案 1 :(得分:0)

您没有在Region构造函数中初始化活动,因此当您尝试在asyncTask postExecute中调用getRegion时,activity为null。你应该在Region构造函数中初始化活动。

答案 2 :(得分:0)

您的活动为空

public Region (Context context, MainActivity act){
    this.context = context;
    this.activity = act;
}

答案 3 :(得分:-2)

您收到NullPointerException,因为您的Region课程未找到getRegion()内的MainActivity方法。

将活动提供给Region类的构造函数。