繁体   English   中英

为什么我的哈希图是空的Android?

[英]Why my hashmap is null Android?

我正在尝试从hashmap(从ListViewRestaurants)获取值,因此我可以将纬度和经度传递给MapsActivity,但由于这个原因,我的hashmap总是返回null ...所以任何人都可以帮助我。

public class ListViewRestaurants extends Activity {

    static ListView listView;
    static ArrayList<HashMap<String, String>> arrList;

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

        listView = (ListView) findViewById(R.id.listiew);
        arrList = new ArrayList<HashMap<String, String>>();

        String json_str = getJsonData();

        try {
            JSONArray jArray = new JSONArray(json_str);

            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json = null;
                json = jArray.getJSONObject(i);

                HashMap<String, String> map1 = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map1.put("id", json.getString("id"));
                map1.put("BusinessName", json.getString("BusinessName"));
                map1.put("AddressLine1", json.getString("AddressLine1"));
                map1.put("AddressLine2", json.getString("AddressLine2"));
                map1.put("AddressLine3", json.getString("AddressLine3"));
                map1.put("PostCode", json.getString("PostCode"));
                map1.put("RatingValue", json.getString("RatingValue"));
                map1.put("RatingDate", json.getString("RatingDate"));
                map1.put("DistanceKM", json.getString("DistanceKM"));
                map1.put("Latitude", json.getString("Latitude"));
                map1.put("Longitude", json.getString("Longitude"));

                int name = json.getInt("RatingValue");
                if(name == 5){
                    map1.put("Image", String.valueOf(R.drawable.ic_launcher_web));
                }
                else if(name==4){
                    //map1.put("Image", String.valueOf(R.drawable.ic_launcher_web));
                }
                else if(name==3){
                    // map1.put("Image", String.valueOf(R.drawable.ic_launcher_web));
                }
                else if(name==2){
                    // map1.put("Image", String.valueOf(R.drawable.ic_launcher_web));
                }
                else if(name==1){
                    // map1.put("Image", String.valueOf(R.drawable.ic_launcher_web));
                }
                else if(name==0){
                    // map1.put("Image", String.valueOf(R.drawable.ic_launcher_web));
                }
                else if(name==-1){
                    map1.put("RatingValue", "Exempt");
                }
                // adding HashList to ArrayList
                arrList.add(map1); //                Intent intent = new Intent(this,MapsActivity.class); //                intent.putExtra("map", map1);
            }


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

        if (!arrList.isEmpty()) {
            ListAdapter adapter = new SimpleAdapter(this, arrList,
                    R.layout.list_item, new String[]{"id", "BusinessName",
                    "AddressLine1", "AddressLine2", "AddressLine3", "PostCode",
                    "RatingValue", "RatingDate", "DistanceKM", "Image"},
                    new int[]{R.id.restaurantId, R.id.BusinessName,
                            R.id.adr1, R.id.adr2, R.id.adr3, R.id.postCode,
                            R.id.rating, R.id.ratingDate, R.id.distance, R.id.image});


            listView.setAdapter(adapter);
        }
    }

    private String getJsonData() {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork()   // or .detectAll() for all detectable problems
                .penaltyLog()
                .build());

        String str = "";
        Intent intent  = getIntent();
        String latitude = intent.getStringExtra("Lat");
        String longtitude = intent.getStringExtra("Lon");
        HttpResponse response;
        HttpClient myClient = new DefaultHttpClient();
        HttpPost myConnection = new HttpPost("http://sandbox.kriswelsh.com/hygieneapi/hygiene.php?op=s_loc&lat="+latitude+"&long="+longtitude);

        try {
            response = myClient.execute(myConnection);
            str = EntityUtils.toString(response.getEntity(), "UTF-8");

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return str;
    }

} 

在这里,我试图从ListViewRestuarants的hashamp(纬度和经度)中检索详细信息,但我总是得到空值。

import android.content.Intent; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.util.Log;

import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions;

import java.util.HashMap;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    static String x;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        //get the value from the array class
        Intent intent = getIntent();
        HashMap<String, String> hashMap = (HashMap<String, String>)intent.getSerializableExtra("map"); System.out.println(hashmap)


       // Log.v("HashMapTest", hashMap.get("Longtitude"));
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title(x));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    } } 

这是一个主要的类,显示选项卡视图(有关更多信息)

import android.app.TabActivity; import android.content.Intent; import android.os.Bundle; import android.widget.TabHost;

public class MainActivity extends TabActivity {

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

        // create the TabHost that will contain the Tabs
        TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);

        TabHost.TabSpec tab1 = tabHost.newTabSpec("First Tab");
        TabHost.TabSpec tab2 = tabHost.newTabSpec("Second Tab");

        // Set the Tab name and Activity
        // that will be opened when particular Tab will be selected
        tab1.setIndicator("Restaurant");
        tab1.setContent(new Intent(this, ListViewRestaurants.class));

        tab2.setIndicator("Map");
        tab2.setContent(new Intent(this, RestaurantMap.class));

        /** Add the tabs  to the TabHost to display. */
        tabHost.addTab(tab1);
        tabHost.addTab(tab2);
    } }

问题是您要在地图中设置其他键,但尝试获取与其他键对应的值-

map1.put("Longitude", json.getString("Longitude")); //Setting "Longitude"

Log.v("HashMapTest", hashMap.get("Longtitude")); //Getting "Longtitude"

显然,您的地图中没有键“ Longtitude ”。

最佳实践是为键使用常量,并将其用于插入和检索,这样可以避免此类问题,并且也不会浪费时间进行调试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM