在singleitem视图中没有显示任何内容

时间:2015-11-26 11:10:47

标签: android parse-platform android-listview

我有一个应用程序从解析中检索信息并显示到列表视图中,但是当运行应用程序并单击列表视图项时,它会打开一个新活动并显示来自parse.com的一些图像和文本但是它没有显示下面的图像

enter image description here

这是我的代码

main activity.java

public class MainActivity extends Activity 
{
ListView listview;
List<ParseObject> ob;
ProgressDialog mProgressDialog;
FinalAdapter adapter;
private List<CodeList> codelist = null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.beg_layout);

    new RemoteDataTask().execute();
}

private class RemoteDataTask extends AsyncTask<Void, Void, Void>
{
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create a progressdialog
        mProgressDialog = new ProgressDialog(MainActivity.this);
        // Set progressdialog title
        mProgressDialog.setTitle("Testing");
        // Set progressdialog message
        mProgressDialog.setMessage("Loading. Please wait this may take few moments ....");
        mProgressDialog.setIndeterminate(true);
        // Show progressdialog
        mProgressDialog.show();
    }


    @Override
    protected Void doInBackground(Void... params)
    {
        codelist = new ArrayList<CodeList>();
        try{
            ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
                "BeginnerActivity");
            query.orderByAscending("_created_at");
            ob = query.find();
            for(ParseObject begactivity : ob){

                ParseFile listimg = (ParseFile) begactivity.get("alphabetimg");
                ParseFile levelimg = (ParseFile) begactivity.get("levelimg");
                ParseFile apiimg = (ParseFile) begactivity.get("apiimg");
                ParseFile descimgone = (ParseFile) begactivity.get("descimgone");
                ParseFile descimgtwo = (ParseFile) begactivity.get("descimgtwo");


                CodeList map = new CodeList();
                map.setListHeading((String) begactivity.get("listheading"));
                map.setSingleItemHeading((String) begactivity.get("heading"));
                map.setDescription((String) begactivity.get("subheading"));
                map.setApiText((String) begactivity.get("apitext"));
                map.setFinalCodeText((String) begactivity.get("codetext"));

                map.setAlphabetimg(listimg.getUrl());
                map.setLevelImg(levelimg.getUrl());
                map.setApiImg(apiimg.getUrl());
                map.setPreviewImgOne(descimgone.getUrl());
                map.setPreviewImgTwo(descimgtwo.getUrl());
                codelist.add(map);
            }
        }catch(ParseException e){
            Log.e("Error", e.getMessage());
            e.printStackTrace();

        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // Locate the listview in listview_main.xml
        listview = (ListView) findViewById(R.id.beg_layoutListView);
        // Pass the results into ListViewAdapter.java
        adapter = new FinalAdapter(MainActivity.this,
                                   codelist);
        // Binds the Adapter to the ListView
        listview.setAdapter(adapter);
        // Close the progressdialog
        mProgressDialog.dismiss();
    }



}

}

codelist.java

public class CodeList
{
private String alphabetimg;
private String listHeading;
private String levelImg;
private String singleItemHeading;
private String description;
private String apiImg;
private String apiText;

private String previewImgOne;
private String previewImgTwo;
private String finalCodeText;



public void setAlphabetimg(String alphabetimg)
{
    this.alphabetimg = alphabetimg;
}

public String getAlphabetimg()
{
    return alphabetimg;
}

public void setListHeading(String listHeading)
{
    this.listHeading = listHeading;
}

public String getListHeading()
{
    return listHeading;
}

public void setLevelImg(String levelImg)
{
    this.levelImg = levelImg;
}

public String getLevelImg()
{
    return levelImg;
}

public void setSingleItemHeading(String singleItemHeading)
{
    this.singleItemHeading = singleItemHeading;
}

public String getSingleItemHeading()
{
    return singleItemHeading;
}

public void setDescription(String description)
{
    this.description = description;
}

public String getDescription()
{
    return description;
}

public void setApiImg(String apiImg)
{
    this.apiImg = apiImg;
}

public String getApiImg()
{
    return apiImg;
}

public void setApiText(String apiText)
{
    this.apiText = apiText;
}

public String getApiText()
{
    return apiText;
}


public void setPreviewImgOne(String previewImgOne)
{
    this.previewImgOne = previewImgOne;
}

public String getPreviewImgOne()
{
    return previewImgOne;
}

public void setPreviewImgTwo(String previewImgTwo)
{
    this.previewImgTwo = previewImgTwo;
}

public String getPreviewImgTwo()
{
    return previewImgTwo;
}

public void setFinalCodeText(String finalCodeText)
{
    this.finalCodeText = finalCodeText;
}

public String getFinalCodeText()
{
    return finalCodeText;
}

}

解析application.java

public class ParseApplication extends Application {

@Override
public void onCreate() {
    super.onCreate();

    // Add your initialization code here
    Parse.initialize(this, "4rOrqK23m0nVq187Of3rhDe0TK1R7FObdBWhfX10", "afKA4B9ohvk3M9pZNv9qK2ypbrdOpXi0FPnrXOu6");

    ParseUser.enableAutomaticUser();
    ParseACL defaultACL = new ParseACL();

    // If you would like all objects to be private by default, remove this line.
    defaultACL.setPublicReadAccess(true);

    ParseACL.setDefaultACL(defaultACL, true);
}

 }

final adapter.java

public class FinalAdapter extends BaseAdapter
{
Context context;
    LayoutInflater inflater;
    ImageLoader imageLoader;
private List<CodeList> codeList = null;
private ArrayList<CodeList> arraylist;

public FinalAdapter(Context context,
                    List<CodeList> codeList) {
    this.context = context;
    this.codeList = codeList;
    inflater = LayoutInflater.from(context);
    this.arraylist = new ArrayList<CodeList>();
    this.arraylist.addAll(codeList);
    imageLoader = new ImageLoader(context);

}

public class ViewHolder{
    TextView listHeading;
    ImageView alphabetList;
}


@Override
public int getCount()
{
    return codeList.size();
}

@Override
public Object getItem(int position)
{
    return codeList.get(position);
}

@Override
public long getItemId(int position)
{
    return position;
}

@Override
public View getView(final int position, View view, ViewGroup parent)
{
    final ViewHolder holder;
    if(view == null){
        holder = new ViewHolder();
        view = inflater.inflate(R.layout.beg_list_item,null);
        holder.listHeading = (TextView) view.findViewById(R.id.beg_list_itemTextView);
        holder.alphabetList = (ImageView) view.findViewById(R.id.beg_list_itemImageView);
        view.setTag(holder);

    }else{
        holder = (ViewHolder) view.getTag();
    }
    holder.listHeading.setText(codeList.get(position).getListHeading());
    imageLoader.DisplayImage(codeList.get(position).getAlphabetimg(),
                             holder.alphabetList);



    view.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View arg0){
                Intent intent = new Intent(context, SingleItemView.class);

                intent.putExtra("listheading",
                                (codeList.get(position).getListHeading()));
                intent.putExtra("alphabetimg",
                                (codeList.get(position).getAlphabetimg()));
                // Start SingleItemView Class
                context.startActivity(intent);

            }
        });                 

    return view;
}

 }

singleitemview.java

public class SingleItemView extends Activity.  
{
    String heading;
    String subHeading;
    String levelImg;
String apiImg;
    String apiText;
    String descImgOne;
    String descImgTwo;
String codeText;
ImageLoader imgloader = new ImageLoader(this);

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.singleitemview);

    Intent i = getIntent();

    heading= i.getStringExtra("heading");
    subHeading = i.getStringExtra("subheading");
    levelImg = i.getStringExtra("levelimg");
    apiImg = i.getStringExtra("apiimg");
    apiText = i.getStringExtra("apitext");
    descImgOne = i.getStringExtra("descimgone");
    descImgTwo = i.getStringExtra("descimgtwo");
    codeText = i.getStringExtra("codetext");


    TextView headingtxt = (TextView)findViewById(R.id.singleitemheading);
    TextView subheadingtxt = (TextView)findViewById(R.id.singleitemsubheading);
    TextView apitxt = (TextView)findViewById(R.id.singleitemviewapitext);
    TextView codetxt = (TextView) findViewById(R.id.singleitemviewcodetext);

    ImageView level =(ImageView) findViewById(R.id.levelimg);
    ImageView api =(ImageView) findViewById(R.id.singleitemviewapiimg);
    ImageView descone =(ImageView) findViewById(R.id.descriptionimgone);
    ImageView desctwo =(ImageView) findViewById(R.id.descriptionimgtwo);

    headingtxt.setText(heading);
    subheadingtxt.setText(subHeading);
    apitxt.setText(apiText);
    codetxt.setText(codeText);

    imgloader.DisplayImage(levelImg, level);
    imgloader.DisplayImage(apiImg, api);
    imgloader.DisplayImage(descImgOne, descone);
    imgloader.DisplayImage(descImgTwo, desctwo);

}
 }

image loaded.java

