如何更改url字符串,当http请求线程运行时显示错误

时间:2016-03-30 19:35:57

标签: android

  

我无法在oncreateview中分配url字符串,因为它是静态final,如果我将其更改为static并将其声明为oncreateview,它会在编译时分配并且没有错误显示但是运行时可能是因为http请求在其他线程上运行无法获取oncreateview中指定的网址。我想要   可以更改URL的代码。在获取url字符串时,http请求在url字符串中运行时没有任何null异常

package com.celebrations.kishan.fragments;


public class FiveFragment extends Fragment {
    private static final String TAG = "Five activity"; 

我希望下面的url可以从之前的活动中更改,因为它是最终的静态我无法改变是为了解决这个问题吗?

    private static final String url = "http://111.111.11.111/celebrations/cab.php";
    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;
    private CustomListAdapter adapter;
    private int datasql8=0;


    public FiveFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        FragmentActivity faActivity = (FragmentActivity) super.getActivity();
        // Replace LinearLayout by the type of the root element of the layout you're trying to load
        RelativeLayout rlLayout = (RelativeLayout) inflater.inflate(R.layout.fragment_eight, container, false);
        // Inflate the layout for this fragment
        listView = (ListView) rlLayout.findViewById(R.id.list);
        adapter = new CustomListAdapter(super.getActivity(), movieList);
        listView.setAdapter(adapter);
        final SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE);
        final SharedPreferences.Editor edt = preferences.edit();



        pDialog = new ProgressDialog(super.getActivity());
        // Showing progress dialog before making http request
        pDialog.setMessage("Celebrating...");
        pDialog.show();

//
  

JsonArrayRequest下面的代码(url,new Response.Listener()

     
    

网址应该是静态和字符串

  
        // Creating volley request obj
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                Movie movie = new Movie();
                                movie.setTitle(obj.getString("title"));
                                movie.setThumbnailUrl(obj.getString("image"));
                                movie.setRating(((Number) obj.get("rating"))
                                        .doubleValue());
                                movie.setYear(obj.getInt("releaseYear"));

                                // Genre is json array
                                //JSONArray genreArry = obj.getJSONArray("genre");
                                ArrayList<String> genre = new ArrayList<String>();
                                for (int j = 0; j < 1; j++) {
                                    genre.add("Certified");
                                }
                                movie.setGenre(genre);
                                if((preferences.getString("dataf8", "empty")).equals("empty"))
                                {
                                    if(isOnline()==true)
                                    { Toast.makeText(getActivity(),"null online",Toast.LENGTH_LONG).show();
                                        edt.putString("dataf8","stored");
                                        edt.commit();

                                        try {
                                            MainActivity.dbs.execSQL("insert into tableeight values('" + obj.getString("title") + "','" + obj.getString("image") + "'," + ((Number) obj.get("rating"))
                                                    .doubleValue() + "," + obj.getInt("releaseYear") + ")");
                                        }catch(Exception ae)
                                        {
                                            Toast.makeText(getActivity(),ae.getMessage().toString(),Toast.LENGTH_LONG).show();
                                        }
                                    }
                                    else
                                    {
                                        Toast.makeText(getActivity(),"Connect To Internet",Toast.LENGTH_SHORT).show();

                                    }
                                }
                                else
                                {
                                    if(isOnline()==true)
                                    {// Toast.makeText(getActivity(),"full fresh insert online"+i,Toast.LENGTH_SHORT).show();
                                        try {

                                            MainActivity.dbs.execSQL("insert into tableeight values('Work online','" + obj.getString("image") + "'," + ((Number) obj.get("rating"))
                                                    .doubleValue() + "," + obj.getInt("releaseYear") + ")");
                                        }catch(Exception ae)
                                        {
                                            Toast.makeText(getActivity(),ae.getMessage().toString(),Toast.LENGTH_LONG).show();
                                        }
                                    }else
                                    {  //Toast.makeText(getActivity(),"old put offline",Toast.LENGTH_LONG).show();
                                        try
                                        {
                                            Cursor point=MainActivity.dbs.rawQuery("select * from tableeight",null);
                                            point.moveToFirst();
                                            do {
                                                movie.setTitle(point.getString(0));
                                                movie.setThumbnailUrl(point.getBlob(1).toString());

                                                movie.setRating(((Number) point.getDouble(2))
                                                        .doubleValue());
                                                movie.setYear(point.getInt(3));

                                                for (int j = 0; j < 1; j++) {
                                                    genre.add("Certified");
                                                }
                                                movie.setGenre(genre);

                                            }while(point.moveToNext());
                                        }
                                        catch (Exception ea)
                                        {
                                            Toast.makeText(getActivity(),ea.getMessage().toString(),Toast.LENGTH_LONG).show();
                                        }
                                    }


                                }

                                // adding movie to movies array
                                movieList.add(movie);
                                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                                    @Override

                                    public void onItemClick(AdapterView parent, View view, int position, long id) {



                                        Movie o = (Movie) parent.getItemAtPosition(position);

                                        Toast.makeText(getActivity(), o.getTitle().toString(), Toast.LENGTH_SHORT).show();
                                        Intent intent = new Intent(getActivity(),Details.class);
                                        intent.putExtra("Key", o.getTitle().toString());
                                        startActivity(intent);
                                    }

                                });

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();

            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);

        return rlLayout ;
    }public boolean isOnline() {
        ConnectivityManager cm =
                (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        return netInfo != null && netInfo.isConnectedOrConnecting();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

        super.onCreateOptionsMenu(menu, inflater);
    }

}

1 个答案:

答案 0 :(得分:1)

您已在代码中使用intent.putExtra。为什么不使用相同的方法传递URL?

 Intent intent = new Intent(getActivity(),Details.class);
 intent.putExtra("Key", o.getTitle().toString());
 intent.putExtra("URL", url);
 startActivity(intent);

编辑1:

如果您想更改网址,可以将其保存(可能是)SharedPreferences并随时读取/写入。

编辑2:

您可以创建一个单独的类来存储网址。像这样:

public class MyUrls{
   public static String url1 = "http://www.example.com/api/";
   // some more urls, if any.
}

现在,请在任何地方使用MyUrls.url1。你也可以更新它。