我有一个活动,其中Navigation Drawer
有许多按钮,其中一个按钮指向fragment
。
问题是我必须让AsyncTask
从服务器获取一些信息,但我无法在getSupportFragmentManager()
内使用AsyncTask
。
我试图使用上下文或活动,但我不能让它工作。
我得到此错误无法解决方法getSupportFragmentManager()
AsyncTask.java:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
public class AsyncTask extends AsyncTask<Void, Void, String> {
private Context c;
private String urlAddress;
private String token;
private DatabaseHelper db;
private Activity mainActivity;
public AsyncTask(Context c, DatabaseHelper databaseHelper, String urlAddress, Activity activity) {
this.c = c;
this.db = databaseHelper;
this.urlAddress = urlAddress;
this.mainActivity = activity;
//GET token FROM database
this.token = db.getValueFromColumn(0, DatabaseHelper.getTableUser(), DatabaseHelper.getUserToken());
}
@Override
protected String doInBackground(Void... params) {
return this.send();
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if (response != null) {
//SUCCESS
mainActivity.getSupportFragmentManager().beginTransaction()
.add(R.id.content_frame
, new SessionsFragment())
.addToBackStack("back")
.commit();
} else {
//NO SUCCESS
}
}
private String send() {
//CONNECT
HttpURLConnection connection = Connector.connect(urlAddress);
if (connection == null) {
return null;
}
try {
OutputStream outputStream = connection.getOutputStream();
//WRITE
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
bufferedWriter.write(new DataPackager(token).packData());
bufferedWriter.flush();
//RELEASE RES
bufferedWriter.close();
outputStream.close();
//HAS IT BEEN SUCCESSFUL?
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
//GET EXACT RESPONSE
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder buffer = new StringBuilder();
String line;
//READ LINE BY LINE
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONObject secondParentObject = parentObject.getJSONObject("data");
//json getter and adder to database
JSONArray array = secondParentObject.getJSONArray("s");
for (int i = 0; i < array.length(); i++) {
JSONObject finalObject = array.getJSONObject(i);
db.SessionsAddJson(finalObject);
//RELEASE RES
reader.close();
}
return "c";
} else {
}
} catch (IOException | JSONException e) {
e.printStackTrace();
} finally {
connection.disconnect();
}
return null;
}
}
我通过以下方式调用任务:
new $AsyncTask(getApplicationContext(), db, URL, MyActivity.this).execute();
感谢您的帮助。
答案 0 :(得分:1)
您的活动应为AppCompatActivity
而不是Activity
答案 1 :(得分:1)
UPD:
你应该在构造函数中传递AppCompatActivity
,如下所示:
替换
private Activity mainActivity;
同
private AppCompatActivity mainActivity;
当你使用它时:替换
new $AsyncTask(getApplicationContext(), db, URL).execute();
同
new $AsyncTask(getApplicationContext(), db, URL, YourCurrentActivity.this).execute();
请注意,YourCurrentActivity
应该extends
AppCompatActivity
。
您只需将AppCompatActivity
与Activity
混淆。 Activity
没有getSupportFragmentManager()
,但AppCompatActivity
有这个。
答案 2 :(得分:1)
如果您使用asyntask类然后加载片段,则需要上下文,即特定活动的上下文。
因此,对要加载片段的相应活动的上下文进行类型转换,并使用特定活动fragmentManager加载片段onPostExecute。
public class sampleAsyncTask extends AsyncTask<Void, Void, Void> {
private YourActivity mActivity;
@Override
protected Void doInBackground(Void... voids) {
return null;
}
public sampleAsyncTask(Context context) {
super();
activity = (YourActivity) context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mActivity.getSupportFragmentManager().beginTransaction()
.add(R.id.content_frame
, new Fragment())
.addToBackStack("back")
.commit();
}
}
修改强>:
在这行代码中,而不是将活动类型转换的通用引用存储到特定活动,即当前活动。
private YOURACTIVITY mainActivity;
public AsyncTask(Context c, DatabaseHelper databaseHelper, String urlAddress, Activity activity) {
this.c = c;
this.db = databaseHelper;
this.urlAddress = urlAddress;
//TypeCast to your particular activity
mainActivity =(YOURACTIVITY) activity;
this.token = db.getValueFromColumn(0, DatabaseHelper.getTableUser(), DatabaseHelper.getUserToken());
}
答案 3 :(得分:0)
试试这个
getActivity().getFragmentManager().beginTransaction()
.add(R.id.content_frame
, new Fragment())
.addToBackStack("back")
.commit();