0

I am trying to load an image from the interwebz but I get a null pointer exception. Here is my code :

public class Search extends ActionBarActivity {
TableLayout tableScrollView;
String[] JSONExceptions = { "type", "em", "user_id", "id", "profilepic",
        "bg" };
String value;
JSONObject jObject;

private float mx, my;
private float curX, curY;

private ScrollView vScroll;
private HorizontalScrollView hScroll;
private Bitmap profilepic;
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search);

    vScroll = (ScrollView) findViewById(R.id.vScroll);
    hScroll = (HorizontalScrollView) findViewById(R.id.hScroll);
    iv = (ImageView) findViewById(R.id.imageView);
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        value = extras.getString("id");
    }
    System.out.println(value);
    tableScrollView = (TableLayout) findViewById(R.id.tableScrollView);
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            jObject = getJson("http://www.tabcards.com/req/androidapi/L2o30H8JlFMtFYHW3KLxkts20ztc5Be6Z6m6v315/json/"
                    + value);
            try {
                profilepic = BitmapFactory.decodeStream(new URL(jObject.getString("profilepic")).openConnection().getInputStream());
                iv.setImageBitmap(profilepic);
            } catch (MalformedURLException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    try {

                        System.out.println("awaking");
                        createUI(jObject);
                        System.out.println("done");

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            });

        }
    });
    thread.start();

    System.out.println("complete");

}

private void createUI(JSONObject jObject) throws JSONException {
    int absIndex = 0;
    String value = jObject.getString("name");
    if (value != "" && !jObject.getString("profilepic").equals("")) {
        System.out.println(jObject.getString("profilepic"));

            insertElement(value, absIndex++, true);
    }


}



public static Bitmap drawableToBitmap (Drawable drawable) {
    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap); 
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}

public static Bitmap getclip(Bitmap bitmap) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
            bitmap.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2,
            bitmap.getWidth() / 2, paint);
    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);
    return output;
}


public Bitmap getCroppedBitmap(Bitmap bitmap) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
            bitmap.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    final int color = 0xff424242;
    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(color);
    // canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
    canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2,
            bitmap.getWidth() / 2, paint);
    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(bitmap, rect, rect, paint);
    //Bitmap _bmp = Bitmap.createScaledBitmap(output, 60, 60, false);
    //return _bmp;
    return output;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.search, menu);
    return true;
}



private void insertElement(String data, int i, boolean flag) {
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View newRow = inflater.inflate(R.layout.row, null, false);
    newRow.setLayoutParams(new TableRow.LayoutParams(
            TableRow.LayoutParams.MATCH_PARENT,
            TableRow.LayoutParams.WRAP_CONTENT));

    TextView dataTextView = (TextView) newRow
            .findViewById(R.id.rowTextView);
    dataTextView.setText(data);

    if(!flag) {
        iv.setVisibility(View.GONE);
    }
    System.out.println(dataTextView.getText().toString());
    tableScrollView.addView(newRow, i);     
}

public static boolean useLoop(String[] arr, String targetValue) {
    for(String s: arr){
        if(s.equals(targetValue))
            return true;
    }
    return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public static <T> boolean contains2(final T[] array, final T v) {
    if (v == null) {
        for (final T e : array)
            if (e == null)
                return true;
    } else {
        for (final T e : array)
            if (e == v || v.equals(e))
                return true;
    }

    return false;
}

public static Drawable LoadImageFromWeb(String url) {
    try {
        InputStream is = (InputStream) new URL(url).getContent();
        Drawable d = Drawable.createFromStream(is, "src name");
        return d;
    } catch (Exception e) {
        return null;
    }
}

// Given a string representation of a URL, sets up a connection and gets
// an input stream.
private InputStream downloadUrl(String urlString) throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000 /* milliseconds */);
    conn.setConnectTimeout(15000 /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Starts the query
    conn.connect();
    return conn.getInputStream();
}

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public static JSONObject getJson(String url) {

    InputStream is = null;
    String result = "";
    JSONObject jsonObject = null;

    // HTTP
    try {
        HttpClient httpclient = new DefaultHttpClient(); // for port 80
                                                            // requests!
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } catch (Exception e) {
        return null;
    }

    // Read response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "utf-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
            System.out.println(line);
        }
        is.close();
        result = sb.toString().replace("[", "");
        System.out.println("done getting obj : " + result);

    } catch (Exception e) {
        return null;
    }

    // Convert string to object
    try {
        jsonObject = new JSONObject(result.replace("]", ""));
    } catch (JSONException e) {
        return null;
    }

    return jsonObject;

}

@Override
public boolean onTouchEvent(MotionEvent event) {
    float curX, curY;

    switch (event.getAction()) {

        case MotionEvent.ACTION_DOWN:
            mx = event.getX();
            my = event.getY();
            break;
        case MotionEvent.ACTION_MOVE:
            curX = event.getX();
            curY = event.getY();
            vScroll.scrollBy((int) (mx - curX), (int) (my - curY));
            hScroll.scrollBy((int) (mx - curX), (int) (my - curY));
            mx = curX;
            my = curY;
            break;
        case MotionEvent.ACTION_UP:
            curX = event.getX();
            curY = event.getY();
            vScroll.scrollBy((int) (mx - curX), (int) (my - curY));
            hScroll.scrollBy((int) (mx - curX), (int) (my - curY));
            break;
    }

    return true;
}
}

It's mostly in the thread where I handle it. I have no idea what is going on and I have tried to look at other questions but none solved my problem. The image that I retrieve is OK, I mean, I do profilepic.getWidth() and it returns the actual accurate value.

6
  • @Rod_Algonquin pastebin.com/1DKPXJ2T Commented Aug 24, 2014 at 19:38
  • @Rod_Algonquin sorry : pastebin.com/sptAREjp Commented Aug 24, 2014 at 19:42
  • Can you check if imageview is null or the bitmap is null Commented Aug 24, 2014 at 19:56
  • @Rod_Algonquin imageview is null Commented Aug 24, 2014 at 20:07
  • Post the xml activity_search Commented Aug 24, 2014 at 20:11

1 Answer 1

1

Problem is that your imageview does not exist in your xml that you used in your activity, thus giving you NPE. You cant use a view that does not exist in your layout of the activity

Solution

add the xml in your activity_search.xml and also make sure that you set the imagebackground in the runonuithread.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok will do. May I ask you how I could not get a downvote in the future? I did not post the catlog because I though it was trivial since only one line was relevant to my project and I knew it was a NPE. Thanks
@gedr just make sure that you posted theright information such as logcat so we can debug the problem right away without asking you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.