我尝试获取mysql数据库信息,并通过单击导航视图中的项目在片段中显示信息,为此我使用Bundle()。
这是我的主要活动:
String JSON_STRING;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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);
displayView(R.id.nav_random);
}
public void displayView(int viewId) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (viewId) {
case R.id.nav_random:
fragment = new Random();
title = "RANDOM";
break;
case R.id.nav_podium:
fragment = new Podium();
title = "PODIUM";
break;
case R.id.nav_sport:
fragment = new Sport();
title = "SPORT";
break;
case R.id.nav_videogames:
fragment = new Games();
title = "GAMES";
break;
case R.id.nav_socialnetwork:
fragment = new SocialNetwork();
title = "SOCIAL NETWORKS";
break;
case R.id.nav_heart:
fragment = new Heart();
title = "FAVORITES";
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (fragment instanceof Podium) {
//Toast.makeText(getApplicationContext(), "Test", Toast.LENGTH_LONG).show();
new BackgroundTask().execute();
Bundle args = new Bundle();
args.putString("JSON_DATA", getIntent().getExtras().getString(JSON_STRING));
fragment.setArguments(args);
}
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
// set the toolbar title
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle("Mon titre");
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
@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) {
Intent myIntent = new Intent(getApplicationContext(), FacebookConnectActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
displayView(item.getItemId());
return true;
}
class BackgroundTask extends AsyncTask<Void, Void, String> {
String json_url;
@Override
protected void onPreExecute() {
json_url = "http://firejackal.fr/script.php";
}
@Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()) != null) {
stringBuilder.append(JSON_STRING + "n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
这是我的碎片"吊舱"代码:
String JSON_STRING;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;
public Podium() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_podium,null);
listView = (ListView) v.findViewById(R.id.listview);
Bundle args = getArguments();
JSON_STRING = args.getString("JSON_DATA");
contactAdapter = new ContactAdapter(this.getContext(),R.layout.row_layout);
listView.setAdapter(contactAdapter);
try {
jsonObject = new JSONObject(JSON_STRING);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String id_user_post, place_post, date_post;
while(count < jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
id_user_post = JO.getString("id_user_post");
place_post = JO.getString("place_post");
date_post = JO.getString("date_post");
Contacts contacts = new Contacts(id_user_post, place_post, date_post);
contactAdapter.add(contacts);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
// Inflate the layout for this fragment
return v;
}
我有一个NullPointerException:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at fr.djey.trollstory.MainPageActivity.displayView(MainPageActivity.java:106)
at fr.djey.trollstory.MainPageActivity.onNavigationItemSelected(MainPageActivity.java:162)
在MainActivity中的这两行上:
args.putString("JSON_DATA", getIntent().getExtras().getString(JSON_STRING));
和
displayView(item.getItemId());
但我不明白为什么,因为我在项目Podium上执行AsyncTask,所以JSON_STRING不应该为null?
编辑
如果我尝试args.putString("JSON_DATA", JSON_STRING);
我得到这个错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()'
在片段中的这一行:
jsonObject = new JSONObject(JSON_STRING);
看起来像是在这一行中抛出的:
args.putString("JSON_DATA", getIntent().getExtras().getString(JSON_STRING));
异常是说存储在getIntent.getExtras()
的Bundle为null。该捆绑包在哪里添加到意图中?
试试这个代码。如果这对你不起作用,请告诉我。
Bundle bundle= getIntent().getExtras;
Bundle args = new Bundle();
args.putString("JSON_DATA", bundle.getString(JSON_STRING));
fragment.setArguments(args);