Pergunta

I'm new to Java and Android.

Here in this application I'm trying to Download multiple images with progress bar and display images in GridView. I'm not getting any error but some exceptions. When I run this code in eclipse, Emulator Just shows "Unfortunately Stopped". So please can anyone help me to sort out this problem??

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.kailash.imagedownloader/com.kailash.imagedownloader.MainActivity}: java.lang.InstantiationException: can't instantiate class com.kailash.imagedownloader.MainActivity; no empty constructor

newInstance failed: no ()

threadid=1: thread exiting with uncaught exception (group=0x40a13300)

Here's the Code:

package com.kailash.imagedownloader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListAdapter;

public class MainActivity extends Activity{

Button btnShowProgress;
private ProgressDialog pDialog;
GridView grid_view;
public static final int progress_bar_type = 0; 

protected static final String[] URLS = {
 "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_2944.jpg",
    "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_2989.jpg",
    "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3005.jpg",
    "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3012.jpg",
    "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3034.jpg",
    "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3047.jpg",
    "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3092.jpg",
    "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3110.jpg",
    "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3113.jpg",
    "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3128.jpg",
    "http://cdn.cs76.net/2011/spring/lectures/6/imgs/img_3160.jpg",
};
public MainActivity(MainActivity mainActivity) {
    // TODO Auto-generated constructor stub
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    GridView gridview = (GridView) findViewById(R.id.grid_view);
    gridview.setAdapter((ListAdapter) new MainActivity(this));

    btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
    grid_view = (GridView) findViewById(R.id.grid_view);
    btnShowProgress.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            new DownloadImages().execute(URLS);
        }
    });

    //new DownloadImages().execute();
}

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case progress_bar_type: 
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Downloading file. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setMax(1000);
        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pDialog.setCancelable(true);
        pDialog.show();
        return pDialog;
    default:
        return null;
    }
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}



public class DownloadImages extends AsyncTask {

      @Override
      protected void onPreExecute() {
          super.onPreExecute();
          showDialog(progress_bar_type);
      }



    protected Object doInBackground(Object... params) {
        System.out.println("External Storage State = " + Environment.getExternalStorageState());
        File directory=new File(Environment.getExternalStorageDirectory(), "/Images");
        if (directory.exists()==false)
        {
            directory.mkdir();
        }
        for(int i = 0; i <URLS.length; i++) {
            try {
                File firstFile=new File(directory+"/" +i+ ".jpeg");
                if(firstFile.exists()==false)
                {
                    HttpClient httpClient =new DefaultHttpClient();
                    HttpGet httpGet =new HttpGet(URLS[i]);
                    HttpResponse resp = httpClient.execute(httpGet);
                    System.out.println("Status Code = " +resp.getStatusLine().getStatusCode());
                    if(resp.getStatusLine().getStatusCode()==200)
                    {
                        HttpEntity entity = resp.getEntity();
                        InputStream is = entity.getContent();
                        Boolean status = firstFile.createNewFile();

                        FileOutputStream foutS = new FileOutputStream(firstFile);
                        byte[] buffer = new byte[1024];
                        long total = 0;
                        int count;
                        while((count = is.read(buffer)) != -1){
                            total += count;
                            foutS.write(buffer, 0, count);
                        }
                        foutS.close();
                        is.close();
                        publishProgress(i);

                        }
                    }

                }catch(MalformedURLException e){
                    e.printStackTrace();
                }catch(ClientProtocolException e){
                    e.printStackTrace();
                }catch(IOException e){
                    e.printStackTrace();
                }
        }
        return null;
            }

     protected void onProgressUpdate(String... progress) {

         pDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @SuppressWarnings("unchecked")
    protected void onProgressUpdate(Object... values){
        super.onProgressUpdate(values);

        }
     protected void onPostExecute(String file_url) {
         dismissDialog(progress_bar_type);
         String imagePath = Environment.getExternalStorageDirectory().toString() + "/Images";
          grid_view.setBackgroundDrawable(Drawable.createFromPath(imagePath));
       }
 }


}

Thank You *please help*

Foi útil?

Solução

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.kailash.imagedownloader/com.kailash.imagedownloader.MainActivity}: java.lang.InstantiationException: can't instantiate class com.kailash.imagedownloader.MainActivity; no empty constructor

You should not create a constructor when extending Activity. As the system invokes the empty constructor, and creating another one causes the class to not have an empty constructor.

There is also no need to create one, as you shouldn't instantiate an activity by yourself at all. For some reason you instantiate your activity inside onCreate and cast it to ListAdapter, which is an error:

gridview.setAdapter((ListAdapter) new MainActivity(this));

You should use a different class which extends ListAdapter for this.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top