我有一个Android程序。这将从服务器获取json并将图像解析为gridview。但是现在它将在logcat中提供ClassCastException,同时在模拟器/设备中运行它。我无法找到我的程序中发生此错误的位置,请有人帮我解决此问题
GridViewActivity.java
public class GridViewActivity extends Activity {
private Utils utils;
private GridViewImageAdapter adapter;
private GridView gridView;
private int columnWidth;
private String image_first[];
ProgressDialog pd;
Context activityContext = GridViewActivity.this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid_view);
gridView = (GridView) findViewById(R.id.grid_view);
utils = new Utils();
// Initilizing Grid View
InitilizeGridLayout();
ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected()) {
new HttpAsyncTask(activityContext).execute("http://vvvvvvvvvvvvvvv.com/Android_Test/index2.php"/*"http://hmkcode.appspot.com/rest/controller/get.json"*/);
} else {
final AlertDialog.Builder myDialogue = new AlertDialog.Builder(this);
myDialogue.setTitle("Connection Error!");
myDialogue.setMessage("This Application requires internet please check your connection settings..." );
myDialogue.setCancelable(false);
myDialogue.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
// Intent i = new Intent("android.settings.WIRELESS_SETTINGS");
// activityContext.startActivity(i);
}
});
AlertDialog dialog = myDialogue.create();
dialog.show();
}
}
private void InitilizeGridLayout() {
Resources r = getResources();
float padding = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
4, r.getDisplayMetrics());
columnWidth = (int) ((utils.getScreenWidth(this) - ((2 + 1) * padding)) /2);
gridView.setNumColumns(2);
gridView.setColumnWidth(columnWidth);
gridView.setStretchMode(GridView.NO_STRETCH);
//gridView.setPadding((int) padding, (int) padding, (int) padding,
// (int) padding);
gridView.setHorizontalSpacing((int) padding);
gridView.setVerticalSpacing((int) padding);
gridView.setGravity(Gravity.CENTER_HORIZONTAL);
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public class HttpAsyncTask extends AsyncTask<String, Void, String[]> {
public HttpAsyncTask(Context c) {
// Store the activity context
activityContext = c;
}
@Override
protected void onPreExecute() {
pd = new ProgressDialog(activityContext);
pd.setTitle("Please Wait");
pd.setMessage("Downloading images...");
pd.setCancelable(false);
pd.show();
}
@Override
protected String[] doInBackground(String... urls) {
String url = GET(urls[0]);
try {
JSONObject json = new JSONObject(url);
JSONArray articles = json.getJSONArray("images");
image_first =new String[json.getJSONArray("images").length()]; //initializtion
for(int i=0;i<json.getJSONArray("images").length();i++)
{
image_first[i] = (articles.getJSONObject(i).optString("image_first"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getApplicationContext());
// set title
alertDialogBuilder.setTitle("Connection Error");
// set dialog message
alertDialogBuilder
.setMessage("Check your internet connection!")
.setCancelable(false)
.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
GridViewActivity.this.finish();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
e.printStackTrace();
}
catch (NullPointerException e) {
// TODO Auto-generated catch block
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getApplicationContext());
// set title
alertDialogBuilder.setTitle("No inrternet available");
// set dialog message
alertDialogBuilder
.setMessage("Check your internet connection!")
.setCancelable(false)
.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
GridViewActivity.this.finish();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
return image_first;
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String[] result) {
pd.dismiss();
ArrayList<String> imagePaths = new ArrayList<String>(Arrays.asList(result));
// Gridview adapter
adapter = new GridViewImageAdapter(GridViewActivity.this, imagePaths,
(int) (columnWidth/1.2),getApplicationContext());
// setting grid view adapter
gridView.setAdapter(adapter);
}
}
}
GridViewImageAdapter.java
private Activity _activity;
private ArrayList<String> _filePaths = new ArrayList<String>();
private int imageWidth;
private Context _cntxt;
public GridViewImageAdapter(Activity activity, ArrayList<String> filePaths,
int imageWidth,Context cntxt) {
this._activity = activity;
this._filePaths = filePaths;
this.imageWidth = imageWidth;
this._cntxt = cntxt;
}
@Override
public int getCount() {
return this._filePaths.size();
}
@Override
public Object getItem(int position) {
return this._filePaths.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(_activity);
} else {
imageView = (ImageView) convertView;
}
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
imageWidth));
ImageLoader imgLoader = new ImageLoader(_cntxt);
// whenever you want to load an image from url
// call DisplayImage function
// url - image url to load
// loader - loader image, will be displayed before getting image
// image - ImageView
imgLoader.DisplayImage(_filePaths.get(position), imageView);
// image view click listener
imageView.setOnClickListener(new OnImageClickListener(position));
return imageView;
}
class OnImageClickListener implements OnClickListener {
int _postion;
// constructor
public OnImageClickListener(int position) {
this._postion = position;
}
@Override
public void onClick(View v) {
// on selecting grid view image
// launch full screen activity
Intent i = new Intent(_activity, FullScreenViewActivity.class);
i.putExtra("position", _postion);
i.putStringArrayListExtra("arraylist", _filePaths);
_activity.startActivity(i);
}
}
Activity act;
public void onBackPressed() {
// TODO Auto-generated method stub
KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
act.getWindow().openPanel(Window.FEATURE_OPTIONS_PANEL, event);
}
}
ImageLoader.java
public class ImageLoader {
MemoryCache memoryCache=new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
LinearLayout l;
Bitmap bitmap;
public ImageLoader(Context context){
fileCache=new FileCache(context);
executorService=Executors.newFixedThreadPool(5);
}
final int stub_id=R.drawable.loader;
public void DisplayImage(String url, ImageView imageView)
{
new HttpAsyncTask().execute(url);
imageViews.put(imageView, url);
Bitmap c = bitmap;
//memoryCache.get(url);
if(c!=null)
imageView.setImageBitmap(c);
else
{
// queuePhoto(url, imageView);
imageView.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
imageView.setImageResource(stub_id);
}
}
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex){
ex.printStackTrace();
if(ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=70;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
public class HttpAsyncTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... urls) {
Bitmap bm = getBitmap(urls[0]);
return bm;
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(Bitmap b) {
bitmap = b;
}
}
}
logcat的
06-06 03:07:03.170: D/AndroidRuntime(800): Shutting down VM
06-06 03:07:03.170: W/dalvikvm(800): threadid=1: thread exiting with uncaught exception (group=0x41465700)
06-06 03:07:03.440: E/AndroidRuntime(800): FATAL EXCEPTION: main
06-06 03:07:03.440: E/AndroidRuntime(800): java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams
06-06 03:07:03.440: E/AndroidRuntime(800): at android.widget.GridView.onMeasure(GridView.java:1042)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.view.View.measure(View.java:15848)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.view.View.measure(View.java:15848)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.view.View.measure(View.java:15848)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
06-06 03:07:03.440: E/AndroidRuntime(800): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2189)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.view.View.measure(View.java:15848)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1905)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1104)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1284)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.view.Choreographer.doFrame(Choreographer.java:532)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.os.Handler.handleCallback(Handler.java:730)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.os.Handler.dispatchMessage(Handler.java:92)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.os.Looper.loop(Looper.java:137)
06-06 03:07:03.440: E/AndroidRuntime(800): at android.app.ActivityThread.main(ActivityThread.java:5103)
06-06 03:07:03.440: E/AndroidRuntime(800): at java.lang.reflect.Method.invokeNative(Native Method)
06-06 03:07:03.440: E/AndroidRuntime(800): at java.lang.reflect.Method.invoke(Method.java:525)
06-06 03:07:03.440: E/AndroidRuntime(800): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
06-06 03:07:03.440: E/AndroidRuntime(800): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
06-06 03:07:03.440: E/AndroidRuntime(800): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:1)
据说您使用alreayd Gridview作为布局参数,但您所做的是将setLayoutParams
方法再次设置为ViewGroup.LayoutParams
,从而捕获异常。
<强>溶液强>
删除imageView.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT))
<强>样品:强> 改变这个
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth,
imageWidth));
以强>
imageView.setLayoutParams(new GridView.LayoutParams(GridView.LayoutParams.WRAP_CONTENT,
GridView.LayoutParams.WRAP_CONTENT));