0

My application does not give any compile-time error and it does show the activity like it show. It is a simple activity with a button. When the user clicks on it, it should download an image from the network. When I click on the button, it just says, "Unfortunately, Concurrency has stopped."

I am reading up on threads in android and I got to know about the rules of not performing intensive operations in the UI thread and not manipulating the UI from outside the UI thread. I was practicing this.

I am not yet familiar with how to read logcats. I am posting my logcat and it will be great if somebody can read it and point out what's causing the problem.

Moreover, the implementation of loadImageFromNetwork() is not coded by me. I just copied it from internet. So I don't have an understanding of its call to the decodeStream() method. It was not my concern for the moment.

Main.java:-

package com.example.concurrency;

import java.io.InputStream;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends Activity {
    public static final String key_name="com.practice.firstApp.key";
    ImageView imageView;

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

    public void downloadImage(){
        new Thread(new Runnable(){

            private Bitmap loadImageFromNetwork(String url){
                try {
                Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(url).getContent());
                return bitmap;
                } catch (Exception e) {
                e.printStackTrace();
                }
                return null;
                }

            public void run(){
                final Bitmap bitmap= loadImageFromNetwork("http://www.google.com/imgres?imgurl=http%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fcommons%2F7%2F7a%2FBasketball.png&imgrefurl=http%3A%2F%2Fcommons.wikimedia.org%2Fwiki%2FFile%3ABasketball.png&h=340&w=340&tbnid=EJmjEDyJzrhAuM%3A&zoom=1&docid=C_hn8nOgsGmuwM&hl=en&ei=Q0o2U93LNcaIygH4mICQBQ&tbm=isch&ved=0CHwQhBwwBg&iact=rc&dur=3875&page=1&start=0&ndsp=14");
                imageView.post(new Runnable(){
                    public void run(){
                        imageView.setImageBitmap(bitmap);
                    }
                });
            }
        }).start();
    }
}

Activity_main.xml:-

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context=".MainActivity" >

     <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:text="@string/Button_MainActivity"

        android:onClick="downloadImage"/>

</RelativeLayout>

String.xml:-

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Concurrency</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="Button_MainActivity">Download</string>

</resources>

Manifest.xml:-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.concurrency"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

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

</manifest>

Logcat:-

It exceeded the length of the question. So you can find it here.

Solace
  • 8,612
  • 22
  • 95
  • 183

5 Answers5

0

Your downloadImage function needs to take a View as a parameter. Add that and it should fix the bug

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
0

You have to add this below line to get the permission to access Internet for your application...

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

Access method of the AsynchTask function inside the activity....

    BitmapWorkerTask backPropcess = new BitmapWorkerTask(position, ht,
                        wt);
                backPropcess.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, urls);

This is a asynctask download class

            public BitmapWorkerTask() {

                }

                @Override
                protected Bitmap doInBackground(String... params) {
                                    URL url;
                        try {
                            url = new URL(params[0]);

                                HttpURLConnection connection = (HttpURLConnection) url
                                        .openConnection();
                                connection.setConnectTimeout(4000);
                                connection.setReadTimeout(10000);
                                int v = connection.getContentLength() > 0 ? connection
                                        .getContentLength() : 0;

                                    if (v > 0) {
                                        InputStream in = new BufferedInputStream(
                                                connection.getInputStream(), 32 * 1024);
                                        Bitmap bitmap = decodeSampledBitmapFromResource(
                                                in, ht[i], wt[i]);
                                        if (bitmap != null && position != null) {
                                            addBitmapToMemoryCache(position, bitmap);
                                            System.out.println(position);

                            }
                        } catch (MalformedURLException e) {
                            // e.printStackTrace();
                        } catch (IOException e) {
                            // e.printStackTrace();
                        }


                    return bitmap;
                }

                @Override
                protected void onPostExecute(Bitmap result) {
                    imageView.setImageBitmap(result);
                }
               }
Naveen Kumar Kuppan
  • 1,424
  • 1
  • 10
  • 12
  • Thank you for answering. 1: I'm recalling that the first line in the code to be added in the manifest file is for a permission to access the internet. Can you please tell me what the next two lines are for? – Solace Mar 29 '14 at 15:17
  • I could not understand the two pieces of code you posted. Should I add the first snippet of code to my activity class? And I don't want to use Asynctask at the moment. Actually I am trying to learn concepts, so I plan to learn using Handlers and Asynctask later after this. – Solace Mar 29 '14 at 15:21
0

You can use AsyncTask or following code

private Handler mhHandler = new Handler() {
    public void handleMessage(android.os.Message msg) {
        if (msg.what == 100 && msg.obj != null) {
            imageView.setImageBitmap((Bitmap) msg.obj);
        }
    };
};

public void downloadImage(View v) {
    new Thread(new Runnable() {
        private Bitmap loadImageFromNetwork(String url) {
            try {
                Bitmap bitmap = BitmapFactory
                        .decodeStream((InputStream) new URL(url)
                                .getContent());
                return bitmap;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        public void run() {
            final Bitmap bitmap = loadImageFromNetwork("http://www.google.com/imgres?imgurl=http%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fcommons%2F7%2F7a%2FBasketball.png&imgrefurl=http%3A%2F%2Fcommons.wikimedia.org%2Fwiki%2FFile%3ABasketball.png&h=340&w=340&tbnid=EJmjEDyJzrhAuM%3A&zoom=1&docid=C_hn8nOgsGmuwM&hl=en&ei=Q0o2U93LNcaIygH4mICQBQ&tbm=isch&ved=0CHwQhBwwBg&iact=rc&dur=3875&page=1&start=0&ndsp=14");
            Message msg = new Message();
            msg.what = 100;
            msg.obj = bitmap;
            mhHandler.sendMessage(msg);
        }
    }).start();
}

and don't forget to put View on parameter of method downloadImage(View v) because you are calling it onClick from layout.

  • Actually I am learning (following [this]() tutorial), and I am just trying to learn to do this using methods like post, postDelayed, and runOnUiThread etc. Once I am clear about it, I will move on to learn the use of Handlers and Asynctasks for this purpose. – Solace Mar 29 '14 at 15:32
  • not a problem just replace method downloadImage() to downloadImage(View v) that will work. – droid_ravikant Mar 29 '14 at 15:47
  • I'll appreciate if you can tell me why does the downloadImage need the View v for? – Solace Mar 29 '14 at 17:42
  • onClick() method having parameter View in interface View.OnClickListener thats why by calling onClick from layout needs a parameter of View . – droid_ravikant Mar 29 '14 at 18:45
0

Adding

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

Also add a parameter of type "View" to your downloadImage function.

flameshimmer
  • 321
  • 3
  • 3
0
private Bitmap loadImageFromNetwork(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        return BitmapFactory.decodeStream(input);
    } catch (IOException e) {
        Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
        e.printStackTrace();
        return icon;
    }
}
Ninja
  • 1
  • 2