我应该在哪里添加我的noInternetConnection方法? Android的

时间:2015-07-30 14:00:13

标签: android internet-connection

一切正常,我已经添加了我的方法来检查是否有互联网连接,以及是否没有更改活动。但它正在加载进度条之前立即更改活动。我应该在哪里添加此方法,以便加载第一个进度条,如果没有互联网连接,则更改活动。

如果有人对此检查互联网连接有任何建议,我会回答任何答案。

这是我使用该方法的活动:

public class ListaPreporuka extends AppCompatActivity {
// Log tag
private static final String TAG = ListaPreporuka.class.getSimpleName();

// Movies json url
private static final String url = "http://www.nadji-ekipu.org/wp-content/uploads/2015/07/movies.txt";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
private static String Title ="title";
private static String bitmap ="thumbnailUrl";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.lista_preporuka);

    getSupportActionBar().setDisplayShowHomeEnabled(true);   
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayUseLogoEnabled(true);
    getSupportActionBar().setLogo(R.drawable.ic_horor_filmovi_ikonica);

    Intent newActivity2=new Intent();
    setResult(RESULT_OK, newActivity2);

    listView = (ListView) findViewById(R.id.list);
    adapter = new CustomListAdapter(this, movieList);
    listView.setAdapter(adapter);

    pDialog = new ProgressDialog(this);
    // Showing progress dialog before making http request
    pDialog.setMessage("Učitavanje...");
    pDialog.show();      

    // 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
                            final JSONArray genreArry = obj.getJSONArray("genre");
                            ArrayList<String> genre = new ArrayList<String>();
                            for (int j = 0; j < genreArry.length(); j++) {
                                genre.add((String) genreArry.get(j));
                            }
                            movie.setGenre(genre);

                            // adding movie to movies array
                            movieList.add(movie);

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

                }
            });

    noInternet();

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(movieReq);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){ 

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) { 
            String name = ((TextView) view.findViewById(R.id.title))
                    .getText().toString();

            bitmap = ((Movie)movieList.get(position)).getThumbnailUrl();

            Intent intent = new Intent(ListaPreporuka.this, MoviesSingleActivity.class);    
            intent.putExtra(Title, name);
            intent.putExtra("images", bitmap);
            intent.putExtra("Year", movieList.get(position).getYear());             
            startActivity(intent);
            overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
            }
        });

}

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

private void hidePDialog() {
    if (pDialog != null) {
        pDialog.dismiss();
        pDialog = null;
    }
}

//WHERE SHOULD I ADD THIS METHOD FOR MAKING MY ACTIVITY SHOW FIRST PROGRESS BAR AND IF THERE IS NO INTERNET CONNECTION, SHOW ANOTHER ACTIVITY
private void noInternet() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    if (info != null) {
        if (!info.isConnected()) {
        }
    }
    else {
        Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(ListaPreporuka.this, NoConnection.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
    }
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    if (item.getItemId() == android.R.id.home) {
        finish();
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
        return true;
    }
    return false;
}

@Override
public void onBackPressed() {

    super.onBackPressed();
    overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}

2 个答案:

答案 0 :(得分:0)

你正在做一些http请求。所以,如果有可用的互联网连接,你想要解决吗? 所以首先检查互联网连接是否可用。

无论你在哪里进行其他操作......

if(internet connection is present){
     //make http request;
}else{
     // display appropriate message and switch to your new activity
}

答案 1 :(得分:0)

如果您想要简单的答案,您可以在同一个地方调用您的方法但有一些延迟。像这样:

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
  @Override
  public void run() {
    //Do something after 100ms
  }
}, 100);

但是,我认为,您最好使用此method来显示对话框:

public static ProgressDialog show (Context context, CharSequence title, CharSequence message, boolean indeterminate, boolean cancelable, DialogInterface.OnCancelListener cancelListener)

实现DialogInterface.OnCancelListener,通过转换到OnCancelListener的onCancel回调中的新活动来调用你的意图。

在noInternet()方法的else语句中使用pDialog.cancel()。