-1

I cannot assign url string in oncreateview because it is static final and if i change it to static and declare it into oncreateview it assigns and no error shows up at compile time but run time may be because http request runs on other thread it cannot fetch the url assigned in oncreateview.I want a code where an url can be changed..and http request runs without any null exception in url string while fetching url string

package com.celebrations.kishan.fragments;


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

I want below url to be changed from previous activity because it is final static i couldnt change is thr any other best solution for this?

    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();

//

HERE BELOW CODE IN JsonArrayRequest(url,new Response.Listener()

URL SHOULD BE STATIC AND STRING

        // 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);
    }

}
Rahul Kishan
  • 314
  • 4
  • 18
  • Possible duplicate of [How do I pass data between activities on Android?](http://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-on-android) – Vucko Mar 30 '16 at 20:27

1 Answers1

1

You have already used intent.putExtra in your code. Why don't you pass the URL using same method?

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

Edit 1:

If you want to change the url, you can save it (may be) in SharedPreferences and read/write it whenever you want.

Edit 2:

You can create a separate class to store urls. Like this:

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

Now, use this like MyUrls.url1 anywhere. You can also update it.

Rohit Arya
  • 6,751
  • 1
  • 26
  • 40
  • I completely agree with your answer, but I wonder if he's not interested in changing the original URL so it will be reflected in the original activity when the user returns to it. I think we're missing the why here. – Roy Falk Mar 30 '16 at 19:40
  • The main problem is I cant change the URL because URL IS STATIC FINAL and if suppose i change it to ONLY STATIC AND DECLARE INSIDE oncreateView it accepts but the http request runs on the other thread so null exception comes when url is declared inside oncreateView – Rahul Kishan Mar 30 '16 at 20:10
  • yea i can edit it but if i edit it,while running it in app the http request runs in an another thread it cannot fetch the url string ends up in error that null exception while trying to fetch url string – Rahul Kishan Mar 30 '16 at 20:32
  • It won't throw `null pointer exception`, this exception is **only** thrown if you are calling a method on a `null` object. That might be some other issue. Just try the solution and post error logs if any. – Rohit Arya Mar 30 '16 at 20:34
  • My error:::Process: info.androidhive.customlistviewvolley, PID: 14451 java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference at com.android.volley.Request.(Request.java:136 at com.android.volley.toolbox.ImageRequest.(ImageRequest.java:71) at com.android.volley.toolbox.ImageLoader.get(ImageLoader.java:219) – Rahul Kishan Mar 30 '16 at 20:40
  • the cause of this error is something else, not related to accessing url. – Rohit Arya Mar 30 '16 at 20:47
  • @Rahulkishan, great. Can you also [accept and upvote](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) my answer. – Rohit Arya Mar 30 '16 at 21:27