首页 > 解决方案 > 我如何从片段中调用地理类(它有演员问题)

问题描述

分段

嗨,我创建了一个抽屉导航菜单活动,并且我有 AnasayfaFragment。我想用谷歌距离 api 计算 2 个位置之间的距离,但我不能从片段中调用 geo.class。我得到一个错误。这是关于铸造的。我从 GeoTask.java 收到关于 public GeoTask(Context mContext) {this.mContext = mContext;geo1= (Geo) mContext;} 的错误:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.orderapp, PID: 25413
    java.lang.ClassCastException: android.app.Application cannot be cast to com.example.orderapp.GeoTask$Geo
        at com.example.orderapp.GeoTask.<init>(GeoTask.java:33)
        at com.example.orderapp.anasayfa.AnasayfaFragment$1.onClick(AnasayfaFragment.java:515)
        at android.view.View.performClick(View.java:7256)
        at android.view.View.performClickInternal(View.java:7218)
        at android.view.View.access$3800(View.java:824)
        at android.view.View$PerformClick.run(View.java:27719)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:228)
        at android.app.ActivityThread.main(ActivityThread.java:7782)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:981)
I/Process: Sending signal. PID: 25413 SIG: 9

这是 GeoTask.java。我该如何施放?

package com.example.orderapp;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by SRIVASTAVA on 1/9/2016.
 */
/*The instance of this class is called by "MainActivty",to get the time taken reach the destination from Google Distance Matrix API in background.
  This class contains interface "Geo" to call the function setDouble(String) defined in "MainActivity.class" to display the result.*/
public class GeoTask extends AsyncTask<String, Void, String> {
    ProgressDialog pd;
    Context mContext;
    Double duration;
    Geo geo1;
//constructor is used to get the context.
    public GeoTask(Context mContext) {
        this.mContext = mContext;
        geo1= (Geo) mContext;
    }
//This function is executed before before "doInBackground(String...params)" is executed to dispaly the progress dialog
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd=new ProgressDialog(mContext);
        pd.setMessage("Loading");
        pd.setCancelable(false);
        pd.show();
    }
//This function is executed after the execution of "doInBackground(String...params)" to dismiss the dispalyed progress dialog and call "setDouble(Double)" defined in "MainActivity.java"
    @Override
    protected void onPostExecute(String aDouble) {
        super.onPostExecute(aDouble);
        if(aDouble!=null)
        {
         geo1.setDouble(aDouble);
            pd.dismiss();
        }
        else
            Toast.makeText(mContext, "Error4!Please Try Again wiht proper values", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            URL url=new URL(params[0]);
            HttpURLConnection con= (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            con.connect();
            int statuscode=con.getResponseCode();
            if(statuscode== HttpURLConnection.HTTP_OK)
            {
                BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
                StringBuilder sb=new StringBuilder();
                String line=br.readLine();
                while(line!=null)
                {
                    sb.append(line);
                    line=br.readLine();
                }
                String json=sb.toString();
                Log.d("JSON",json);
                JSONObject root=new JSONObject(json);
                JSONArray array_rows=root.getJSONArray("rows");
                Log.d("JSON","array_rows:"+array_rows);
                JSONObject object_rows=array_rows.getJSONObject(0);
                Log.d("JSON","object_rows:"+object_rows);
                JSONArray array_elements=object_rows.getJSONArray("elements");
                Log.d("JSON","array_elements:"+array_elements);
                JSONObject object_elements=array_elements.getJSONObject(0);
                Log.d("JSON","object_elements:"+object_elements);
                JSONObject object_duration=object_elements.getJSONObject("duration");
                JSONObject object_distance=object_elements.getJSONObject("distance");

                Log.d("JSON","object_duration:"+object_duration);
                return object_duration.getString("value")+","+object_distance.getString("value");

            }
        } catch (MalformedURLException e) {
            Log.d("error", "error1");
        } catch (IOException e) {
            Log.d("error", "error2");
        } catch (JSONException e) {
            Log.d("error","error3");
        }


        return null;
    }
    interface Geo{
        public void setDouble(String min);
    }

}

这是我的 AnasayfaFragment

 @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.anasayfa_fragment, container, false);
        bottom_sheet = view.findViewById(R.id.bottom_sheet);
        sheetBehavior = BottomSheetBehavior.from(bottom_sheet);
        new getJsonResponseSiparisBilgileri().execute();
        new getJsonResponseTedarikciBilgi().execute();
        imageView=view.findViewById(R.id.imageView2);
        btnonayla=view.findViewById(R.id.btnOnayla);
        txtMesafe=view.findViewById(R.id.txtMesafe);
        txtsure=view.findViewById(R.id.textSure);

        getDirection=(CircularImageView)view.findViewById(R.id.btngetdirection);
        getDirection.setOnClickListener(this);
           btnonayla.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + "37.8716794,32.4915672" + "&destinations=" + "37.8716794,32.4915672" + "&mode=driving&language=fr-FR&avoid=tolls&key=myKey";
                new GeoTask(getActivity().getApplication()).execute(url);

            }
        });

这是 AnasayfaActivity

package com.example.orderapp;

import android.os.Bundle;
import android.view.Menu;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.material.navigation.NavigationView;

import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

public class AnasayfaActivity extends AppCompatActivity {
    private GoogleMap mMap;    private Polyline currentPolyline;

    private MarkerOptions place1, place2;
    List<MarkerOptions> markerOptionsList=new ArrayList<>();
    private AppBarConfiguration mAppBarConfiguration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_anasayfa);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_anasayfa,R.id.nav_home, R.id.nav_siparislerim, R.id.nav_grafikler,
                R.id.nav_guncelle, R.id.nav_davet, R.id.nav_help,R.id.nav_howtouse,R.id.nav_aboutus,R.id.nav_oneriSikayet,R.id.nav_kullanimKosul,R.id.nav_quit)
                .setDrawerLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.anasayfa, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }






}

标签: androidfragment

解决方案


推荐阅读