0

ich meinen String wollen json von Fragment zu einer anderen Aktivität übergeben, so Schnittstelle zwischen Fragment und Aktivität machen, aber wenn das Mittagessen App null Ausnahme von dieser Linie von meinem Fragment erhalten: adapterCalljson.MethodCallbackjson(jsonStr);Schnittstelle zwischen Fragment und Aktivität nicht funktioniert

dies ist mein bisher versuchen:

Interface-Klasse:

public interface AdapterCalljson { 
    void MethodCallbackjson(String jsonn); 
} 

Fragment:

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; 


     } 
    } 
+0

Um. Sie haben 'adapterCalljson' nie zugewiesen. –

+0

Ihr Adapter ist Null Chum, sollten Sie eine Nullprüfung haben –

+0

Abgesehen von diesem Punkt, ich glaube nicht, Sie verstehen, wie "async" funktioniert. 'jsonStr' ist auch null an dem Punkt, an dem Sie diese Methode aufrufen –

Antwort

0

Sie haben AdapterCalljson kein Objekt zugewiesen. Angenommen, Sie AdapterCalljson in der Host-Aktivität sind Implementierung, weisen Sie aus dem Kontext 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); 

} 
+0

also füge ich deinen Teil der Codes in mein Fragment, aber NULL-Ausnahme von dieser Zeile: neue RuntimeException werfen (Kontext + "muss AdapterCalljson implementieren"); – Erf

+0

@ user7415865 Nichts in dieser Zeile löst eine Nullzeigerausnahme aus. Sie erhalten wahrscheinlich eine 'RuntimeException' aus dem genauen Grund, der dort geschrieben wird. Die Aktivität ** muss AdapterCalljson implementieren ** –

0

Erstens Ihre Aktivität das Fragment enthält diese Schnittstelle implementieren müssen.

public class MainActivity implements AdapterCalljson { 

    @Override 
    void MethodCallbackjson(String jsonn) { 
     doSomethingWithJson(jsonn); 
    }  

    private void doSomethingWithJson(String json) { 

    } 

    // onCreate... 

} 

Als nächstes würde ich empfehlen, erstellen Sie die RecyclerView außerhalb der AsyncTask. Sie müssen die Variable myFragmentView nicht speichern.

Zusätzlich können Sie den Rückruf noch nicht aufrufen. Keine Daten verfügbar.

@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; 
} 

Dann sollten Sie vielleicht doInBackground Rückkehr des JSON-String, so dass Sie es als eine Klassenvariable nicht speichern müssen.

Das letzte Argument ist der Rückgabetyp.

public class GetContacts extends AsyncTask<Void, Void, String> 

So, dann ist es public String doInBackground(Void params...) {} und public void onPostExecute(String result) {}.

Mit anderen Worten, nicht nur return null von doInBackground

@Override 
protected String doInBackground(Void... arg0) { 

    HttpHandler sh = new HttpHandler(); 

    // Making a request to url and getting response 
    jsonStr = sh.makeServiceCall(url); 

    // Parse JSON more... 

    return jsonStr; 
} 

Und dann sollten Sie in der Lage sein, Ihren Rückruf zu verwenden.

@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 
} 
Verwandte Themen