2014-06-26 38 views
1

我目前正在使用外部數據庫處理帶有web服務的android應用程序。該應用程序由多個任務組成,每個任務分配給每個攝像機ID。每臺攝像機都具有存儲在數據庫中的特定長/經度。所以現在當我選擇一個特定的任務時,會有一個指導按鈕,將用戶當前位置顯示爲谷歌地圖中的一個標記。我想在谷歌地圖上顯示任務的長/緯度作爲標記,所以會有2個標記。只需要一些有關android編碼的幫助。任何幫助,將不勝感激!如何在Google地圖v2上顯示緯度/長度標記android

GoogleMapActivity.java

public class GoogleMapActivity extends Activity implements LocationListener { 
GoogleMap map; 
private String cameraid; 

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

    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

    lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); 

    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)) 
    .getMap(); 

    } 

    @Override 
public void onLocationChanged(Location location) { 

    map.clear(); 

    MarkerOptions mp = new MarkerOptions(); 

    mp.position(new LatLng(location.getLatitude(), location.getLongitude())); 

    mp.title("My Current Location"); 

    map.addMarker(mp); 

    map.animateCamera(CameraUpdateFactory.newLatLngZoom(
    new LatLng(location.getLatitude(), location.getLongitude()), 16)); 

    } 
@Override 
public void onProviderDisabled(String provider) { 
    // TODO Auto-generated method stub 

    } 

    @Override 
public void onProviderEnabled(String provider) { 
    // TODO Auto-generated method stub 

    } 

    @Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 
    // TODO Auto-generated method stub 

    } 

} 

AcceptTask.java

public class AcceptTask extends SherlockActivity { 

    private static String sendingURL, 
          url, 
          imageURL, 
          dateTimeP, 
          notificationID, 
          cameraID; 
    private String check = null; 
    // JSON Node names 
    private static final String TAG_GET = "jobViewResult", 
           TAG_IMAGEURL = "imageurl", 
           TAG_MESSAGE = "vmessage", 

           TAG_GETA = "assignResult", 
           TAG_STATUS = "assignStatus"; 

    private ProgressDialog pDialog; 
    public static final int progress_bar_type = 0; 

    private TextView tvCamera, tvDate; 
    private ImageView my_image; 
    // contacts JSONObject 
    JSONObject api = null; 
    private long userInteractionTime = 0; 
    AsyncTask<Void, Void, Void> mRegisterTask; 


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

     tvCamera = (TextView) findViewById(R.id.tv_CameraID); 
     tvDate = (TextView) findViewById(R.id.tv_DateR); 
     my_image = (ImageView) findViewById(R.id.img_Task); 
     //set the icon clickable 
     getSupportActionBar().setHomeButtonEnabled(true); 
     //add an < arrow on the icon 
     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 

      File file = new File("/sdcard/LocationSystem/pendingtask_temp.jpg"); 
      if (file.exists()) { 
       file.delete(); 
      } 


