我是android编程的新手,我不确定代码有什么问题。请查看并提出一些意见或修复!预先感谢您!
练习 fragment :
public class ExerciseFragment<MainActivity> extends Fragment {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String TITLE = "title";
static String DIFFICULTY = "difficulty";
static String CATEGORY = "category";
static String IMAGE = "image";
static String DESCRIPTION ="description";
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_exercise, container, false);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
return rootView;
}// DownloadJSON AsyncTask
public class DownloadJSON extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle("Exercise Tips!");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progress dialog
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://beta.json-generator.com/api/json/get/MZZHIfy");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("exercisecategory");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrieve JSON Objects
map.put("title", jsonobject.getString("title"));
map.put("difficulty", jsonobject.getString("difficulty"));
map.put("category", jsonobject.getString("category"));
map.put("description", jsonobject.getString("description"));
map.put("image", jsonobject.getString("image"));
// 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 fragment_exercise.xml
listview = (ListView) getView().findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(getActivity().getApplicationContext(), arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
ListViewAdapter:
@SuppressLint("ViewHolder")
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter (Context context, ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView title;
TextView difficulty;
TextView category;
TextView description;
ImageView image;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.exe_list, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in exe_list.xml
title = (TextView) itemView.findViewById(R.id.title);
difficulty = (TextView) itemView.findViewById(R.id.difficulty);
category = (TextView) itemView.findViewById(R.id.category);
description = (TextView) itemView.findViewById(R.id.description);
// Locate the ImageView in exe_list.xml
image = (ImageView) itemView.findViewById(R.id.image);
// Capture position and set results to the TextViews
title.setText(resultp.get(ExerciseFragment.TITLE));
difficulty.setText(resultp.get(ExerciseFragment.DIFFICULTY));
category.setText(resultp.get(ExerciseFragment.CATEGORY));
description.setText(resultp.get(ExerciseFragment.DESCRIPTION));
// Capture position and set results to the ImageView
// Passes images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(ExerciseFragment.IMAGE), image);
Log.e("TEST","message here1");
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Log.e("TEST","message here2");
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
Log.e("TEST","message here3");
// Pass all data title
intent.putExtra("title", resultp.get(ExerciseFragment.TITLE));
Log.e("TEST","message here4");
// Pass all data difficulty
intent.putExtra("difficulty", resultp.get(ExerciseFragment.DIFFICULTY));
Log.e("TEST","message here5");
// Pass all data category
intent.putExtra("category",resultp.get(ExerciseFragment.CATEGORY));
Log.e("TEST","message here6");
// Pass all data description
intent.putExtra("description", resultp.get(ExerciseFragment.DESCRIPTION));
Log.e("TEST","message here7");
// Pass all data image
intent.putExtra("image", resultp.get(ExerciseFragment.IMAGE));
Log.e("TEST","message here8");
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
SingleItemView:
public class SingleItemView extends Activity {
// Declare Variables
String title;
String difficulty;
String category;
String description;
String image;
String position;
ImageLoader imageLoader = new ImageLoader(this);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from exe_single.xml
setContentView(R.layout.exe_single);
Intent i = getIntent();
// Get the result of title
title = i.getStringExtra("title");
// Get the result of difficulty
difficulty = i.getStringExtra("difficulty");
// Get the result of category
category = i.getStringExtra("category");
// Get the result of description
description = i.getStringExtra("description");
// Get the result of image
image = i.getStringExtra("image");
// Locate the TextViews in exe_single.xml
TextView txttitle = (TextView) findViewById(R.id.title);
TextView txtdifficulty = (TextView) findViewById(R.id.difficulty);
TextView txtcategory = (TextView) findViewById(R.id.category);
TextView txtdescription = (TextView) findViewById(R.id.description);
// Locate the ImageView in exe_single.xml
ImageView imgimage = (ImageView) findViewById(R.id.image);
// Set results to the TextViews
txttitle.setText(title);
txtdifficulty.setText(difficulty);
txtcategory.setText(category);
txtdescription.setText(description);
// Capture position and set results to the ImageView
// Passes image images URL into ImageLoader.class
imageLoader.DisplayImage(image, imgimage);
}
日志猫:
05-11 14:30:26.400: I/PGA(4771): Attempting to create new SOCKET connectionn pid = 4771, tid = 4771
05-11 14:30:26.410: I/PGA(4771): New SOCKET connection: com.fwong.eatright (pid 4771, tid 4771)
05-11 14:30:31.620: I/MemoryCache(4771): MemoryCache will use up to 48.0MB
05-11 14:30:31.640: D/dalvikvm(4771): GC_FOR_ALLOC freed 397K, 13% free 3511K/4004K, paused 10ms, total 10ms
05-11 14:30:31.650: E/TEST(4771): message here1
05-11 14:30:31.670: E/TEST(4771): message here1
05-11 14:30:31.680: E/TEST(4771): message here1
05-11 14:30:31.680: I/MemoryCache(4771): cache size=50784 length=1
05-11 14:30:31.820: I/MemoryCache(4771): cache size=108384 length=2
05-11 14:30:32.000: I/MemoryCache(4771): cache size=147104 length=3
05-11 14:30:33.580: E/TEST(4771): message here2
05-11 14:30:33.580: E/TEST(4771): message here3
05-11 14:30:33.580: E/TEST(4771): message here4
05-11 14:30:33.580: E/TEST(4771): message here5
05-11 14:30:33.580: E/TEST(4771): message here6
05-11 14:30:33.580: E/TEST(4771): message here7
05-11 14:30:33.580: E/TEST(4771): message here8
05-11 14:30:33.580: D/AndroidRuntime(4771): Shutting down VM
05-11 14:30:33.580: W/dalvikvm(4771): threadid=1: thread exiting with uncaught exception (group=0x55d4fb20)
05-11 14:30:33.580: I/Process(4771): Sending signal. PID: 4771 SIG: 9
05-11 14:30:33.580: D/AndroidRuntime(4771): procName from cmdline: com.fwong.eatright
05-11 14:30:33.580: E/AndroidRuntime(4771): in writeCrashedAppName, pkgName :com.fwong.eatright
05-11 14:30:33.580: D/AndroidRuntime(4771): file written successfully with content: com.fwong.eatright StringBuffer : ;com.fwong.eatright
05-11 14:30:33.580: E/AndroidRuntime(4771): FATAL EXCEPTION: main
05-11 14:30:33.580: E/AndroidRuntime(4771): Process: com.fwong.eatright, PID: 4771
05-11 14:30:33.580: E/AndroidRuntime(4771): android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
05-11 14:30:33.580: E/AndroidRuntime(4771): at android.app.ContextImpl.startActivity(ContextImpl.java:1034)
05-11 14:30:33.580: E/AndroidRuntime(4771): at android.app.ContextImpl.startActivity(ContextImpl.java:1021)
05-11 14:30:33.580: E/AndroidRuntime(4771): at android.content.ContextWrapper.startActivity(ContextWrapper.java:311)
05-11 14:30:33.580: E/AndroidRuntime(4771): at com.fwong.eatright.exercise.ListViewAdapter$1.onClick(ListViewAdapter.java:107)
05-11 14:30:33.580: E/AndroidRuntime(4771): at android.view.View.performClick(View.java:4443)
05-11 14:30:33.580: E/AndroidRuntime(4771): at android.view.View$PerformClick.run(View.java:18442)
05-11 14:30:33.580: E/AndroidRuntime(4771): at android.os.Handler.handleCallback(Handler.java:733)
05-11 14:30:33.580: E/AndroidRuntime(4771): at android.os.Handler.dispatchMessage(Handler.java:95)
05-11 14:30:33.580: E/AndroidRuntime(4771): at android.os.Looper.loop(Looper.java:136)
05-11 14:30:33.580: E/AndroidRuntime(4771): at android.app.ActivityThread.main(ActivityThread.java:5021)
05-11 14:30:33.580: E/AndroidRuntime(4771): at java.lang.reflect.Method.invokeNative(Native Method)
05-11 14:30:33.580: E/AndroidRuntime(4771): at java.lang.reflect.Method.invoke(Method.java:515)
05-11 14:30:33.580: E/AndroidRuntime(4771): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
05-11 14:30:33.580: E/AndroidRuntime(4771): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
05-11 14:30:33.580: E/AndroidRuntime(4771): at dalvik.system.NativeStart.main(Native Method)
最佳答案
您正在使用 ApplicationContext 来启动 Activity。为此,您需要使用 ActivityContext。
在初始化适配器更改的练习 fragment 中:
adapter = new ListViewAdapter(getActivity().getApplicationContext(), arraylist);
致:
adapter = new ListViewAdapter(getActivity(), arraylist);
如果这不起作用,您还可以尝试在 ListView
上设置 OnItemClickListener
而不是 OnClickListener
在 >项目 View
。因此,请删除您在适配器的 getView()
方法中设置的 OnClickListener
。相反,当您初始化适配器并将其设置为 ListView
时,还会调用 ListView.setOnItemClickListener(new AdapterView.OnItemClickListener)
并将您的功能粘贴到此处。此监听器用作处理列表项选择的最佳实践。
当您按照自己的方式而不是我上面描述的方式进行操作时,会发生什么情况:每次加载 View 时(自从您使用 ListView 以来,这已经是很多次了),应用程序需要分配内存来设置OnClickListener。现在您只需分配一次。
关于java - 选择 ListView 项目后应用程序自动关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30160904/