Сбой startActivity при обработке растровых изображений размером 5 КБ
Я не могу найти решение после серфинга в Интернете. У меня есть два класса активности: ImageActivity (MAIN) и ChunkImageActivity. Другой класс расширяет BaseAdapter, и он вызывается ChunkImageActivity. Первая содержит три кнопки, с помощью которых я выбираю количество частей, на которые должен делиться ImageView. Вторая вызывается ImageActivity, когда нажата одна из трех кнопок. Проблема возникает, когда намерение запускает ChunkImageActivity, которое имеет GridView в setContentView (R.layout.image_grid);
1. ImageActivity
package com.example.laptop.gridsplitter;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class ImageActivity extends Activity implements View.OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*
* Here three, four and five are the id's of the buttons declared as
* the contents of the sliding drawer.
* See main.xml for clarity
*/
Button b1 = (Button) findViewById(R.id.three);
Button b2 = (Button) findViewById(R.id.four);
Button b3 = (Button) findViewById(R.id.five);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
}
@Override
public void onClick(View view){
//chunkNumbers is to tell how many chunks the image should split
int chunkNumbers = 0;
/*
* switch-case is used to find the button clicked
* and assigning the actual value to chunkNumbers variable
*/
switch (view.getId()) {
case R.id.three:
chunkNumbers = 9 ;
break;
case R.id.four:
chunkNumbers = 16 ;
break;
case R.id.five:
chunkNumbers = 25 ;
}
//Getting the source image to split
ImageView image = (ImageView) findViewById(R.id.source_image);
splitImage(image, chunkNumbers);
}
private void splitImage(ImageView image, int chunkNumbers) {
//For the number of rows and columns of the grid to be displayed
int rows,cols;
//For height and width of the small image chunks
int chunkHeight,chunkWidth;
//To store all the small image chunks in bitmap format in this list
ArrayList<Bitmap> chunkedImages = new ArrayList<Bitmap>(chunkNumbers);
//Getting the scaled bitmap of the source image
BitmapDrawable drawable = (BitmapDrawable) image.getDrawable();
Bitmap bitmap = drawable.getBitmap();
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap,
bitmap.getWidth(),bitmap.getHeight(), true);
rows = cols = (int) Math.sqrt(chunkNumbers);
chunkHeight = bitmap.getHeight()/rows;
chunkWidth = bitmap.getWidth()/cols;
//xCoord and yCoord are the pixel positions of the image chunks
int yCoord = 0;
for(int x=0; x<rows; x++){
int xCoord = 0;
for(int y=0; y<cols; y++){
chunkedImages.add(Bitmap.createBitmap(scaledBitmap, xCoord, yCoord, chunkWidth,
chunkHeight));
xCoord += chunkWidth;
}
yCoord += chunkHeight;
}
//Start a new activity to show these chunks into a grid
Intent intent = new Intent(ImageActivity.this, ChunkedImageActivity.class);
intent.putParcelableArrayListExtra("image chunks", chunkedImages);
ImageActivity.this.startActivity(intent);
}
}
Я совершенно уверен, что эти последние пять строк и код splitImage являются правильными
** 2. ChunkImageActivity**
package com.example.laptop.gridsplitter;
import java.util.ArrayList;
import java.util.ArrayList;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.GridView;
//This activity will display the small image chunks into a grid view
public class ChunkedImageActivity extends Activity {
public void onCreate(Bundle bundle){
super.onCreate(bundle);
setContentView(R.layout.image_grid);
//Getting the image chunks sent from the previous activity
ArrayList<Bitmap> imageChunks = getIntent().getParcelableArrayListExtra("image
chunks");
//Getting the grid view and setting an adapter to it
GridView grid = (GridView) findViewById(R.id.gridview);
grid.setAdapter(new ImageAdapter(this, imageChunks));
grid.setNumColumns((int) Math.sqrt(imageChunks.size()));
}
}
**3. ImageAdapter**
package com.example.laptop.gridsplitter;
import java.util.ArrayList;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
//The adapter class associated with the ChunkedImageActivity class
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Bitmap> imageChunks;
private int imageWidth, imageHeight;
//constructor
public ImageAdapter(Context c, ArrayList<Bitmap> images){
mContext = c;
imageChunks = images;
imageWidth = images.get(0).getWidth();
imageHeight = images.get(0).getHeight();
}
@Override
public int getCount() {
return imageChunks.size();
}
@Override
public Object getItem(int position) {
return imageChunks.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView image;
if(convertView == null){
image = new ImageView(mContext);
/*
* NOTE: I have set imageWidth - 10 and imageHeight
* as arguments to LayoutParams class.
* But you can take anything as per your requirement
*/
image.setLayoutParams(new GridView.LayoutParams(imageWidth - 10 , imageHeight));
image.setPadding(0, 0, 0, 0);
}else{
image = (ImageView) convertView;
}
image.setImageBitmap(imageChunks.get(position));
return image;
}
}
** MANIFEST**
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.laptop.gridsplitter"
>
<application
android:hardwareAccelerated="true"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".ImageActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ChunkedImageActivity">
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</activity>
</application>
</manifest>
** LAYOUT**
1. main.xml:
' <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView android:src="@drawable/katewinslet"
android:id="@+id/source_image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
<SlidingDrawer android:id="@+id/split_slider"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:topOffset="230dip"
android:handle="@+id/split_image"
android:content="@+id/split_numbers">
<Button android:id="@id/split_image"
android:text="@string/button_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"/>
<LinearLayout android:id="@id/split_numbers"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button android:id="@+id/three"
android:text="@string/three"
android:clickable="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button android:id="@+id/four"
android:text="@string/four"
android:clickable="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button android:id="@+id/five"
android:text="@string/five"
android:clickable="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</SlidingDrawer>
'
2. image_grid.xml:
'<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:numColumns="auto_fit">
</GridView>'
Все, что я получил, это черный экран после запуска ChunkImageActivity. Я сомневаюсь, что проблема заключается в обработке растрового изображения, поскольку оно составляет менее 50 КБ. Не могли бы вы мне помочь?
NB: я использовал Toast.makeText ранее, и я заметил, что пока splitImage все работает хорошо. Проблема приходит с обработкой arraylist или началом новой деятельности.
1 ответ
Вы пробовали отладку и проверку, правильно ли создается и правильно ли передается массив-адаптер в адаптер изображения?