您好我正在开发一个将成为Android启动器的应用程序此启动器中有三个不同的屏幕,第一个屏幕是一个应该导入的书架,并在设备的SD卡位置显示所有书籍第二个是计算器(工作正常!)第三个是一个家庭作业页面,你可以制作谷歌驱动器文档和闪存卡(也工作正常!!)当我运行我的代码时,我没有错误,当它在我的设备上启动时应用程序自动崩溃并在模拟器上。
继承我的Logcat:
11-23 15:05:06.314: E/SurfaceFlinger(323): ro.sf.lcd_density must be defined as a build property
11-23 15:05:15.084: E/Trace(3807): error opening trace file: No such file or directory (2)
11-23 15:05:15.254: E/AndroidRuntime(3807): FATAL EXCEPTION: main
11-23 15:05:15.254: E/AndroidRuntime(3807): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.d4a.tobias/it.gmariotti.android.examples.googleaccount.MainFrag}: java.lang.NullPointerException
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.os.Handler.dispatchMessage(Handler.java:99)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.os.Looper.loop(Looper.java:137)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread.main(ActivityThread.java:5041)
11-23 15:05:15.254: E/AndroidRuntime(3807): at java.lang.reflect.Method.invokeNative(Native Method)
11-23 15:05:15.254: E/AndroidRuntime(3807): at java.lang.reflect.Method.invoke(Method.java:511)
11-23 15:05:15.254: E/AndroidRuntime(3807): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-23 15:05:15.254: E/AndroidRuntime(3807): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-23 15:05:15.254: E/AndroidRuntime(3807): at dalvik.system.NativeStart.main(Native Method)
11-23 15:05:15.254: E/AndroidRuntime(3807): Caused by: java.lang.NullPointerException
11-23 15:05:15.254: E/AndroidRuntime(3807): at com.sibext.android_shelf.adapter.ShelfAdapter.setToListView(ShelfAdapter.java:70)
11-23 15:05:15.254: E/AndroidRuntime(3807): at it.gmariotti.android.examples.googleaccount.MainFrag.onCreate(MainFrag.java:78)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.Activity.performCreate(Activity.java:5104)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
11-23 15:05:15.254: E/AndroidRuntime(3807): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
11-23 15:05:15.254: E/AndroidRuntime(3807): ... 11 more
11-23 15:05:15.354: E/SurfaceFlinger(323): ro.sf.lcd_density must be defined as a build property
11-23 15:05:15.824: E/SurfaceFlinger(323): ro.sf.lcd_density must be defined as a build property
11-23 15:07:05.354: E/SurfaceFlinger(323): ro.sf.lcd_density must be defined as a build property
Heres MainFrag.java:
package it.gmariotti.android.examples.googleaccount;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.Toast;
import com.d4a.tobias.R;
import com.sibext.android_shelf.ImportBooks;
import com.sibext.android_shelf.adapter.ShelfAdapter;
public class MainFrag extends FragmentActivity{
private MyAdapter mAdapter;
private ViewPager mPager;
//Shelf
private static final String TARGET_DIRECTORY = "mnt/sdcard/shelf/";
private ListView list;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mainfrag);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
// TitlePageIndicator titleIndicator = (TitlePageIndicator) findViewById(R.id.titles);
// titleIndicator.setViewPager(mPager);
// pts=(PagerTitleStrip)findViewById(R.id.pager_title_strip);
//Shelf
File dir = new File(TARGET_DIRECTORY);
if(!dir.exists()){
dir.mkdirs();
//past here
addBooksFromAssetsToCard();
}else{
String files[] = dir.list();
if(files.length == 0){
//past here
addBooksFromAssetsToCard();
}
}
list = (ListView)findViewById(R.id.list);
ShelfAdapter adapter = new ShelfAdapter(this, TARGET_DIRECTORY);
adapter.setToListView(list);
}
public static class MyAdapter extends FragmentPagerAdapter {
String arr[]={"Calculator","Books","Homework"};
public MyAdapter(FragmentManager fm) {
super(fm);
}
@Override
public CharSequence getPageTitle(int position) {
// TODO Auto-generated method stub
return arr[position];
}
@Override
public int getCount() {
return arr.length;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Calculator();
case 1:
return new Book();
case 2:
return new Homework();
default:
return null;
}
}
}
//Shelf
public void addBooksFromAssetsToCard(){
List<String> books;
try {
books = getBooksFromAsset(getApplicationContext());
for(String book : books){
copyFromAssets(book);
}
} catch (Exception e) {
}
}
public List<String> getBooksFromAsset(Context ctx) throws Exception
{
AssetManager assetManager =ctx.getAssets();
String[] files = assetManager.list("books");
List<String> it=Arrays.asList(files);
return it;
}
public void copyFromAssets(String book)
{
AssetManager assetManager = getAssets();
String[] files = null;
InputStream in = null;
OutputStream out = null;
//String filename = "filename.ext";
try
{
in = assetManager.open("books/"+book);
out = new FileOutputStream(Environment.getExternalStorageDirectory()+File.separator+"/shelf/"+book);
Log.d("Copying...", ""+book);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch(Exception e)
{
Log.e("tag", "Failed to copy asset file: " + book, e);
}
}
public void copyFile(InputStream in, OutputStream out) throws Exception
{
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
Log.d("Copy_State", "Done...");
}
public void onImportClicked(View v){
Toast.makeText(getApplicationContext(), "Please wait...", Toast.LENGTH_LONG).show();
Intent in = new Intent(getApplicationContext(), ImportBooks.class);
startActivity(in);
}
}
EDIT ADDED Shelf Adapter.java:
package com.sibext.android_shelf.adapter;
import java.io.File;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.SparseArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.Toast;
import com.d4a.tobias.R;
import com.sibext.android_shelf.MainActivity;
import com.sibext.android_shelf.shelf.ShelfItem;
public class ShelfAdapter extends BaseAdapter {
private static final int ROW_COUNT_DEFAULT = 2;
private static final int ROW_COUNT_LAND_DEFAULT = 4;
private static final int ROW_HEIGHT_DEFAULT = 150;
private Context context;
private int rowCount = ROW_COUNT_DEFAULT;
private int rowCountLand = ROW_COUNT_LAND_DEFAULT;
private int rowHeight = ROW_HEIGHT_DEFAULT;
private SparseArray<LoadPreviewTask> taskPool;
private ArrayList<ShelfItem> items;
String PATH;
ShelfItem item;
public ShelfAdapter(Context context, String targetDir) {
this.context = context;
items = new ArrayList<ShelfItem>();
taskPool = new SparseArray<ShelfAdapter.LoadPreviewTask>();
if (targetDir == null || context == null) {
throw new NullPointerException("ShelfAdapter: wrong paramenters - " +
(targetDir == null ? "Target directory " : "Context ") + "is null");
}
File dir = new File(targetDir);
if(dir.exists() && dir.isDirectory()){
for(File f : dir.listFiles()){
if(f != null && f.getName().endsWith(".pdf")){
items.add(new ShelfItem(f));
}
}
}
}
public void setToListView(ListView list){
list.setDividerHeight(0);
list.setAdapter(this);
}
public void setRowCount(int rowCount, int rowCountLand) {
this.rowCount = rowCount;
this.rowCountLand = rowCountLand;
}
public void setRowHeight(int rowHeight) {
this.rowHeight = rowHeight;
}
@Override
public int getCount() {
int sub = getSubItemsCount();
return (int)(sub/getRowCount()) + (sub%getRowCount() == 0 ? 0 : 1);
}
public int getSubItemsCount(){
return items.size();
}
@Override
public ShelfItem getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
convertView = View.inflate(context, R.layout.shelf_row, null);
AbsListView.LayoutParams itemParams = new AbsListView.LayoutParams(
AbsListView.LayoutParams.MATCH_PARENT, rowHeight);
convertView.setLayoutParams(itemParams);
LinearLayout.LayoutParams subItemParams = getSubViewParams();
for(int i = 0; i < getRowCount(); i++){
View sub = getSubView(getSubPosition(position, i), null);
sub.setLayoutParams(subItemParams);
((ViewGroup)convertView).addView(sub);
holder.subViews.add(sub);
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
for(int i = 0; i < holder.subViews.size(); i++){
getSubView(getSubPosition(position, i), holder.subViews.get(i));
}
}
return convertView;
}
public View getSubView(final int position, View convertView){
final SubViewHolder holder;
if(convertView == null){
convertView = View.inflate(context, R.layout.shelf_item, null);
holder = new SubViewHolder();
holder.img = (ImageView)convertView.findViewById(R.id.shelf_item_image);
convertView.setTag(holder);
} else {
holder = (SubViewHolder)convertView.getTag();
}
if(position >= getSubItemsCount()){
holder.img.setImageBitmap(null);
return convertView;
}
item = getItem(position);
PATH = item.getFile().getAbsolutePath();
Bitmap preview = item.getPreviewFromSD();
if(preview != null){
holder.img.setImageBitmap(preview);
} else {
holder.img.setImageResource(R.drawable.ic_launcher);
LoadPreviewTask task = taskPool.get(holder.hashCode());
if (task != null) {
task.cancel(true);
taskPool.remove(holder.hashCode());
task = null;
}
task = new LoadPreviewTask(holder, rowHeight);
taskPool.put(holder.hashCode(), task);
task.execute(item);
}
holder.img.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final ShelfItem si = items.get(position);
/*Toast.makeText(context, "Item #" + position+"\n"+si.getFile().getAbsolutePath(), Toast.LENGTH_SHORT).show();
*/
final CharSequence[] items = {"View", "Delete"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Please choose:");
builder.setItems(items, new DialogInterface.OnClickListener() {
//Toast.makeText(getApplicationContext(), ""+items[0], Toast.LENGTH_SHORT).show();
public void onClick(DialogInterface dialog, int index) {
if(index == 0){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(si.getFile()),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
context.startActivity(intent);
}else if(index == 1){
File file = new File(si.getFile().getAbsoluteFile().toString());
boolean deleteStatus = file.delete();
if(deleteStatus){
Toast.makeText(context, "Deleted Successfully...", Toast.LENGTH_SHORT).show();
Intent in = new Intent(context, MainActivity.class);
context.startActivity(in);
}else{
Toast.makeText(context, "Unable to delete...", Toast.LENGTH_SHORT).show();
}
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
return convertView;
}
private int getSubPosition(int listItemPosition, int offset){
return listItemPosition * getRowCount() + offset;
}
private LinearLayout.LayoutParams getSubViewParams(){
LinearLayout.LayoutParams p = new LayoutParams(0, LayoutParams.MATCH_PARENT);
p.weight = 1f;
return p;
}
private int getRowCount() {
return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT
? rowCount : rowCountLand;
}
private static class ViewHolder{
public ArrayList<View> subViews;
public ViewHolder() {
this.subViews = new ArrayList<View>();
}
}
private static class SubViewHolder{
public ImageView img;
}
private class LoadPreviewTask extends AsyncTask<ShelfItem, Void, Bitmap>{
private SubViewHolder holder;
private int rowHeight;
public LoadPreviewTask(SubViewHolder holder, int rowHeight) {
super();
this.holder = holder;
this.rowHeight = rowHeight;
}
@Override
protected Bitmap doInBackground(ShelfItem... params) {
ShelfItem item = (ShelfItem)params[0];
Bitmap preview = item.getPreview(rowHeight);
item.savePreview(preview);
return preview;
}
@Override
protected void onPostExecute(final Bitmap result) {
if(isCancelled()){
holder = null;
return;
}
holder.img.setImageBitmap(result);
taskPool.remove(holder.hashCode());
}
}
}
我还是Android的新手,所以请不要评判,任何帮助将不胜感激
提前致谢
答案 0 :(得分:1)
list = (ListView)findViewById(R.id.list);
返回null,因为您的列表尚未创建。覆盖onViewCreated()
并将代码放在那里。
答案 1 :(得分:0)
你的问题在这里:adapter.setToListView(list);应该是这样的:list.setAdapter(...)但是你在ShelfAdapter.java上有另外的错误,你能把你从第65行写的东西复制到第70行吗?