Android 片段和活动之间的接口不工作
我想将我的字符串json从片段传递到另一个活动,以便在片段和活动之间建立接口,但当午餐应用程序从我的片段中的这一行获得null异常时:Android 片段和活动之间的接口不工作,android,android-fragments,interface,nullpointerexception,Android,Android Fragments,Interface,Nullpointerexception,我想将我的字符串json从片段传递到另一个活动,以便在片段和活动之间建立接口,但当午餐应用程序从我的片段中的这一行获得null异常时:adapterCalljson.MethodCallbackjson(jsonStr) 这是我迄今为止的尝试: 接口类: public interface AdapterCalljson { void MethodCallbackjson(String jsonn); } 片段: public class maghalat extends Fragme
adapterCalljson.MethodCallbackjson(jsonStr)代码>
这是我迄今为止的尝试:
接口类:
public interface AdapterCalljson {
void MethodCallbackjson(String jsonn);
}
片段:
public class maghalat extends Fragment {
private View myFragmentView;
private RecyclerView recyclerView;
private DataAdapter adapter;
private String TAG = MainActivity.class.getSimpleName();
public ProgressDialog pDialog;
List<jsonContent> listcontent=new ArrayList<>();
public int dog=1;
public String url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_recent_posts";
public int id;
AdapterCalljson adapterCalljson;
public String json;
public String jsonStr;
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof AdapterCalljson) {
adapterCalljson = (AdapterCalljson) context;
} else {
throw new RuntimeException(context + " must implement AdapterCalljson");
}
}
@Override
public void onDetach() {
super.onDetach();
adapterCalljson = null;
}
public interface AdapterCalljson {
void MethodCallbackjson(String json);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myFragmentView = inflater.inflate(R.layout.maghalat, container, false);
adapterCalljson.MethodCallbackjson(json);
asyncRun();
return myFragmentView;
}
public void asyncRun(){
if(isNetworkConnected()) {
new GetContacts().execute();
} else
{
Toast.makeText(getActivity().getApplicationContext(), "دستگاه شما به اینترنت متصل نیست!", Toast.LENGTH_LONG).show();
}
}
public class GetContacts extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
id=jsonObj.getInt("pages");
JSONArray posts = jsonObj.getJSONArray("posts");
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
jsonContent jsonContent=new jsonContent();
jsonContent.title=c.getString("title");
jsonContent.content=c.getString("content");
//img
JSONObject post_img=c.getJSONObject("thumbnail_images");
for (int j=0;j<post_img.length();j++)
{
JSONObject v=post_img.getJSONObject("mom-portfolio-two");
jsonContent.imgurl=v.getString("url");
}
jsonContent.pages=id;
jsonContent.curpage=dog;
listcontent.add(jsonContent);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
recyclerView=(RecyclerView)myFragmentView.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
adapter=new DataAdapter(getActivity(), listcontent, new AdapterCallback() {
@Override
public void MethodCallbackgo(String data) {
Integer s=null;
try {
s= Integer.valueOf(data);
}catch (NumberFormatException e)
{
}
if (s!=null && s>=1 && s<=id)
{
dog= Integer.parseInt(data);
url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_recent_posts";
new GetContacts().execute();
}else
{
Toast.makeText(getActivity().getApplicationContext(),"صفحه پیدا نشد",Toast.LENGTH_SHORT).show();
}
}
@Override
public void MethodCallbacknext() {
if (dog<id)
{
dog += 1;
url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_recent_posts";
new GetContacts().execute();
}else {
Toast.makeText(getActivity().getApplicationContext(),"این آخرین صفحه است",Toast.LENGTH_SHORT).show();
}
}
@Override
public void MethodCallbackprev() {
if (dog!=1)
{
dog-=1;
url = "http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/"+String.valueOf(dog)+"/?json=get_recent_posts";
new GetContacts().execute();
}else{
Toast.makeText(getActivity().getApplicationContext(),"این اولین صفحه است",Toast.LENGTH_SHORT).show();
}
}
});
recyclerView.setAdapter(adapter);
json=jsonStr;
}
}
公共类maghalat扩展片段{
私有视图myFragmentView;
私人回收站;
专用数据适配器;
私有字符串标记=MainActivity.class.getSimpleName();
公共对话;
List listcontent=new ArrayList();
公共int狗=1;
公共字符串url=”http://memaraneha.ir/category/%d9%85%d9%82%d8%a7%d9%84%d8%a7%d8%aa/page/“+String.valueOf(dog)+”/?json=get_recents_posts”;
公共int id;
AdapterCalljson AdapterCalljson;
公共字符串json;
公共字符串jsonStr;
@凌驾
公共void-onAttach(上下文){
super.onAttach(上下文);
if(AdapterCalljson的上下文实例){
adapterCalljson=(adapterCalljson)上下文;
}否则{
抛出新的RuntimeException(上下文+“必须实现AdapterCalljson”);
}
}
@凌驾
公共无效连接(){
super.onDetach();
adapterCalljson=null;
}
公共接口适配器调用JSON{
void MethodCallbackjson(字符串json);
}
@凌驾
CreateView上的公共视图(布局、充气机、视图组容器、捆绑包保存状态){
myFragmentView=充气机。充气(R.layout.maghalat,容器,假);
adapterCalljson.MethodCallbackjson(json);
异步运行();
返回myFragmentView;
}
公共void asyncRun(){
如果(isNetworkConnected()){
新建GetContacts().execute();
}否则
{
Toast.makeText(getActivity().getApplicationContext(),“Toast.LENGTH.”show(),“Toast.LENGTH.”;
}
}
公共类GetContacts扩展异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//显示进度对话框
pDialog=newprogressdialog(getActivity());
setMessage(“请稍候…”);
pDialog.setCancelable(假);
pDialog.show();
}
@凌驾
受保护的Void doInBackground(Void…arg0){
HttpHandler sh=新的HttpHandler();
//向url发出请求并获得响应
jsonStr=sh.makeServiceCall(url);
Log.e(标签,“来自url的响应:+jsonStr”);
if(jsonStr!=null){
试一试{
JSONObject jsonObj=新的JSONObject(jsonStr);
id=jsonObj.getInt(“页面”);
JSONArray posts=jsonObj.getJSONArray(“posts”);
对于(int i=0;i 对于(int j=0;j=1&&s您尚未将对象分配给adapterCalljson。假设您正在主机活动中实现adapterCalljson
,请从上下文onAttach
中分配它:
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof AdapterCalljson) {
adapterCalljson = (AdapterCalljson) context;
} else {
throw new RuntimeException(context + " must implement AdapterCalljson");
}
}
@Override
public void onDetach() {
super.onDetach();
adapterCalljson = null;
}
public interface AdapterCalljson {
void MethodCallbackjson(String json);
}
首先,包含片段的活动必须实现该接口
public class MainActivity implements AdapterCalljson {
@Override
void MethodCallbackjson(String jsonn) {
doSomethingWithJson(jsonn);
}
private void doSomethingWithJson(String json) {
}
// onCreate...
}
接下来,我建议您在AsyncTask之外创建RecyclerView。您不需要保存myFragmentView
变量
此外,您还无法调用回调。没有数据
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.maghalat, container, false);
// recyclerView = rootView.findViewById
// adapter = ...
// recyclerView.setAdadpter...
asyncRun(); // This happens in the background. There is no JSON yet
return rootView;
}
然后,也许您应该让doInBackground
返回JSON字符串,这样就不必将其存储为类变量
最后一个参数是返回类型
public class GetContacts extends AsyncTask<Void, Void, String>
然后你应该能够使用你的回调
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
if (adapterCalljson != null) {
adapterCalljson.MethodCallbackjson(result);
} else {
Log.w("Callback Error", "callback not assigned");
}
// adapter.notifyDataSetChanged(); // Might want this
}
嗯。你从来没有给任何东西分配过adapterCalljson
。你的适配器是空的,你应该有一个空检查。除此之外,我认为你不明白“异步”是怎么回事工作。jsonStr
在调用该方法时也是空的通过@cricket\u 007请回答我的问题并告诉我的代码必须在哪里更改,所以我在我的片段中添加你的部分代码,但从这一行获得空异常:抛出新的RuntimeException(上下文+“必须实现AdapterCalljson”);@user7415865该行中的任何内容都不会引发空指针异常。您可能会因为写入该行的确切原因而收到RuntimeException
。该活动必须实现AdapterCalljson
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
if (adapterCalljson != null) {
adapterCalljson.MethodCallbackjson(result);
} else {
Log.w("Callback Error", "callback not assigned");
}
// adapter.notifyDataSetChanged(); // Might want this
}