-2

I am trying to change the image source of an image view via java codes. The logic is that if my database retrieves product details, and one of the txtfields present is productcategory. so if productcategory= "blabla" i would like the image src to be : xxx.jpg. However i am having a nullpointerexception while trying to do that. Help Anyone ? Please

My logcat

04-02 15:10:07.450  22337-22337/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.project.mobileshoppingassistant/com.project.mobileshoppingassistant.MapViewActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
            at android.app.ActivityThread.access$600(ActivityThread.java:140)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4898)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.project.mobileshoppingassistant.MapViewActivity.logic(MapViewActivity.java:82)
            at com.project.mobileshoppingassistant.MapViewActivity.onCreate(MapViewActivity.java:73)
            at android.app.Activity.performCreate(Activity.java:5206)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
            at android.app.ActivityThread.access$600(ActivityThread.java:140)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4898)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
            at dalvik.system.NativeStart.main(Native Method)

MapViewActivity.java

package com.project.mobileshoppingassistant;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PointF;
import android.net.wifi.ScanResult;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

import org.json.JSONObject;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeSet;

public class MapViewActivity extends MapActivity {
    public final static String EXTRA_MESSAGE_FLOOR = "com.inte.indoorpositiontracker.FLOOR";

    private static final int MENU_ITEM_EDIT_MAP = 21;

    public static final int SCAN_DELAY = 1000; // delay for the first scan (milliseconds)
    public static final int SCAN_INTERVAL = 1000; // interval between scans (milliseconds)
    public static final int MAX_SCAN_THREADS = 2; // max amount of simultaneus scans

    private int mScanThreadCount = 0;

    //keys to save fingerPrint to sharedPereferences--start
    public static final String KEY_ID="fingerprint_id";
    public static final String KEY_MAP="fingerprint_map";
    public static final String KEY_POSITON_X="fingerprintX";
    public static final String KEY_POSITON_Y="fingerprintY";
    //end

    public static final String KEY_FINGERPRINT_MADE="hasFIngerPrintBeenMade";//used to check if
    // an average point has been calculated

    // UI pointer to visualize user where he is on the map
    private WifiPointView mLocationPointer;

    // handler for callbacks to the UI thread
    private static Handler sUpdateHandler = new Handler();

    // runnable to refresh map (called by the handler)
    private Runnable mRefreshMap = new Runnable() {
        public void run() {
            refreshMap();
        }
    };

    private boolean mPaused = false; // used to detect if the application is on map edit mode

    private HashMap<String, Integer> mMeasurements; // used to calculate weighted averages of signal strengths



