分离文件中的 AsyncTask 和 MainActivity
AsyncTask and MainActivity in separated files
我试图通过将我的 AsyncTask class 和 MainActivity class 放在其他文件中来分离它们。
这是我的完整程序:
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;
}
}
现在,我希望能够稍微清理一下我的代码,所以我决定将这两个 class 分开。我看到了这个例子(上面),我试图在我的项目中实现这个解决方案,但我失败了。
Android: How to run asynctask from different class file?
这是我的 MainActivity class:
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);
}
}
这是我的地区 class:
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.access0(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)
你能告诉我如何解决吗?
您没有在 Region 构造函数中初始化 activity,因此当您尝试在 asyncTask postExecute 中调用 getRegion 时,activity 为 null。您应该在 Region 构造函数中初始化 activity。
您得到 NullPointerException
,因为您的 Region
class 没有找到 MainActivity
.[=15= 中的 getRegion()
方法]
将 activity 提供给 Region
class 的构造函数。
将您的区域 class 更改为:
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);
}
}
为什么?出色地。您在 onPostExecute
中的 activity
上调用了 getRegion
。但是 activity
从未被初始化。由于您希望它在您执行 new Region(this)
的 MainActivity 中调用该方法,因此必须更改构造函数。由于您不使用 Context
,我们将其删除并替换为 MainActivity
,并确保它为 class 中的 activity
字段提供值。
请注意 Activity
是 Context
的子class。 activity 中的 this
是 activity,因此是上下文。不是说你需要它。
查看回调例程也可能很好。这就是您在这里所做的,但可以通过使用界面来完成。然后重新使用您的代码会更容易。
您的activity为空
public Region (Context context, MainActivity act){
this.context = context;
this.activity = act;
}
我试图通过将我的 AsyncTask class 和 MainActivity class 放在其他文件中来分离它们。 这是我的完整程序:
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;
}
}
现在,我希望能够稍微清理一下我的代码,所以我决定将这两个 class 分开。我看到了这个例子(上面),我试图在我的项目中实现这个解决方案,但我失败了。 Android: How to run asynctask from different class file?
这是我的 MainActivity class:
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);
}
}
这是我的地区 class:
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.access0(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)
你能告诉我如何解决吗?
您没有在 Region 构造函数中初始化 activity,因此当您尝试在 asyncTask postExecute 中调用 getRegion 时,activity 为 null。您应该在 Region 构造函数中初始化 activity。
您得到 NullPointerException
,因为您的 Region
class 没有找到 MainActivity
.[=15= 中的 getRegion()
方法]
将 activity 提供给 Region
class 的构造函数。
将您的区域 class 更改为:
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);
}
}
为什么?出色地。您在 onPostExecute
中的 activity
上调用了 getRegion
。但是 activity
从未被初始化。由于您希望它在您执行 new Region(this)
的 MainActivity 中调用该方法,因此必须更改构造函数。由于您不使用 Context
,我们将其删除并替换为 MainActivity
,并确保它为 class 中的 activity
字段提供值。
请注意 Activity
是 Context
的子class。 activity 中的 this
是 activity,因此是上下文。不是说你需要它。
查看回调例程也可能很好。这就是您在这里所做的,但可以通过使用界面来完成。然后重新使用您的代码会更容易。
您的activity为空
public Region (Context context, MainActivity act){
this.context = context;
this.activity = act;
}