public class ImageLoader {

MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
// Handler to display images in UI thread
Handler handler = new Handler();

public ImageLoader(Context context) {
    fileCache = new FileCache(context);
    executorService = Executors.newFixedThreadPool(5);
}

final int stub_id = R.drawable.temp_img;

public void DisplayImage(String url, ImageView imageView) {
    imageViews.put(imageView, url);
    Bitmap bitmap = memoryCache.get(url);
    if (bitmap != null)
        imageView.setImageBitmap(bitmap);
    else {
        queuePhoto(url, imageView);
        imageView.setImageResource(stub_id);
    }
}

private void queuePhoto(String url, ImageView imageView) {
    PhotoToLoad p = new PhotoToLoad(url, imageView);
    executorService.submit(new PhotosLoader(p));
}

private Bitmap getBitmap(String url) {
    File f = fileCache.getFile(url);

    Bitmap b = decodeFile(f);
    if (b != null)
        return b;

    // Download Images from the Internet
    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();
        conn.disconnect();
        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;
        FileInputStream stream1 = new FileInputStream(f);
        BitmapFactory.decodeStream(stream1, null, o);
        stream1.close();

        // 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;
        FileInputStream stream2 = new FileInputStream(f);
        Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
        stream2.close();
        return bitmap;
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

// Task for the queue
private class PhotoToLoad {
    public String url;
    public ImageView imageView;

    public PhotoToLoad(String u, ImageView i) {
        url = u;
        imageView = i;
    }
}

class PhotosLoader implements Runnable {
    PhotoToLoad photoToLoad;

    PhotosLoader(PhotoToLoad photoToLoad) {
        this.photoToLoad = photoToLoad;
    }

    @Override
    public void run() {
        try {
            if (imageViewReused(photoToLoad))
                return;
            Bitmap bmp = getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if (imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
            handler.post(bd);
        } catch (Throwable th) {
            th.printStackTrace();
        }
    }
}

boolean imageViewReused(PhotoToLoad photoToLoad) {
    String tag = imageViews.get(photoToLoad.imageView);
    if (tag == null || !tag.equals(photoToLoad.url))
        return true;
    return false;
}

// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
    Bitmap bitmap;
    PhotoToLoad photoToLoad;

    public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
        bitmap = b;
        photoToLoad = p;
    }

    public void run() {
        if (imageViewReused(photoToLoad))
            return;
        if (bitmap != null)
            photoToLoad.imageView.setImageBitmap(bitmap);
        else
            photoToLoad.imageView.setImageResource(stub_id);
    }
}

public void clearCache() {
    memoryCache.clear();
    fileCache.clear();
}

}

filecache.java

public class FileCache {

private File cacheDir;

public FileCache(Context context) {
    // Find the dir to save cached images
    if (android.os.Environment.getExternalStorageState().equals(
            android.os.Environment.MEDIA_MOUNTED))
        cacheDir = new File(
            android.os.Environment.getExternalStorageDirectory(),
            "ImgTxt");
    else
        cacheDir = context.getCacheDir();
    if (!cacheDir.exists())
        cacheDir.mkdirs();
}

public File getFile(String url) {
    String filename = String.valueOf(url.hashCode());
    // String filename = URLEncoder.encode(url);
    File f = new File(cacheDir, filename);
    return f;

}

public void clear() {
    File[] files = cacheDir.listFiles();
    if (files == null)
        return;
    for (File f : files)
        f.delete();
}

}

memorycache.java

public class MemoryCache {

private static final String TAG = "MemoryCache";

// Last argument true for LRU ordering
private Map<String, Bitmap> cache = Collections
.synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true));

// Current allocated size
private long size = 0;

// Max memory in bytes
private long limit = 1000000;

public MemoryCache() {
    // Use 25% of available heap size
    setLimit(Runtime.getRuntime().maxMemory() / 4);
}

public void setLimit(long new_limit) {
    limit = new_limit;
    Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB");
}

public Bitmap get(String id) {
    try {
        if (!cache.containsKey(id))
            return null;
        return cache.get(id);
    } catch (NullPointerException ex) {
        ex.printStackTrace();
        return null;
    }
}

public void put(String id, Bitmap bitmap) {
    try {
        if (cache.containsKey(id))
            size -= getSizeInBytes(cache.get(id));
        cache.put(id, bitmap);
        size += getSizeInBytes(bitmap);
        checkSize();
    } catch (Throwable th) {
        th.printStackTrace();
    }
}

private void checkSize() {
    Log.i(TAG, "cache size=" + size + " length=" + cache.size());
    if (size > limit) {
        // Least recently accessed item will be the first one iterated
        Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<String, Bitmap> entry = iter.next();
            size -= getSizeInBytes(entry.getValue());
            iter.remove();
            if (size <= limit)
                break;
        }
        Log.i(TAG, "Clean cache. New size " + cache.size());
    }
}

public void clear() {
    try {
        cache.clear();
        size = 0;
    } catch (NullPointerException ex) {
        ex.printStackTrace();
    }
}

long getSizeInBytes(Bitmap bitmap) {
    if (bitmap == null)
        return 0;
    return bitmap.getRowBytes() * bitmap.getHeight();
}
}

android manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mycompany.myapp" >

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
    android:name="ParseApplication"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        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=".SingleItemView">
    </activity>
</application>

</manifest>

1 个答案:

答案 0 :(得分:0)

在onclicklistener()中添加此代码

intent.putExtra("levelimg",
                            (codeList.get(position).getLevelImg()));

                    intent.putExtra("heading",
                            (codeList.get(position).getSingleItemHeading()));

                    intent.putExtra("subheading",
                            (codeList.get(position).getDescription()));

                    intent.putExtra("apitext",
                            (codeList.get(position).getApiText()));

                    intent.putExtra("apiimg",
                            (codeList.get(position).getApiImg()));

                    intent.putExtra("descimgone",
                            (codeList.get(position).getPreviewImgOne()));

                    intent.putExtra("descimgtwo",
                            (codeList.get(position).getPreviewImgTwo()));

                    intent.putExtra("codetext",
                            (codeList.get(position).getFinalCodeText()));
相关问题