    /** INSTANCE METHODS*/

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        logic();
    }

    public void logic() {
        Intent intent = getIntent();
        String from = intent.getStringExtra("from");
        if ("ActivityB".equals(from)) {
            ImageView img = (ImageView) findViewById(R.id.mapView);
            TextView txt = (TextView) findViewById(R.id.tvProductDescription);
                        if (txt.getText().equals("Baby")) {
                            img.setImageResource(R.drawable.cart);
                        } else if (txt.getText().equals("Meat")) {
                            img.setImageResource(R.drawable.msaicon);
                        }
                mMeasurements = new HashMap<String, Integer>();
                mLocationPointer = mMap.createNewWifiPointOnMap(new PointF(-1000, -1000));
                mLocationPointer.activate();

                if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(KEY_FINGERPRINT_MADE, false)) {
                    mLocationPointer.setFingerprint(getSavedFingerprint());
                }

                Timer timer = new Timer();
                timer.schedule(new TimerTask() {

                    @Override
                    public void run() {
                        if (mPaused == false) { // start scan only when this activity is active
                            mWifi.startScan();
                        }
                    }

                }, SCAN_DELAY, SCAN_INTERVAL);

            } else if ("ActivityA".equals(from)) {

                mMeasurements = new HashMap<String, Integer>();

                mLocationPointer = mMap.createNewWifiPointOnMap(new PointF(-1000, -1000));
                mLocationPointer.activate();

                if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(KEY_FINGERPRINT_MADE, false)) {
                    mLocationPointer.setFingerprint(getSavedFingerprint());
                }

                Timer timer = new Timer();
                timer.schedule(new TimerTask() {

                    @Override
                    public void run() {
                        if (mPaused == false) { // start scan only when this activity is active
                            mWifi.startScan();
                        }
                    }

                }, SCAN_DELAY, SCAN_INTERVAL);
            }
        }



    @Override
    public void onReceiveWifiScanResults(final List<ScanResult> results) {
        IndoorPositionTracker application = (IndoorPositionTracker) getApplication();
        final ArrayList<Fingerprint> fingerprints = application.getFingerprintData(mSelectedMap);

        // calculating the location might take some time in case there are a lot of fingerprints (>10000),
        // so it's reasonable to limit scan thread count to make sure there are not too many of these threads
        // going on at the same time
        if(results.size() > 0 && fingerprints.size() > 0 && mScanThreadCount <= MAX_SCAN_THREADS) {
            Thread t = new Thread() {
                public void run() {
                    mScanThreadCount++;

                    HashMap<String, Integer> measurements = new HashMap<String, Integer>();
                    for (ScanResult result : results) {
                        measurements.put(result.BSSID, result.level);
                    }

                    TreeSet<String> keys = new TreeSet<String>();
                    keys.addAll(mMeasurements.keySet());
                    keys.addAll(measurements.keySet());

                    // calculate access point signal strengths with weighted averages
                    // (adjust to suddent big changes in received signal strengths)
                    for (String key : keys) {
                        Integer value = measurements.get(key);
                        Integer oldValue = mMeasurements.get(key);
                        if(oldValue == null) {
                            mMeasurements.put(key, value);
                        } else if(value == null) {
                            mMeasurements.remove(key);
                        } else {
                            value = (int) (oldValue * 0.4f + value * 0.6f);
                            mMeasurements.put(key, value);
                        }
                    }


                    Fingerprint f = new Fingerprint(mMeasurements);

                    // find fingerprint closest to our location (one with the smallest euclidean distance to us)
                    Fingerprint closestMatch = f.getClosestMatch(fingerprints);

                    runOnUiThread(new Runnable() {
                        public void run() {
                            PreferenceManager.getDefaultSharedPreferences(MapViewActivity.this).edit()
                                    .putBoolean(KEY_FINGERPRINT_MADE,true).commit();
                        }
                    });
                    mLocationPointer.setFingerprint(closestMatch); // translate UI pointer to new location on screen
                    saveFingerPrint(closestMatch);
                    // need to refresh map through updateHandler since only UI thread is allowed to touch its views
                    sUpdateHandler.post(mRefreshMap);

                    mScanThreadCount--;
                }
            };
            t.start(); // start new scan thread
        }
    }

    public void startMapEditActivity() {
        Intent intent = new Intent(MapViewActivity.this, MapEditActivity.class);
        intent.putExtra(EXTRA_MESSAGE_FLOOR, mSelectedMap);
        startActivity(intent); // start map edit mode
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // add menu items
        super.onCreateOptionsMenu(menu); // items for changing map
        menu.add(Menu.NONE, MENU_ITEM_EDIT_MAP, Menu.NONE, "Edit map");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case MENU_ITEM_EDIT_MAP: // start map edit mode
                startMapEditActivity();
                return true;
            default: // change map
                return super.onOptionsItemSelected(item);
        }
    }

    private void saveMap(HashMap<String,Integer> inputMap){
        SharedPreferences pSharedPref = getApplicationContext().getSharedPreferences
                ("MyVariables", Context.MODE_PRIVATE);
        if (pSharedPref != null){
            JSONObject jsonObject = new JSONObject(inputMap);
            String jsonString = jsonObject.toString();
            SharedPreferences.Editor editor = pSharedPref.edit();
            editor.remove("My_map").commit();
            editor.putString("My_map", jsonString);
            editor.commit();
        }
    }

    private HashMap<String,Integer> loadMap(){
        HashMap<String,Integer> outputMap = new HashMap<String,Integer>();
        SharedPreferences pSharedPref = getApplicationContext().getSharedPreferences("MyVariables", Context.MODE_PRIVATE);
        try{
            if (pSharedPref != null){
                String jsonString = pSharedPref.getString("My_map", (new JSONObject()).toString());
                JSONObject jsonObject = new JSONObject(jsonString);
                Iterator<String> keysItr = jsonObject.keys();
                while(keysItr.hasNext()) {
                    String key = keysItr.next();
                    Integer value = (Integer) jsonObject.get(key);
                    outputMap.put(key, value);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return outputMap;
    }

    private void saveFingerPrint(Fingerprint fingerprint)
    {
        PreferenceManager.getDefaultSharedPreferences(this).edit()
                .putInt(KEY_ID,fingerprint.getId())
                .putString(KEY_MAP,fingerprint.getMap())
                .putFloat(KEY_POSITON_X,fingerprint.getLocation().x)
                .putFloat(KEY_POSITON_Y,fingerprint.getLocation().y)
                .commit();
        saveMap(fingerprint.getMeasurements());

    }

    private Fingerprint getSavedFingerprint()
    {
        SharedPreferences preferences=PreferenceManager.getDefaultSharedPreferences(this);
        int id=preferences.getInt(KEY_ID, -1);
        String map=preferences.getString(KEY_MAP, null);
        Float positionX=preferences.getFloat(KEY_POSITON_X, -1);
        Float positionY=preferences.getFloat(KEY_POSITON_Y,-1);
        PointF pointF=new PointF(positionX,positionY);
        Fingerprint fingerprint=new Fingerprint(id,map,pointF,loadMap());

        return fingerprint;
    }


}

2 Answers2

0

img.setOnTouchListener(new OnTouchListener() {

    @Override
    public boolean onTouch(View arg0, MotionEvent arg1) {


        switch (arg1.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                imgTicket.setImageResource(R.drawable.hticket);
                break;
            }
            case MotionEvent.ACTION_UP: {
                imgTicket.setImageResource(R.drawable.ticket);
                break;
            }
            case MotionEvent.ACTION_CANCEL:{
                imgTicket.setImageResource(R.drawable.ticket);
                break;
            }
            }
            return true;
        // TODO Auto-generated method stub

    }
});
manoj kumar
  • 199
  • 7
0

Edit Check if you are getting value in this variable:

 String from = intent.getStringExtra("from");
        if ("ActivityB".equals(from)) {....}

You are trying to access TextView and ImageView of previous activity. Just Define them in the activities where their layouts are called. Define them as public static keywords. Like:

Define separately :

   public static TextView txt;
     public static ImageView img; 

and declare:

txt=(TextView) findViewById(R.id.tvProductDescription);
img= (ImageView) findViewById(R.id.mapView);

And in current Activity:

 if ((Displayproductdetails.txt.getText().toString()).equalsIgnoreCase("Baby")) {
                           Displayproductdetails.img.setImageResource(R.drawable.cart);
                        } else if ((Displayproductdetails.txt.getText().toString()).equalsIgnoreCase("Meat")) {
                           Displayproductdetails.img.setImageResource(R.drawable.msaicon);
                        }
Android Geek
  • 8,956
  • 2
  • 21
  • 35
  • nothing doing mate, still same thing – Pem Kushal Apr 02 '16 at 11:42
  • @PemKushal check if your `from` string is not null. – Android Geek Apr 02 '16 at 11:46
  • yes, the logcat indicates the error is starting from the if condition. – Pem Kushal Apr 02 '16 at 11:48
  • @PemKushal ok you mean from `if ((txt.getText().toString())`? And are textview setted with text baby and Meat? – Android Geek Apr 02 '16 at 11:51
  • Actually the txtfield values are taken from a previous activity. I Have one acttivity displayproductdetails, which populates txtfield product category from database. then on the same activity i have a button which launches mapviewactivity. so basically i want an if condition, that if txtcategory = meat, the imagesrc will be x.jpg if txtcategory = baby imagesrc = d.jpg. got my point ? – Pem Kushal Apr 02 '16 at 11:58
  • @PemKushal that's why they are showing null pointer exception, as you are trying to access ImageView and TextView which are not present in current layout. – Android Geek Apr 02 '16 at 12:00
  • @PemKushal check for the edit. now this is perfect solution. – Android Geek Apr 02 '16 at 12:05
  • cannot make a static reference to the non-static method findviewbyid(int) TextView I'm having this error when i declare them as public static. any help mate ? – Pem Kushal Apr 02 '16 at 12:21
  • @PemKushal define separately and declare separately like in edit. check. – Android Geek Apr 02 '16 at 12:27
  • Thank you loads mate, i have been trying to solve this for the last 12 hours. thank you thank you mate – Pem Kushal Apr 02 '16 at 12:33
  • @PemKushal Great... if this helped you can accept the answer and upvote so that question can be closed. Thanks :) – Android Geek Apr 02 '16 at 12:52
  • @PemKushal thanks and please upvote too :) – Android Geek Apr 02 '16 at 13:00