      if(isNetworkConnected()){ 
       try{ 
      // getting intent data 
      Intent intent = getIntent(); 

      /** Get values from previous intent */ 
      dateTimeP = intent.getStringExtra("TAG_IMAGE_TIME_DATE_P"); 
      cameraID = intent.getStringExtra("TAG_CAMERA_ID_P"); 
      notificationID = intent.getStringExtra("TAG_NOTIFICATION_ID"); 

      /** Display cameraID and date time */ 
      tvCamera.setText(cameraID); 
      tvDate.setText(dateTimeP); 

      url = "url"; 

      // Creating JSON Parser instance 
      JSONParser jParser = new JSONParser(); 

      // getting JSON string from URL 
      JSONObject json = jParser.getJSONFromUrl(url); 

      try { 
       api = json.getJSONObject(TAG_GET); 
       check = api.getString(TAG_MESSAGE); 
       // Storing each json item in variable 
       imageURL = api.getString(TAG_IMAGEURL); 

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

      if(check.equals("Job available")){ 
      new DownloadImageTask().execute(imageURL); 
      }else{ 
       AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogTheme)); 
       builder.setCancelable(false); 
       builder.setTitle("Job Unavailable"); 
       builder.setMessage(check); 
      // Setting Icon to Dialog 
       builder.setIcon(R.drawable.ic_action_error); 
       builder.setPositiveButton("OK", 
         new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int which) { 
          Intent loadIntent = new Intent(); 
          loadIntent.putExtra("startUpdate_PList", "start"); 
          setResult(Activity.RESULT_OK, loadIntent); 
          finish(); 
         } 
        }); 
       builder.show(); 
      } 
     } catch(Exception e) { 
      if(e != null) { 
       showServerErrorDialog(); 
      } 
     } 
     }else{showNetworkErrorDialog();} 
} 

    private void showServerErrorDialog(){ 
     AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogTheme)); 
     builder.setCancelable(false); 
     builder.setTitle("Server Error"); 
     builder.setMessage("Server is currently unable to connect. Please check your network connectivity."); 
    // Setting Icon to Dialog 
     builder.setIcon(R.drawable.ic_action_error); 
     builder.setPositiveButton("OK", 
       new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 
        finish(); 
       } 
      }); 
     builder.show(); 
    } 

    private void showNetworkErrorDialog(){ 
     AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogTheme)); 

     builder.setTitle("No Network Connection"); 
     builder.setMessage("Please turn on your mobile 3G or connect to a network in order to use this application."); 
    // Setting Icon to Dialog 
     builder.setIcon(R.drawable.ic_action_error); 

     builder.setPositiveButton("Close", 
       new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int which) { 
         AcceptTask.this.finish(); 
        } 
       }); 

     builder.setNegativeButton("Setting", 
       new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int which) { 
         //calling setting menu 
         startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0); 
        } 
       }); 
     builder.show(); 
    } 

    private boolean isNetworkConnected() { 
      ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
      NetworkInfo ni = cm.getActiveNetworkInfo(); 
      if (ni == null) { 
      return false; 
      } else{ 
      return true; 
     } 
     } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
       // Handle presses on the action bar items 
       switch (item.getItemId()) { 
       case android.R.id.home: 
        if(my_image.getDrawable() != null){ 
         File file = new File("/sdcard/LocationSystem/pendingtask_temp.jpg"); 
         if (file.exists()) { 
          file.delete(); 
         } 
        } 
        Intent loadIntent = new Intent(); 
        loadIntent.putExtra("startUpdate_PList", "start"); 
        setResult(Activity.RESULT_OK, loadIntent); 
        finish(); 
       break; 
        default: 
         return super.onOptionsItemSelected(item); 
       } 
       return false; 
      } 

    @Override 
    public void onUserInteraction() { 
     userInteractionTime = System.currentTimeMillis(); 
     super.onUserInteraction(); 
     Log.i("appname","Interaction"); 
    } 

    @Override 
    public void onUserLeaveHint() { 
     long uiDelta = (System.currentTimeMillis() - userInteractionTime); 

     super.onUserLeaveHint(); 

     if (uiDelta < 100){ 
      Logout(); 
     } 
    } 

    @Override 
    public void onResume() { 
     super.onResume(); 
     if(isNetworkConnected()){ 
     try{ 
      SharedPreferences checkLogin1 = getApplicationContext().getSharedPreferences("checklogin", 0); 
      String staffID = checkLogin1.getString("staffID", ""); 
      String staffPassword = checkLogin1.getString("password", ""); 

      DefaultHttpClient httpClient = new DefaultHttpClient(); 

      //get the unique id 
      SharedPreferences pref = getApplicationContext().getSharedPreferences("checklogin", 0); 
      String checkID = pref.getString("loginRID", ""); 

      HttpGet request = new HttpGet(url); 

      request.setHeader("Accept", "application/json"); 
      request.setHeader("Content-type", "application/json"); 

      HttpResponse response = httpClient.execute(request); 

      HttpEntity responseEntity = response.getEntity(); 

      // Read response data into buffer 
      char[] buffer = new char[(int) responseEntity 
        .getContentLength()]; 
      InputStream stream = responseEntity.getContent(); 
      InputStreamReader reader = new InputStreamReader(stream); 
      reader.read(buffer); 
      stream.close(); 

      JSONObject svr = new JSONObject(new String(buffer)); 
      JSONObject obj = svr.getJSONObject("loginTestResult"); 
      String validation = obj.getString("valid"); 
      String position = obj.getString("position"); 
      String companyID = obj.getString("companyID"); 
      String messageStatus = obj.getString("message"); 
      if(validation.equals("1")){ 

       checkNotNull(SERVER_URL, "SERVER_URL"); 
       checkNotNull(SENDER_ID, "SENDER_ID"); 
       // Make sure the device has the proper dependencies. 
       GCMRegistrar.checkDevice(this); 
       // Make sure the manifest was properly set - comment out this line 
       // while developing the app, then uncomment it when it's ready. 
       GCMRegistrar.checkManifest(this); 
       //mDisplay = (TextView) findViewById(R.id.display); 
       //gcmIDtxt =(TextView) findViewById(R.id.gcmID); 
       registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION)); 
       final String regId = GCMRegistrar.getRegistrationId(this); 
       System.out.print(regId); 
       if (regId.equals("")) { 
        // Automatically registers application on startup. 
        GCMRegistrar.register(this, SENDER_ID); 
       } else { 
        // Device is already registered on GCM, check server. 
//     if (GCMRegistrar.isRegisteredOnServer(this)) { 
//      // Skips registration. 
//      //mDisplay.append(getString(R.string.already_registered) + "\n"); 
//      //gcmIDtxt.setText(regId); 
// 
//     } else { 
         // Try to register again, but not in the UI thread. 
         // It's also necessary to cancel the thread onDestroy(), 
         // hence the use of AsyncTask instead of a raw thread. 
         final Context context = this; 
         mRegisterTask = new AsyncTask<Void, Void, Void>() { 

          @Override 
          protected Void doInBackground(Void... params) { 
           boolean registered = 
             ServerUtilities.register(context, regId); 
           // At this point all attempts to register with the app 
           // server failed, so we need to unregister the device 
           // from GCM - the app will try to register again when 
           // it is restarted. Note that GCM will send an 
           // unregistered callback upon completion, but 
           // GCMIntentService.onUnregistered() will ignore it. 
           if (!registered) { 
            GCMRegistrar.unregister(context); 
           } 
           return null; 
          } 

          @Override 
          protected void onPostExecute(Void result) { 
           mRegisterTask = null; 
          } 
         }; 
         mRegisterTask.execute(null, null, null); 
//      } 
       } 

     }else{ 
      AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogTheme)); 
       builder.setCancelable(false); 
       builder.setTitle("Error"); 
       builder.setMessage(messageStatus + " Please sign in again."); 
       // Setting Icon to Dialog 
       builder.setIcon(android.R.drawable.ic_dialog_alert); 
       builder.setPositiveButton("OK", 
         new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int which) { 
          SharedPreferences pref2 = getApplicationContext().getSharedPreferences("checklogin", 0); 
          final SharedPreferences.Editor editor1 = pref2.edit(); 
          editor1.putInt("login", 0); 
          editor1.commit(); 
          Intent intent = new Intent(AcceptTask.this, LoginPage.class); 
          intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
          startActivity(intent); 
          finish(); 
         } 
        }); 
       builder.show(); 
     } 

      } catch(Exception e) { 
        if(e != null) { 
         showServerErrorDialog(); 
        } 
       } 
     }else{ 
      showNetworkErrorDialog(); 
     } 
     //runAcceptedTask(); 
    } 

    private final BroadcastReceiver mHandleMessageReceiver = 
       new BroadcastReceiver() { 
      @Override 
      public void onReceive(Context context, Intent intent) { 
      String newMessage = intent.getExtras().getString(EXTRA_MESSAGE); 
      //mDisplay.append(newMessage + "\n"); 
      } 
     }; 

    private void checkNotNull(Object reference, String name) { 
      if (reference == null) { 
       throw new NullPointerException(
         getString(R.string.error_config, name)); 
      } 
     } 

    private void Logout(){ 
     if(isNetworkConnected()){ 
     try{ 
       StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() 
       .permitAll().build(); 
       StrictMode.setThreadPolicy(policy); 


      DefaultHttpClient httpClient = new DefaultHttpClient(); 

      //get the unique id 
      SharedPreferences pref = getApplicationContext().getSharedPreferences("checklogin", 0); 
      String checkID = pref.getString("loginRID", ""); 
      String staffID = pref.getString("staffID", ""); 


      HttpGet request = new HttpGet(url); 

      request.setHeader("Accept", "application/json"); 
      request.setHeader("Content-type", "application/json"); 

      HttpResponse response = httpClient.execute(request); 

      HttpEntity responseEntity = response.getEntity(); 

      // Read response data into buffer 
      char[] buffer = new char[(int) responseEntity 
        .getContentLength()]; 
      InputStream stream = responseEntity.getContent(); 
      InputStreamReader reader = new InputStreamReader(stream); 
      reader.read(buffer); 
      stream.close(); 

      JSONObject svr = new JSONObject(new String(buffer)); 
      JSONObject obj = svr.getJSONObject("logoutResult"); 
      String messageStatus = obj.getString("userMessage"); 
      if(messageStatus.equals("Updated Successfully!!")){ 

       }else{ 
        AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogTheme)); 
        builder.setCancelable(false); 
        builder.setTitle("Error"); 
        builder.setMessage(messageStatus); 
       // Setting Icon to Dialog 
        builder.setIcon(R.drawable.ic_action_error); 
        builder.setPositiveButton("OK", 
          new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, int which) { 
           finish(); 
          } 
         }); 
        builder.show(); 
       } 


      } catch (Exception e) { 
       if(e != null) { 
         showServerErrorDialog(); 
        } 
      } 
     } 
      else{ 
       showNetworkErrorDialog(); 
      } 
    } 


    //accept task button 
    public void acceptTask(View v) { 
     File file = new File("/sdcard/LocationSystem/pendingtask_temp.jpg"); 
     if (file.exists()) { 
      file.delete(); 
     } 

     AlertDialog.Builder builder = new AlertDialog.Builder(AcceptTask.this); 

     builder.setTitle("Confirm Accept"); 
     builder.setMessage("Are you sure to accept this job?"); 

     builder.setPositiveButton("YES", new DialogInterface.OnClickListener() { 

      public void onClick(DialogInterface dialog, int which) { 
       if(isNetworkConnected()){ 
       try{ 
       // Do do my action here 
       SharedPreferences pref = getApplicationContext().getSharedPreferences(
         "checklogin", 0); 
       String staffID = pref.getString("staffID", ""); 
       //sendingURL = ""+staffID; 
       sendingURL = "url"; 

       // Creating JSON Parser instance 
       JSONParser jParser = new JSONParser(); 

       // getting JSON string from URL 
       JSONObject json = jParser.getJSONFromUrl(sendingURL); 

       try { 
        api = json.getJSONObject(TAG_GETA); 
        check = api.getString(TAG_STATUS); 
       } catch (JSONException e) { 
        if(e != null) { 
         showServerErrorDialog();} 
       } 
       if(check.equals("Job available")){ 
        DefaultHttpClient httpclient = new DefaultHttpClient(); 
        HttpGet httpget = new HttpGet(sendingURL); 

        try { 
         HttpResponse response = httpclient.execute(httpget); 
         Toast.makeText(getApplicationContext(), "You accepted the job.", Toast.LENGTH_SHORT).show(); 
         Intent loadIntent = new Intent(); 
         loadIntent.putExtra("startUpdate_PList", "start"); 
         setResult(Activity.RESULT_OK, loadIntent); 
         finish(); 
        } 
        catch (IOException e) { 
         if(e != null) { 
           showServerErrorDialog();} 
       } 
        }else{ 
         AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(AcceptTask.this, R.style.AlertDialogTheme)); 
         builder.setCancelable(false); 
         builder.setTitle("Job Unavailable"); 
         builder.setMessage(check); 
        // Setting Icon to Dialog 
         builder.setIcon(R.drawable.ic_action_error); 
         builder.setPositiveButton("OK", 
           new DialogInterface.OnClickListener() { 
           public void onClick(DialogInterface dialog, int which) { 
            Intent loadIntent = new Intent(); 
            loadIntent.putExtra("startUpdate_PList", "start"); 
            setResult(Activity.RESULT_OK, loadIntent); 
            finish(); 
           } 
          }); 
         builder.show(); 
        } 


       } catch(Exception e) { 
        if(e != null) { 
         showServerErrorDialog(); 
        } 
       } 
       }else{ 
        showNetworkErrorDialog(); 
       } 

      } 
     }); 

     builder.setNegativeButton("NO", new DialogInterface.OnClickListener() { 

      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.cancel(); 
      } 
     }); 

     AlertDialog alert = builder.create(); 
     alert.show(); 


} 

    private class DownloadImageTask extends AsyncTask<String, String, String> { 

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

     protected String doInBackground(String... urls) { 
      int count; 
      try { 
       URL url = new URL(urls[0]); 
       URLConnection connection = url.openConnection(); 
       connection.connect(); 
       int lenghtOfFile = connection.getContentLength(); 

       InputStream in = new BufferedInputStream(url.openStream(), 8192); 
       byte data[] = new byte[1024]; 

      // Output stream to write file 
       OutputStream output = new FileOutputStream("/sdcard/LocationSystem/pendingtask_temp.jpg"); 

       long total = 0; 
       while((count = in.read(data)) != -1){ 
        total += count; 
        publishProgress(""+(int)((total*100)/lenghtOfFile)); 

        File file = new File(getExternalCacheDir(), "pendingtask_temp.jpg"); 
        if (file.exists()) { 
         file.delete(); 
        }else{ 
        output.write(data, 0, count); 
        } 
       } 
       output.flush(); 
       output.close(); 
       in.close(); 

      } catch (Exception e) { 
       Log.e("Error", e.getMessage()); 
       if(e != null) { 
        showServerErrorDialog(); 
       } 
      } 
      return null; 
     } 
     /** 
     * Updating progress bar 
     * */ 
     protected void onProgressUpdate(String... progress) { 
      // setting progress percentage 
      pDialog.setProgress(Integer.parseInt(progress[0])); 
     } 

     protected void onPostExecute(String file_url) { 
      // dismiss the dialog after the file was downloaded 
      dismissDialog(progress_bar_type); 

      String imagePath = Environment.getExternalStorageDirectory().toString() + "/LocationSystem/pendingtask_temp.jpg"; 
      // setting downloaded into image view 
      my_image.setImageDrawable(Drawable.createFromPath(imagePath)); 
      File file = new File("/sdcard/LocationSystem/pendingtask_temp.jpg"); 
       if (file.exists()) { 
        file.delete(); 
       } 
      if (my_image.getDrawable() == null){ 
       Toast.makeText(AcceptTask.this, "Please select again!",Toast.LENGTH_LONG).show(); 
       finish(); 
      } 
     } 
    } 

    @Override 
    protected Dialog onCreateDialog(int id) { 
     switch (id) { 
     case progress_bar_type: // we set this to 0 
      pDialog = new ProgressDialog(this); 
      pDialog.setMessage("Downloading file. Please wait..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setMax(100); 
      pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
      //pDialog.setButton("Cancel", (DialogInterface.OnClickListener) null); 
      pDialog.setButton("Cancel", 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int which) { 
          AcceptTask.this.finish(); 
         } 
        }); 

      pDialog.setCancelable(false); 
      pDialog.show(); 
      return pDialog; 
     default: 
      return null; 
     } 
     } 

    @Override 
    public void onBackPressed() { 
     if(my_image.getDrawable() != null){ 
      File file = new File("/sdcard/LocationSystem/pendingtask_temp.jpg"); 
      if (file.exists()) { 
       file.delete(); 
      } 
     } 
     Intent loadIntent = new Intent(); 
     loadIntent.putExtra("startUpdate_PList", "start"); 
     setResult(Activity.RESULT_OK, loadIntent); 
     finish(); 
    } 

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

} 
+0

您的代碼看起來沒問題。你有什麼問題?你有一些錯誤? –

+0

是的我的代碼是完美的工作。現在我只想使用數據庫中的long/lat值在谷歌地圖上顯示任務標記,我在這樣做時遇到了一些問題。 – user3777508

+0

問題是什麼? –

回答

0

你可以做一個asynck任務中獲得的DB值,並在onlocationchange調用此任務。

+0

謝謝你會試試 – user3777508

+0

好的。然後說出結果。 –

相關問題