我必须创建一个ArrayAdapter,但当我将getActivity()放入构造函数时,它会显示cannot resolve method getActivity()
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import android.widget.ArrayAdapter;
import java.net.HttpURLConnection;
import java.lang.Void;
import android.widget.ListView;
import android.os.AsyncTask;
import android.content.Context;
public class HttpURLConnectionExample extends AsyncTask<ListView, Void, String> {
public ListView myList = null;
public void sendGet(ListView lv){
myList = lv;
this.execute();
return;
}
@Override
protected String doInBackground(ListView... arg0) {
String url = "http://192.168.1.9";
URL obj = null;
try{
obj = new URL(url);}
catch(IOException e){}
HttpURLConnection con = null;
try{
con = (HttpURLConnection) obj.openConnection();}
catch(IOException e){}
//con.setRequestProperty("User-Agent", USER_AGENT);
try{
con.setRequestMethod("GET");}
catch(ProtocolException e){}
try{
con.connect();}
catch(IOException e){}
try{
int responseCode = con.getResponseCode();}
catch(IOException e){}
BufferedReader in = null;
try{
in = new BufferedReader(
new InputStreamReader(con.getInputStream()));}
catch(IOException e){}
String inputLine;
StringBuffer response = new StringBuffer();
try{
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}}
catch(IOException e){}
try{
in.close();}
catch(IOException e){}
//print result
System.out.println(response.toString());
return response.toString();
}
@Override
protected void onPostExecute(String result) {
String strParts[] = result.split("@");
ArrayList<dispencer> listAr = new ArrayList<dispencer>();
for(int i=0; i<strParts.length; i++){
listAr.add( new dispencer(strParts[i]) );
}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_expandable_list_item_1);
for (int i = 0; i < listAr.size(); ++i) {
adapter.add(listAr.get(i).toString());
}
myList.setAdapter(adapter);
return ;
}
}
我读过我必须使用getActivity方法,因为我是在一个片段而不是在上下文中。 编辑我不能扩展我的MainActivity类,因为这个类已经扩展了asyncTask。
答案 0 :(得分:0)
首先要确保你导入了Fragment类并使你的片段扩展了它。 使用Type
定义变量Context mContext ;
然后用getActivity()像这样
初始化这个变量mContext=getActivity();
将此变量传递给适配器
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_expandable_list_item_1);
答案 1 :(得分:0)
您没有扩展片段类。所以你需要做一些事情。
当你想在asynctask类中使用上下文时。你需要在类构造函数中传递上下文。
例如
public class MyCustomTask extends AsyncTask<Void, Void, Long> {
private Context mContext;
public MyCustomTask (Context context){
mContext = context;
}
//other methods like onPreExecute etc.
protected void onPostExecute(Long result) {
Toast.makeText(mContext,"Its working", Toast.LENGTH_LONG).show();
} }
通过以下方式实例化课程。
MyCustomTask task = new MyCustomTask(context);
task.execute(..);
答案 2 :(得分:0)
您正在延长AsyncTask
而不是Fragment
类,而是将Context
或Activity
引用传递给构造函数:
public MyTask(Context context)
并在您的任务中存储对它的引用。