Android json应用程序崩溃-由于没有网络连接,无法从未访问的服务器加载json文本文件
我正在使用JSON教程。它使用JSON文本文件从服务器加载数据,在这里一切正常。但是如果没有打开移动数据!,并没有从服务器接收到数据,我的应用程序只是崩溃。如何解决这个问题,也就是说,我正在寻找警报对话框或吐司味精,以显示网络不可用。最重要的是防止应用程序因为这个问题而崩溃。这是我的活动Android json应用程序崩溃-由于没有网络连接,无法从未访问的服务器加载json文本文件,android,json,Android,Json,我正在使用JSON教程。它使用JSON文本文件从服务器加载数据,在这里一切正常。但是如果没有打开移动数据!,并没有从服务器接收到数据,我的应用程序只是崩溃。如何解决这个问题,也就是说,我正在寻找警报对话框或吐司味精,以显示网络不可用。最重要的是防止应用程序因为这个问题而崩溃。这是我的活动 package app.test.json; import android.app.ProgressDialog; import android.content.Context; import android.
package app.test.json;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String FLAG = "flag";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Button btn = (Button) findViewById(R.id.readmore);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,appdetails.class));
}
});
*/
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
//mProgressDialog.setTitle("Connecting to Server");
// Set progressdialog message
mProgressDialog.setMessage("Connecting to App Server...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://localhost/json.txt");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("worldpopulation");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("rank", jsonobject.getString("rank"));
map.put("country", jsonobject.getString("country"));
map.put("population", jsonobject.getString("population"));
map.put("flag", jsonobject.getString("flag"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
Toast.makeText(MainActivity.this, "Connected To Server",Toast.LENGTH_LONG).show();
}
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}`
}
package app.test.json;
导入android.app.ProgressDialog;
导入android.content.Context;
导入android.content.Intent;
导入android.net.ConnectivityManager;
导入android.net.NetworkInfo;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.support.design.widget.FloatingActionButton;
导入android.support.design.widget.Snackbar;
导入android.util.Log;
导入android.view.view;
导入android.support.design.widget.NavigationView;
导入android.support.v4.view.GravityCompat;
导入android.support.v4.widget.DrawerLayout;
导入android.support.v7.app.ActionBarDrawerToggle;
导入android.support.v7.app.AppActivity;
导入android.support.v7.widget.Toolbar;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.widget.Button;
导入android.widget.ListView;
导入android.widget.Toast;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入java.io.IOException;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.util.ArrayList;
导入java.util.Calendar;
导入java.util.HashMap;
公共类MainActivity扩展AppCompatActivity实现NavigationView.OnNavigationItemSelectedListener{
//声明变量
JSONObject JSONObject;
JSONArray JSONArray;
列表视图列表视图;
ListViewAdapter适配器;
进程对话框;
ArrayList ArrayList;
静态字符串RANK=“RANK”;
静态字符串COUNTRY=“COUNTRY”;
静态字符串POPULATION=“POPULATION”;
静态字符串FLAG=“FLAG”;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*按钮btn=(按钮)findViewById(R.id.readmore);
btn.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
startActivity(新意图(MainActivity.this、appdetails.class));
}
});
*/
//执行下载JSON异步任务
新建下载JSON().execute();
Toolbar Toolbar=(Toolbar)findViewById(R.id.Toolbar);
设置支持操作栏(工具栏);
FloatingActionButton fab=(FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
Snackbar.make(查看“替换为您自己的操作”,Snackbar.LENGTH\u LONG)
.setAction(“Action”,null).show();
}
});
抽屉布局抽屉=(抽屉布局)findViewById(R.id.抽屉布局);
ActionBarDrawerToggle切换=新建ActionBarDrawerToggle(
这,抽屉,工具栏,R.string.navigation\u drawer\u open,R.string.navigation\u drawer\u close);
抽屉。设置抽屉定位器(开关);
toggle.syncState();
NavigationView NavigationView=(NavigationView)findViewById(R.id.nav_视图);
navigationView.setNavigationItemSelectedListener(此);
}
//下载JSON异步任务
私有类下载JSON扩展异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//创建一个progressdialog
mProgressDialog=新建ProgressDialog(MainActivity.this);
//设置进程对话框标题
//setTitle(“连接到服务器”);
//设置进程对话框消息
设置消息(“连接到应用服务器…”);
mProgressDialog.setUndeterminate(false);
//显示进度对话框
mProgressDialog.show();
}
@凌驾
受保护的Void doInBackground(Void…参数){
//创建一个数组
arraylist=新的arraylist();
//从给定的URL地址检索JSON对象
jsonobject=JSONfunctions
.getJSONfromURL(“http://localhost/json.txt");
试一试{
//在JSON中找到数组名称
jsonarray=jsonobject.getJSONArray(“世界人口”);
for(int i=0;i