我一直试图设置SimpleAdapter
,但应用程序一直在崩溃。我正在尝试从数据库中获取值并在ListView
中显示它。我用Google搜索并发现在SimpleAdapter
中我们可以将上下文称为getActivity()
以获取当前片段的上下文。我还发现我们可以为片段设置上下文,但我没有尝试过,因为我不知道如何设置片段的上下文。代码如下
disp.java
package com.example.festipedia_logo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockListFragment;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class disp extends SherlockFragment {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://192.168.43.77/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "price";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home2, container, false);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
return view;
// Get listview
//ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
}
// Response from Edit Product Activity
//@Override
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
// Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), productsList,
R.layout.home2, new String[] {
TAG_NAME},
new int[] { R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
MainActivity.java
package com.example.festipedia_logo;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.view.GravityCompat;
//@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@TargetApi(Build.VERSION_CODES.ECLAIR)
public class MainActivity extends SherlockFragmentActivity {
JSONParser jsonParser = new JSONParser();
EditText googlemap;
EditText eventwebsite;
EditText eventname;
EditText location;
EditText collegename;
private static String url_create_product = "http://192.168.0.103:8080/festipedia/create_product.php";
// Declare Variables
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
MenuListAdapter mMenuAdapter;
String[] title;
//String[] subtitle;
int icon;
//String a= "Add Event";
Fragment Home = new disp();
Fragment Add = new adding();
private CharSequence mDrawerTitle;
private CharSequence mTitle;
static int flag=0;
@Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null){
View root = findViewById(R.id.content_layout); //find your root view
loadTextViewState((ViewGroup)root, savedInstanceState); //load state
}
super.onCreate(savedInstanceState);
// Get the view from drawer_main.xml
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayUseLogoEnabled(false);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(false);
//getSupportActionBar().setIcon(R.drawable.fest);
//getSupportActionBar().setLogo(R.drawable.fest);
Drawable d=getResources().getDrawable(R.drawable.action);
getSupportActionBar().setBackgroundDrawable(d);
//getSupportActionBar().setBackgroundDrawable(fest);
FragmentTransaction ft1 = getSupportFragmentManager().beginTransaction();
ft1.replace(R.id.content_frame, Home);
ft1.commit();
// Get the Title
mTitle = mDrawerTitle = getTitle();
// Generate title
title = new String[] { "Home", "Add", "Categories",
"Event Organisers", "Search" };
// Generate subtitle
//subtitle = new String[] { "Subtitle Fragment 1", "Subtitle Fragment 2",
// "Subtitle Fragment 3" };
// Generate icon
icon = R.drawable.action_about;
// Locate DrawerLayout in drawer_main.xml
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// Locate ListView in drawer_main.xml
mDrawerList = (ListView) findViewById(R.id.listview_drawer);
// Set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// Pass string arrays to MenuListAdapter
mMenuAdapter = new MenuListAdapter(MainActivity.this, title,
icon);
// Set the MenuListAdapter to the ListView
mDrawerList.setAdapter(mMenuAdapter);
// Capture listview menu item click
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
// TODO Auto-generated method stub
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
// Set the title on the action when drawer open
getSupportActionBar().setTitle(mDrawerTitle);
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
//selectItem(0);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else if(!mDrawerLayout.isDrawerOpen(mDrawerList)){
mDrawerLayout.openDrawer(mDrawerList);
}
else{ Intent i = new Intent();
i.setClass(this,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}
// else if(item.getItemId()==R.id.action_settings)
// {
// Intent i=new Intent(MainActivity.this,Developer.class);
// startActivity(i);
//
// //setContentView(R.layout.drawer_main);
// }
return super.onOptionsItemSelected(item);
}
private String keyForTextView(TextView txt){
return "textView"+txt.getId();
}
/* go through all your views in your layout and save their values */
private void saveTextViewState(ViewGroup rootView, Bundle bundle){
int children = rootView.getChildCount();
for (int i = 0; i < children; i++) {
View view = rootView.getChildAt(i);
if (view instanceof TextView){
TextView txt = (TextView)view;
if (txt.getText() != null){
bundle.putString(keyForTextView(txt), txt.getText().toString());
}
}else if (view instanceof ViewGroup){
saveTextViewState((ViewGroup)view, bundle);
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
View root = findViewById(R.id.content_layout); //find your root view of your layout
saveTextViewState((ViewGroup)root, outState); //save state
super.onSaveInstanceState(outState);
}
private void loadTextViewState(ViewGroup rootView, Bundle bundle){
int children = rootView.getChildCount();
for (int i = 0; i < children; i++) {
View view = rootView.getChildAt(i);
if (view instanceof TextView){
TextView txt = (TextView)view;
String saved = bundle.getString(keyForTextView(txt));
txt.setText(saved);
}else if (view instanceof ViewGroup){
loadTextViewState((ViewGroup)view, bundle);
}
}
}
// ListView click listener in the navigation drawer
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
flag=0;ConnectivityManager cm;NetworkInfo activeNetwork;
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Locate Position
switch (position) {
case 0:
Intent i = new Intent(getApplicationContext(), mainpageact.class);
startActivity(i);
break;
case 1:
ft.replace(R.id.content_frame, Add);
break;/*
case 2:cm=(ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork=cm.getActiveNetworkInfo();
if((activeNetwork!=null && activeNetwork.isConnectedOrConnecting())==true){
ft.replace(R.id.content_frame, videos);}
else{
ft.replace(R.id.content_frame, videos);flag=1;}
break;
case 3:
cm=(ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork=cm.getActiveNetworkInfo();
if((activeNetwork!=null && activeNetwork.isConnectedOrConnecting())==true){
ft.replace(R.id.content_frame, tour);}
else{
ft.replace(R.id.content_frame, tour);flag=1;}
break;
case 4:
ft.replace(R.id.content_frame, sunday);
break;
case 5:
cm=(ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork=cm.getActiveNetworkInfo();
if((activeNetwork!=null && activeNetwork.isConnectedOrConnecting())==true){
ft.replace(R.id.content_frame, blog);}
else{
ft.replace(R.id.content_frame, blog);flag=1;}
break;
*/
}
ft.commit();
mDrawerList.setItemChecked(position, true);
// Get the title followed by the position
setTitle(title[position]);
// Close drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
private long mLastPress = 0;
@Override
public void onBackPressed() {
Toast onBackPressedToast = Toast.makeText(this, "Press once again to go to main menu", Toast.LENGTH_SHORT);
long currentTime = System.currentTimeMillis();
if (currentTime - mLastPress > 1000) {
onBackPressedToast.show();
FragmentTransaction ft1 = getSupportFragmentManager().beginTransaction();
ft1.replace(R.id.content_frame, Home);
ft1.commit();
// Closing all previous activities
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mLastPress = currentTime;
} else {
onBackPressedToast.cancel(); //Difference with previous answer. Prevent continuing showing toast after application exit
super.onBackPressed();
}
}
/* protected String doInBackground(String... args) {
String Eventname = eventname.getText().toString();
String Collegename = collegename.getText().toString();
String Location= location.getText().toString();
String Googlemap = googlemap.getText().toString();
String Eventwebsite = eventwebsite.getText().toString();
//String description = inputDesc.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("eventname", Eventname));
params.add(new BasicNameValuePair("googlemap", Googlemap));
params.add(new BasicNameValuePair("collegename", Collegename));
params.add(new BasicNameValuePair("eventwebsite",Eventwebsite));
params.add(new BasicNameValuePair("location", Location));
//params.add(new BasicNameValuePair("description", description));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame,new home1() , "Fest Content");
ft.commit();
return null;
}*/
}
编辑 Logcat(应用程序也崩溃在Sherlock片段中)
03-19 20:23:59.996: E/Buffer Error(14807): Error converting result java.lang.NullPointerException: lock == null
03-19 20:24:00.011: E/JSON Parser(14807): Error parsing data org.json.JSONException: End of input at character 0 of
03-19 20:24:00.021: E/AndroidRuntime(14807): FATAL EXCEPTION: AsyncTask #1
03-19 20:24:00.021: E/AndroidRuntime(14807): Process: com.example.festipedia_logo, PID: 14807
03-19 20:24:00.021: E/AndroidRuntime(14807): java.lang.RuntimeException: An error occured while executing doInBackground()
03-19 20:24:00.021: E/AndroidRuntime(14807): at android.os.AsyncTask$3.done(AsyncTask.java:300)
03-19 20:24:00.021: E/AndroidRuntime(14807): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
03-19 20:24:00.021: E/AndroidRuntime(14807): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
03-19 20:24:00.021: E/AndroidRuntime(14807): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
03-19 20:24:00.021: E/AndroidRuntime(14807): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-19 20:24:00.021: E/AndroidRuntime(14807): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-19 20:24:00.021: E/AndroidRuntime(14807): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-19 20:24:00.021: E/AndroidRuntime(14807): at java.lang.Thread.run(Thread.java:841)
03-19 20:24:00.021: E/AndroidRuntime(14807): Caused by: java.lang.NullPointerException
03-19 20:24:00.021: E/AndroidRuntime(14807): at com.example.festipedia_logo.disp$LoadAllProducts.doInBackground(disp.java:106)
03-19 20:24:00.021: E/AndroidRuntime(14807): at com.example.festipedia_logo.disp$LoadAllProducts.doInBackground(disp.java:1)
03-19 20:24:00.021: E/AndroidRuntime(14807): at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-19 20:24:00.021: E/AndroidRuntime(14807): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-19 20:24:00.021: E/AndroidRuntime(14807): ... 4 more
03-19 20:24:00.436: E/WindowManager(14807): android.view.WindowLeaked: Activity com.example.festipedia_logo.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42fe6ef8 V.E..... R......D 0,0-1026,288} that was originally added here
03-19 20:24:00.436: E/WindowManager(14807): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:456)
03-19 20:24:00.436: E/WindowManager(14807): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:267)
03-19 20:24:00.436: E/WindowManager(14807): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
03-19 20:24:00.436: E/WindowManager(14807): at android.app.Dialog.show(Dialog.java:288)
03-19 20:24:00.436: E/WindowManager(14807): at com.example.festipedia_logo.disp$LoadAllProducts.onPreExecute(disp.java:89)
03-19 20:24:00.436: E/WindowManager(14807): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
03-19 20:24:00.436: E/WindowManager(14807): at android.os.AsyncTask.execute(AsyncTask.java:535)
03-19 20:24:00.436: E/WindowManager(14807): at com.example.festipedia_logo.disp.onCreateView(disp.java:64)
03-19 20:24:00.436: E/WindowManager(14807): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
03-19 20:24:00.436: E/WindowManager(14807): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
03-19 20:24:00.436: E/WindowManager(14807): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
03-19 20:24:00.436: E/WindowManager(14807): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
03-19 20:24:00.436: E/WindowManager(14807): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
03-19 20:24:00.436: E/WindowManager(14807): at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:570)
03-19 20:24:00.436: E/WindowManager(14807): at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1189)
03-19 20:24:00.436: E/WindowManager(14807): at android.app.Activity.performStart(Activity.java:5436)
03-19 20:24:00.436: E/WindowManager(14807): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
03-19 20:24:00.436: E/WindowManager(14807): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
03-19 20:24:00.436: E/WindowManager(14807): at android.app.ActivityThread.access$900(ActivityThread.java:161)
03-19 20:24:00.436: E/WindowManager(14807): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
03-19 20:24:00.436: E/WindowManager(14807): at android.os.Handler.dispatchMessage(Handler.java:102)
03-19 20:24:00.436: E/WindowManager(14807): at android.os.Looper.loop(Looper.java:157)
03-19 20:24:00.436: E/WindowManager(14807): at android.app.ActivityThread.main(ActivityThread.java:5356)
03-19 20:24:00.436: E/WindowManager(14807): at java.lang.reflect.Method.invokeNative(Native Method)
03-19 20:24:00.436: E/WindowManager(14807): at java.lang.reflect.Method.invoke(Method.java:515)
03-19 20:24:00.436: E/WindowManager(14807): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
03-19 20:24:00.436: E/WindowManager(14807): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
03-19 20:24:00.436: E/WindowManager(14807): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:1)
您的内容必须包含其属性为的ListView 'android.R.id.list'
由于您要扩展ListFragment
,您的布局应包含ID为@android:id/list
编辑:
The method setListAdapter(ListAdapter) is undefined for the type new Runnable(){}
由于您从SherlockListFragment
更改为SherlockFragment
,因此setListAdapter不再可用。您需要一个ListView
对象,您可以在其上调用ListView.setAdapter