Projects >> Ushahidi_Android >>abe93274b2c502fafb3a81438dc35f1a3299a027

Chunk
Conflicting content
	private static final int TIME_DIALOG_ID = 4;
    private static final int DATE_DIALOG_ID = 5;
	
	private final static Handler mHandler = new Handler();
	
    private boolean mError = false;

    private EditText mIncidentTitle;
<<<<<<< HEAD
	private EditText mIncidentLocation;
	private EditText mIncidentDesc;
	
	private TextView mIncidentDate;
	private ImageView mSelectedPhoto;
	private TextView mSelectedCategories;
	
	private Button mBtnSend;
	private Button mBtnCancel;
	private Button mBtnAddCategory;
	private Button mPickTime;
	private Button mPickDate;
	private Button mBtnPicture;
	private Button mAddLocation;
	
	private HashMap mTimeDigits;
	
	private Bundle mBundle;
	private Bundle mExtras;
	
	private static final int DIALOG_ERROR_NETWORK = 0;
	private static final int DIALOG_ERROR_SAVING = 1;
	private static final int DIALOG_CHOOSE_IMAGE_METHOD = 2;
	private static final int DIALOG_MULTIPLE_CATEGORY = 3;
	private Vector mVectorCategories = new Vector();
	private Vector mCategoriesId = new Vector();
	
	private HashMap mCategoriesTitle = new HashMap();
	private HashMap mParams = new HashMap();
	
	public static final String PREFS_NAME = "UshahidiPref";
	
	@Override
=======

    private EditText mIncidentLocation;

    private EditText mIncidentDesc;

    private TextView mIncidentDate;

    private TextView mSelectedPhoto;

    private TextView mSelectedCategories;

    private Button mBtnSend;

    private Button mBtnCancel;

    private Button mBtnAddCategory;

    private Button mPickTime;

    private Button mPickDate;

    private Button mBtnPicture;

    private Button mAddLocation;

    private HashMap mTimeDigits;

    private Bundle mBundle;

    private Bundle mExtras;

    private static final int DIALOG_ERROR_NETWORK = 0;

    private static final int DIALOG_ERROR_SAVING = 1;

    private static final int DIALOG_LOADING_CATEGORIES = 2;

    private static final int DIALOG_LOADING_LOCATIONS = 3;

    private static final int DIALOG_CHOOSE_IMAGE_METHOD = 4;

    private static final int DIALOG_MULTIPLE_CATEGORY = 6;

    private static final int TIME_DIALOG_ID = 7;

    private static final int DATE_DIALOG_ID = 8;

    private final static Handler mHandler = new Handler();

    private Vector mVectorCategories = new Vector();

    private Vector mCategoriesId = new Vector();

    private HashMap mCategoriesTitle = new HashMap();

    private HashMap mParams = new HashMap();

    public static final String PREFS_NAME = "UshahidiService";

    @Override
>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
Solution content
    private boolean mError = false;

    private EditText mIncidentTitle;

    private EditText mIncidentLocation;

    private EditText mIncidentDesc;

    private TextView mIncidentDate;

    private ImageView mSelectedPhoto;

    private TextView mSelectedCategories;

    private Button mBtnSend;

    private Button mBtnCancel;

    private Button mBtnAddCategory;

    private Button mPickTime;

    private Button mPickDate;

    private Button mBtnPicture;

    private Button mAddLocation;

    private HashMap mTimeDigits;

    private Bundle mBundle;

    private Bundle mExtras;

    private static final int DIALOG_ERROR_NETWORK = 0;

    private static final int DIALOG_ERROR_SAVING = 1;

    private static final int DIALOG_CHOOSE_IMAGE_METHOD = 2;

    private static final int DIALOG_MULTIPLE_CATEGORY = 3;

    private static final int TIME_DIALOG_ID = 4;

    private static final int DATE_DIALOG_ID = 5;

    private final static Handler mHandler = new Handler();

    private Vector mVectorCategories = new Vector();

    private Vector mCategoriesId = new Vector();

    private HashMap mCategoriesTitle = new HashMap();

    private HashMap mParams = new HashMap();

    public static final String PREFS_NAME = "UshahidiPref";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
File
AddIncident.java
Developer's decision
Version 1
Kind of conflict
Annotation
Attribute
Method invocation
Chunk
Conflicting content
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.add_incident);
        mFoundAddresses = new ArrayList
(); <<<<<<< HEAD mGc = new Geocoder(this); //load settings UshahidiPref.loadSettings(AddIncident.this); ======= mGc = new Geocoder(this); // load settings UshahidiService.loadSettings(AddIncident.this); >>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146 initComponents(); }
Solution content
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.add_incident);
        mFoundAddresses = new ArrayList
(); mGc = new Geocoder(this); // load settings UshahidiPref.loadSettings(AddIncident.this); initComponents(); }
File
AddIncident.java
Developer's decision
Version 1
Kind of conflict
Attribute
Comment
Method invocation
Chunk
Conflicting content
				
		
		
				if( !hasFocus ) {
        }
        return false;
    }
<<<<<<< HEAD
	
	//menu stuff
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo) {
		populateMenu(menu);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		populateMenu(menu);

		return(super.onCreateOptionsMenu(menu));
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return(applyMenuChoice(item) ||
				super.onOptionsItemSelected(item));
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {

		return(applyMenuChoice(item) ||
				super.onContextItemSelected(item));
	}
	
	private void populateMenu(Menu menu) {
		MenuItem i;
		
		i = menu.add( Menu.NONE, HOME, Menu.NONE, R.string.menu_home );
		i.setIcon(R.drawable.ushahidi_home);
		
		i = menu.add( Menu.NONE, LIST_INCIDENT, Menu.NONE, R.string.incident_list );
		i.setIcon(R.drawable.ushahidi_list);
		  
		i = menu.add( Menu.NONE, INCIDENT_MAP, Menu.NONE, R.string.incident_menu_map );
		i.setIcon(R.drawable.ushahidi_map);
		  
		
		i = menu.add( Menu.NONE, INCIDENT_REFRESH, Menu.NONE, R.string.incident_menu_refresh );
		i.setIcon(R.drawable.ushahidi_refresh);
		  
		i = menu.add( Menu.NONE, SETTINGS, Menu.NONE, R.string.menu_settings );
		i.setIcon(R.drawable.ushahidi_settings);
		  
		i = menu.add( Menu.NONE, ABOUT, Menu.NONE, R.string.menu_about );
		i.setIcon(R.drawable.ushahidi_about);
		
		
	}
	
	private boolean applyMenuChoice(MenuItem item) {
		Intent launchPreferencesIntent;
		switch (item.getItemId()) {
		
		case LIST_INCIDENT:
			launchPreferencesIntent = new Intent( AddIncident.this,ListIncidents.class);
    		startActivityForResult(launchPreferencesIntent, LIST_INCIDENTS);
    		setResult(RESULT_OK);
			return true;
	
		mIncidentTitle.setOnFocusChangeListener(new View.OnFocusChangeListener() {

					if(TextUtils.isEmpty(mIncidentTitle.getText())) {
                    addReportsTask.execute();

		case INCIDENT_MAP:
			public void onFocusChange(View v, boolean hasFocus) {
			launchPreferencesIntent = new Intent( AddIncident.this, ViewIncidents.class);
    		startActivityForResult(launchPreferencesIntent,MAP_INCIDENTS);
			return true;
	
		case HOME:
			launchPreferencesIntent = new Intent( AddIncident.this,Ushahidi.class);
    		startActivityForResult(launchPreferencesIntent, GOTOHOME);
    		setResult(RESULT_OK);
			return true;
		
		case ABOUT:
			launchPreferencesIntent = new Intent( AddIncident.this,About.class);
    		startActivityForResult(launchPreferencesIntent, REQUEST_CODE_ABOUT);
    		setResult(RESULT_OK);
			return true;
			
		case SETTINGS:	
			launchPreferencesIntent = new Intent().setClass(AddIncident.this, Settings.class);
			
			// Make it a subactivity so we know when it returns
			startActivityForResult(launchPreferencesIntent, REQUEST_CODE_SETTINGS);
			return true;
		
		}
		return false;
	}
	
	/**
	 * Initialize UI components
	 */
	private void initComponents(){
		mBtnPicture = (Button) findViewById(R.id.btnPicture);
		mBtnAddCategory = (Button) findViewById(R.id.add_category);
		mBtnSend = (Button) findViewById(R.id.incident_add_btn);
		mBtnCancel = (Button) findViewById(R.id.incident_add_cancel);
		mIncidentDate = (TextView) findViewById(R.id.lbl_date);
		mPickDate = (Button) findViewById(R.id.pick_date);
		mPickTime = (Button) findViewById(R.id.pick_time);
		mAddLocation = (Button) findViewById(R.id.location);
	
		mSelectedPhoto = (ImageView) findViewById(R.id.sel_photo_prev);
		mSelectedCategories = (TextView) findViewById(R.id.lbl_category);
		
		mIncidentTitle = (EditText) findViewById(R.id.incident_title);
		mIncidentLocation = (EditText) findViewById(R.id.incident_location);
						mIncidentTitle.setError(getString(R.string.empty_report_title));
					}
				}
				
			}
			
		});
		
		mIncidentLocation.setOnFocusChangeListener( new View.OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				if( !hasFocus ) {
					if( TextUtils.isEmpty(mIncidentLocation.getText())) {
						mIncidentLocation.setError(getString(R.string.empty_report_location));
					}
				}
			}
		});
		
		mIncidentDesc = (EditText) findViewById(R.id.incident_desc);
		mIncidentDesc.setOnFocusChangeListener(new View.OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				if( !hasFocus ) {
					if(TextUtils.isEmpty(mIncidentDesc.getText())) {
						mIncidentDesc.setError(getString(R.string.empty_report_description));
					}
				}
			}
			
		});
		
		//open location map window
		mAddLocation.setOnClickListener( new View.OnClickListener(){
			public void onClick( View v ) {
				
				Intent intent = new Intent( AddIncident.this,LocationMap.class);
				startActivityForResult(intent,VIEW_MAP);
				setResult( RESULT_OK, intent );
				
			}
		});
		
		mBtnSend.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v){
				//Dipo Fix
				mError = false;
				if( TextUtils.isEmpty(mIncidentTitle.getText())) {
					mErrorMessage = getString(R.string.empty_report_title);
					mError = true;
				}
				
				if( TextUtils.isEmpty(mIncidentDesc.getText())) {
					mErrorMessage += getString(R.string.empty_report_description);
					mError = true;
				}
				if( TextUtils.isEmpty(mIncidentLocation.getText())) {
					mErrorMessage += getString(R.string.empty_report_location);
					mError = true;
				}
				
				//Dipo Fix
				if(mVectorCategories.size() == 0) {
					mErrorMessage += getString(R.string.empty_report_categories);
					mError = true;
				}
				
				if( !mError ) {
					
					AddReportsTask addReportsTask = new AddReportsTask();
					addReportsTask.appContext = AddIncident.this;
					addReportsTask.execute();
					
				}else{
					final Toast t = Toast.makeText(AddIncident.this,
							"Error!\n\n"+ mErrorMessage,
							Toast.LENGTH_LONG);
					t.show();
					mErrorMessage = "";
				}
			 
				
				}
			});
		
		mBtnPicture.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(DIALOG_CHOOSE_IMAGE_METHOD);
			}
		});
		
		mBtnCancel.setOnClickListener( new View.OnClickListener() {
			public void onClick(View v) {
				clearFields();
				Intent intent = new Intent( AddIncident.this,Ushahidi.class);
        		startActivityForResult( intent, GOTOHOME );
        		setResult(RESULT_OK);
        		finish();
			}
		});
		
		mBtnAddCategory.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(DIALOG_MULTIPLE_CATEGORY);
				mCounter++;
			}
		});
		
		mPickDate.setOnClickListener(new View.OnClickListener() {
=======

    /**
     * Initialize UI components
     */
    private void initComponents() {
        mBtnPicture = (Button)findViewById(R.id.btnPicture);
        mBtnAddCategory = (Button)findViewById(R.id.add_category);
        mBtnSend = (Button)findViewById(R.id.incident_add_btn);
        mBtnCancel = (Button)findViewById(R.id.incident_add_cancel);
        mIncidentDate = (TextView)findViewById(R.id.lbl_date);
        mPickDate = (Button)findViewById(R.id.pick_date);
        mPickTime = (Button)findViewById(R.id.pick_time);
        mAddLocation = (Button)findViewById(R.id.location);

        mSelectedPhoto = (TextView)findViewById(R.id.lbl_photo);
        mSelectedCategories = (TextView)findViewById(R.id.lbl_category);

        mIncidentTitle = (EditText)findViewById(R.id.incident_title);
        mIncidentLocation = (EditText)findViewById(R.id.incident_location);

        mIncidentTitle.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    if (TextUtils.isEmpty(mIncidentTitle.getText())) {
                        mIncidentTitle.setError(getString(R.string.empty_report_title));
                    }
                }

            }

        });

        mIncidentLocation.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    if (TextUtils.isEmpty(mIncidentLocation.getText())) {
                        mIncidentLocation.setError(getString(R.string.empty_report_location));
                    }
                }
            }
        });

        mIncidentDesc = (EditText)findViewById(R.id.incident_desc);
        mIncidentDesc.setOnFocusChangeListener(new View.OnFocusChangeListener() {

                    addReportsTask.appContext = AddIncident.this;
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    if (TextUtils.isEmpty(mIncidentDesc.getText())) {
                        mIncidentDesc.setError(getString(R.string.empty_report_description));
                    }
                }
            }

        });

        // open location map window
        mAddLocation.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                Intent intent = new Intent(AddIncident.this, LocationMap.class);
                startActivityForResult(intent, VIEW_MAP);
                setResult(RESULT_OK, intent);

            }
        });

        mBtnSend.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Dipo Fix
                mError = false;
                if (TextUtils.isEmpty(mIncidentTitle.getText())) {
                    mErrorMessage = getString(R.string.empty_report_title);
                    mError = true;
                }

                if (TextUtils.isEmpty(mIncidentDesc.getText())) {
                    mErrorMessage += getString(R.string.empty_report_description);
                    mError = true;
                }

                if (TextUtils.isEmpty(mIncidentLocation.getText())) {
                    mErrorMessage += getString(R.string.empty_report_location);
                    mError = true;
                }

                // Dipo Fix
                if (mVectorCategories.size() == 0) {
                    mErrorMessage += getString(R.string.empty_report_categories);
                    mError = true;
                }

                if (!mError) {

                    AddReportsTask addReportsTask = new AddReportsTask();
                } else {
                    final Toast t = Toast.makeText(AddIncident.this, "Error!\n\n" + mErrorMessage,
                            Toast.LENGTH_LONG);
                    t.show();
                    mErrorMessage = "";
                }

            }
        });

        mBtnPicture.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DIALOG_CHOOSE_IMAGE_METHOD);
            }
        });

        mBtnCancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                clearFields();
                Intent intent = new Intent(AddIncident.this, Ushahidi.class);
                startActivityForResult(intent, GOTOHOME);
                setResult(RESULT_OK);
                finish();
            }
        });

        mBtnAddCategory.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DIALOG_MULTIPLE_CATEGORY);
                mCounter++;
            }
        });

        mPickDate.setOnClickListener(new View.OnClickListener() {
>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146

            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
Solution content
        }
        return false;
    }

    /**
     * Initialize UI components
     */
    private void initComponents() {
        mBtnPicture = (Button)findViewById(R.id.btnPicture);
        mBtnAddCategory = (Button)findViewById(R.id.add_category);
        mBtnSend = (Button)findViewById(R.id.incident_add_btn);
        mBtnCancel = (Button)findViewById(R.id.incident_add_cancel);
        mIncidentDate = (TextView)findViewById(R.id.lbl_date);
        mPickDate = (Button)findViewById(R.id.pick_date);
        mPickTime = (Button)findViewById(R.id.pick_time);
        mAddLocation = (Button)findViewById(R.id.location);

        mSelectedPhoto = (ImageView)findViewById(R.id.sel_photo_prev);
        mSelectedCategories = (TextView)findViewById(R.id.lbl_category);

        mIncidentTitle = (EditText)findViewById(R.id.incident_title);
        mIncidentLocation = (EditText)findViewById(R.id.incident_location);

        mIncidentTitle.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    if (TextUtils.isEmpty(mIncidentTitle.getText())) {
                        mIncidentTitle.setError(getString(R.string.empty_report_title));
                    }
                }

            }

        });

        mIncidentLocation.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    if (TextUtils.isEmpty(mIncidentLocation.getText())) {
                        mIncidentLocation.setError(getString(R.string.empty_report_location));
                    }
                }
            }
        });

        mIncidentDesc = (EditText)findViewById(R.id.incident_desc);
        mIncidentDesc.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    if (TextUtils.isEmpty(mIncidentDesc.getText())) {
                        mIncidentDesc.setError(getString(R.string.empty_report_description));
                    }
                }
            }

        });

        // open location map window
        mAddLocation.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                Intent intent = new Intent(AddIncident.this, LocationMap.class);
                startActivityForResult(intent, VIEW_MAP);
                setResult(RESULT_OK, intent);

            }
        });

        mBtnSend.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Dipo Fix
                mError = false;
                if (TextUtils.isEmpty(mIncidentTitle.getText())) {
                    mErrorMessage = getString(R.string.empty_report_title);
                    mError = true;
                }

                if (TextUtils.isEmpty(mIncidentDesc.getText())) {
                    mErrorMessage += getString(R.string.empty_report_description);
                    mError = true;
                }

                if (TextUtils.isEmpty(mIncidentLocation.getText())) {
                    mErrorMessage += getString(R.string.empty_report_location);
                    mError = true;
                }

                // Dipo Fix
                if (mVectorCategories.size() == 0) {
                    mErrorMessage += getString(R.string.empty_report_categories);
                    mError = true;
                }

                if (!mError) {

                    AddReportsTask addReportsTask = new AddReportsTask();
                    addReportsTask.appContext = AddIncident.this;
                    addReportsTask.execute();

                } else {
                    final Toast t = Toast.makeText(AddIncident.this, "Error!\n\n" + mErrorMessage,
                            Toast.LENGTH_LONG);
                    t.show();
                    mErrorMessage = "";
                }

            }
        });

        mBtnPicture.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DIALOG_CHOOSE_IMAGE_METHOD);
            }
        });

        mBtnCancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                clearFields();
                Intent intent = new Intent(AddIncident.this, Ushahidi.class);
                startActivityForResult(intent, GOTOHOME);
                setResult(RESULT_OK);
                finish();
            }
        });

        mBtnAddCategory.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DIALOG_MULTIPLE_CATEGORY);
                mCounter++;
            }
        });

        mPickDate.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
File
AddIncident.java
Developer's decision
Combination
Kind of conflict
Annotation
Attribute
Cast expression
Comment
Method declaration
Method invocation
Method signature
Chunk
Conflicting content
				mBundle = null;
        }
    }

        mMinute = c.get(Calendar.MINUTE);
        c.get(Calendar.AM_PM);
        updateDisplay();
<<<<<<< HEAD
        
	}
	
	//fetch categories
	public String[] showCategories() {
				mExtras = data.getExtras();
		super.onActivityResult(requestCode, resultCode, data);
				mBundle = null;
				
		// The preferences returned if the request code is what we had given
		// earlier in startSubActivity
		switch(requestCode) {
		
			case REQUEST_CODE_CAMERA:
				if(resultCode != RESULT_OK){
					return;
				}
				
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);	//pull it out of landscape mode
        mVectorCategories.clear();
		  Cursor cursor = UshahidiApplication.mDb.fetchAllCategories();
		  
		  String categories[] = new String[cursor.getCount()];
	
		  int i = 0;
		  if (cursor.moveToFirst()) {
			  
			  int titleIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.CATEGORY_TITLE);
			  
			  int idIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.CATEGORY_ID);
			  
			  do {
				  categories[i] = cursor.getString(titleIndex);
				  mCategoriesTitle.put(String.valueOf(cursor.getInt(idIndex)), 
						  cursor.getString(titleIndex));
				  mCategoriesId.add(String.valueOf(cursor.getInt(idIndex)));
				  i++;
			  }while( cursor.moveToNext() );
		  }
		 
		  cursor.close();
		  return categories;
		  
	}
	
	//reset records in the field
	private void clearFields() {
		mBtnPicture = (Button) findViewById(R.id.btnPicture);
		mBtnAddCategory = (Button) findViewById(R.id.add_category);
		mIncidentTitle.setText("");
		mIncidentLocation.setText("");
		mIncidentDesc.setText("");
		mVectorCategories.clear();
		mSelectedCategories.setText("");
		mCounter = 0;
		updateDisplay();
		
		//clear persistent data
		 SharedPreferences.Editor editor = getPreferences(0).edit();
	     editor.putString("title", "");
	     editor.putString("desc", "");
	     editor.putString("date", "");
	     editor.commit();
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
				mExtras = data.getExtras();
				if ( mExtras != null ) mBundle = mExtras.getBundle("filename");
				
				if ( mBundle != null && !mBundle.isEmpty() ) {
					UshahidiPref.fileName = mBundle.getString("name");
					mSelectedPhoto.setImageDrawable(ImageManager.getImages(UshahidiPref.fileName));
				}
				break;
	
			case REQUEST_CODE_IMAGE:
				
				if(resultCode != RESULT_OK){
					return;
				}
				
				Uri uri = data.getData();
				Bitmap b = null;
				
				try {
					b = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
				} catch (FileNotFoundException e) {
					break;
				} catch (IOException e) {
					break;
				}
				
				ByteArrayOutputStream byteArrayos = new ByteArrayOutputStream();
				
				try {
					b.compress(CompressFormat.JPEG, 75, byteArrayos);				
					byteArrayos.flush();
				} catch (OutOfMemoryError e){
					break;
				} catch (IOException e) {
					break;
				}
				
				mFilename = "android_pic_upload" + randomString() + ".jpg";
				ImageManager.writeImage(byteArrayos.toByteArray(), mFilename);
				UshahidiPref.fileName = mFilename;
				mSelectedPhoto.setImageBitmap(ImageManager.getBitmap(UshahidiPref.fileName));
				break;
				
			case VIEW_MAP:
				if(resultCode != RESULT_OK){
					return;
				}
				if( mExtras != null ) mBundle = mExtras.getBundle("locations");
				
				if( mBundle != null && !mBundle.isEmpty() ) {
					mIncidentLocation.setText( mBundle.getString("location"));
				
					AddIncident.sLatitude = mBundle.getDouble("latitude");
					AddIncident.sLongitude = mBundle.getDouble("longitude");
				}
				break;
		}
	}
	
	private static Random random = new Random();

	protected static String randomString() {
		return Long.toString(random.nextLong(), 10);
	}
	
	//
	final Runnable mSentIncidentOffline = new Runnable() {
		public void run() {
			if( addToDb() == -1 ) {
				mHandler.post(mSentIncidentFail);
			}else { 
				mHandler.post(mSentIncidentOfflineSuccess);
				//clearFields();
			}
		}
	};
	
	final Runnable mSentIncidentFail = new Runnable() {
		public void run() {
			Util.showToast(AddIncident.this, R.string.failed_to_add_report_online);
		}
	};
	
	final Runnable mSentIncidentOfflineFail = new Runnable() {
		public void run() {
			Util.showToast(AddIncident.this, R.string.failed_to_add_report_offline);
		}
	};
	
	final Runnable mSentIncidentOfflineSuccess = new Runnable() {
		public void run() {
			Util.showToast(AddIncident.this, R.string.report_successfully_added_offline);
	
		}
	};
	
	//
	final Runnable mSendIncidentOnline = new Runnable() {
		public void run() {
			if( !postToOnline() ) {
				mHandler.post(mSentIncidentFail);
			}else { 
				mHandler.post(mSentIncidentSuccess);
				
			}
		}
	};
	
	//
	final Runnable mSentIncidentSuccess = new Runnable() {
		public void run() {
			Util.showToast(AddIncident.this, R.string.report_successfully_added_online);
			
		}
	};

	/**
	 * Create various dialog
	 */
	@Override
=======

    }

    // fetch categories
    public String[] showCategories() {
        Cursor cursor = UshahidiApplication.mDb.fetchAllCategories();

        String categories[] = new String[cursor.getCount()];

        int i = 0;
        if (cursor.moveToFirst()) {

            int titleIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.CATEGORY_TITLE);

            int idIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.CATEGORY_ID);

            do {
                categories[i] = cursor.getString(titleIndex);
                mCategoriesTitle.put(String.valueOf(cursor.getInt(idIndex)),
                        cursor.getString(titleIndex));
                mCategoriesId.add(String.valueOf(cursor.getInt(idIndex)));
                i++;
            } while (cursor.moveToNext());
        }

        cursor.close();
        return categories;

    }

    // reset records in the field
    private void clearFields() {
        mBtnPicture = (Button)findViewById(R.id.btnPicture);
        mBtnAddCategory = (Button)findViewById(R.id.add_category);
        mIncidentTitle.setText("");
        mIncidentLocation.setText("");
        mIncidentDesc.setText("");
                if (resultCode != RESULT_OK) {
                    return;
                }

                Uri uri = data.getData();
                Bitmap b = null;

                try {
        mSelectedPhoto.setText("");
        mSelectedCategories.setText("");
        mCounter = 0;
        updateDisplay();

        // clear persistent data
        SharedPreferences.Editor editor = getPreferences(0).edit();
        editor.putString("title", "");
        editor.putString("desc", "");
        editor.putString("date", "");
        editor.commit();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // The preferences returned if the request code is what we had given
        // earlier in startSubActivity
        switch (requestCode) {

            case REQUEST_CODE_CAMERA:
                if (resultCode != RESULT_OK) {
                    return;
                }

                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); // pull
                                                                                      // it
                                                                                      // out
                                                                                      // of
                                                                                      // landscape
                                                                                      // mode
                mBundle = null;
                mExtras = data.getExtras();
                if (mExtras != null)
                    mBundle = mExtras.getBundle("filename");

                if (mBundle != null && !mBundle.isEmpty()) {
                    UshahidiService.fileName = mBundle.getString("name");
                    mSelectedPhoto.setText(UshahidiService.fileName);
                }
                break;

            case REQUEST_CODE_IMAGE:

                    b = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                } catch (FileNotFoundException e) {
                    break;
                } catch (IOException e) {
                    break;
                }

                ByteArrayOutputStream byteArrayos = new ByteArrayOutputStream();

                try {
                    b.compress(CompressFormat.JPEG, 75, byteArrayos);
                    byteArrayos.flush();
                } catch (OutOfMemoryError e) {
                    break;
                } catch (IOException e) {
                    break;
                }

                mFilename = "android_pic_upload" + randomString() + ".jpg";
                ImageManager.writeImage(byteArrayos.toByteArray(), mFilename);
                UshahidiService.fileName = mFilename;
                mSelectedPhoto.setText(UshahidiService.fileName);
                break;

            case VIEW_MAP:
                if (resultCode != RESULT_OK) {
                    return;
                }

                mBundle = null;
                mExtras = data.getExtras();
                if (mExtras != null)
                    mBundle = mExtras.getBundle("locations");

                if (mBundle != null && !mBundle.isEmpty()) {
                    mIncidentLocation.setText(mBundle.getString("location"));

                    AddIncident.sLatitude = mBundle.getDouble("latitude");
                    AddIncident.sLongitude = mBundle.getDouble("longitude");
                }
                break;
>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
    private static Random random = new Random();

    protected static String randomString() {
        return Long.toString(random.nextLong(), 10);
    }

    //
    final Runnable mSentIncidentOffline = new Runnable() {
        public void run() {
            if (addToDb() == -1) {
                mHandler.post(mSentIncidentFail);
            } else {
                mHandler.post(mSentIncidentOfflineSuccess);
                // clearFields();
            }
        }
    };

    final Runnable mSentIncidentFail = new Runnable() {
        public void run() {
            Util.showToast(AddIncident.this, R.string.failed_to_add_report_online);
        }
    };

    final Runnable mSentIncidentOfflineFail = new Runnable() {
        public void run() {
            Util.showToast(AddIncident.this, R.string.failed_to_add_report_offline);
        }
    };

    final Runnable mSentIncidentOfflineSuccess = new Runnable() {
        public void run() {
            Util.showToast(AddIncident.this, R.string.report_successfully_added_offline);

        }
    };

    //
    final Runnable mSendIncidentOnline = new Runnable() {
        public void run() {
            if (!postToOnline()) {
                mHandler.post(mSentIncidentFail);
            } else {
                mHandler.post(mSentIncidentSuccess);

            }
        }
    };

    //
    final Runnable mSentIncidentSuccess = new Runnable() {
        public void run() {
            Util.showToast(AddIncident.this, R.string.report_successfully_added_online);

        }
    };

    /**
     * Create various dialog
     */
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_ERROR_NETWORK: {
Solution content
        mMinute = c.get(Calendar.MINUTE);
        c.get(Calendar.AM_PM);
        updateDisplay();

    }

    // fetch categories
    public String[] showCategories() {
        Cursor cursor = UshahidiApplication.mDb.fetchAllCategories();

        String categories[] = new String[cursor.getCount()];

        int i = 0;
        if (cursor.moveToFirst()) {

            int titleIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.CATEGORY_TITLE);

            int idIndex = cursor.getColumnIndexOrThrow(UshahidiDatabase.CATEGORY_ID);

            do {
                categories[i] = cursor.getString(titleIndex);
                mCategoriesTitle.put(String.valueOf(cursor.getInt(idIndex)),
                        cursor.getString(titleIndex));
                mCategoriesId.add(String.valueOf(cursor.getInt(idIndex)));
                i++;
            } while (cursor.moveToNext());
        }

        cursor.close();
        return categories;

    }

    // reset records in the field
    private void clearFields() {
        mBtnPicture = (Button)findViewById(R.id.btnPicture);
        mBtnAddCategory = (Button)findViewById(R.id.add_category);
        mIncidentTitle.setText("");
        mIncidentLocation.setText("");
        mIncidentDesc.setText("");
        mVectorCategories.clear();
        mSelectedCategories.setText("");
        mCounter = 0;
        updateDisplay();

        // clear persistent data
        SharedPreferences.Editor editor = getPreferences(0).edit();
        editor.putString("title", "");
        editor.putString("desc", "");
        editor.putString("date", "");
        editor.commit();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // The preferences returned if the request code is what we had given
        // earlier in startSubActivity
        switch (requestCode) {

            case REQUEST_CODE_CAMERA:
                if (resultCode != RESULT_OK) {
                    return;
                }

                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); // pull
                                                                                      // it
                                                                                      // out
                                                                                      // of
                                                                                      // landscape
                                                                                      // mode
                mBundle = null;
                mExtras = data.getExtras();
                if (mExtras != null)
                    mBundle = mExtras.getBundle("filename");

                if (mBundle != null && !mBundle.isEmpty()) {
                    UshahidiPref.fileName = mBundle.getString("name");
                    mSelectedPhoto.setImageDrawable(ImageManager.getImages(UshahidiPref.fileName));
                }
                break;

            case REQUEST_CODE_IMAGE:

                if (resultCode != RESULT_OK) {
                    return;
                }

                Uri uri = data.getData();
            Util.showToast(AddIncident.this, R.string.failed_to_add_report_offline);
        }
    final Runnable mSentIncidentOfflineFail = new Runnable() {
        public void run() {
                Bitmap b = null;

                try {
                    b = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                } catch (FileNotFoundException e) {
                    break;
                } catch (IOException e) {
                    break;
                }

                ByteArrayOutputStream byteArrayos = new ByteArrayOutputStream();

                try {
                    b.compress(CompressFormat.JPEG, 75, byteArrayos);
                    byteArrayos.flush();
                } catch (OutOfMemoryError e) {
                    break;
                } catch (IOException e) {
                    break;
                }

                mFilename = "android_pic_upload" + randomString() + ".jpg";
                ImageManager.writeImage(byteArrayos.toByteArray(), mFilename);
                UshahidiPref.fileName = mFilename;
                mSelectedPhoto.setImageBitmap(ImageManager.getBitmap(UshahidiPref.fileName));
                break;

            case VIEW_MAP:
                if (resultCode != RESULT_OK) {
                    return;
                }

                mBundle = null;
                mExtras = data.getExtras();
                if (mExtras != null)
                    mBundle = mExtras.getBundle("locations");

                if (mBundle != null && !mBundle.isEmpty()) {
                    mIncidentLocation.setText(mBundle.getString("location"));

                    AddIncident.sLatitude = mBundle.getDouble("latitude");
                    AddIncident.sLongitude = mBundle.getDouble("longitude");
                }
                break;
        }
    }

    private static Random random = new Random();

    protected static String randomString() {
        return Long.toString(random.nextLong(), 10);
    }

    //
    final Runnable mSentIncidentOffline = new Runnable() {
        public void run() {
            if (addToDb() == -1) {
                mHandler.post(mSentIncidentFail);
            } else {
                mHandler.post(mSentIncidentOfflineSuccess);
                // clearFields();
            }
        }
    };

    final Runnable mSentIncidentFail = new Runnable() {
        public void run() {
            Util.showToast(AddIncident.this, R.string.failed_to_add_report_online);
        }
    };

    };

    final Runnable mSentIncidentOfflineSuccess = new Runnable() {
        public void run() {
            Util.showToast(AddIncident.this, R.string.report_successfully_added_offline);

        }
    };

    //
    final Runnable mSendIncidentOnline = new Runnable() {
        public void run() {
            if (!postToOnline()) {
                mHandler.post(mSentIncidentFail);
            } else {
                mHandler.post(mSentIncidentSuccess);

            }
        }
    };

    //
    final Runnable mSentIncidentSuccess = new Runnable() {
        public void run() {
            Util.showToast(AddIncident.this, R.string.report_successfully_added_online);

        }
    };

    /**
     * Create various dialog
     */
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_ERROR_NETWORK: {
File
AddIncident.java
Developer's decision
Combination
Kind of conflict
Annotation
Attribute
Comment
Method declaration
Method invocation
Chunk
Conflicting content
     * @author henryaddo
     */
    public long addToDb() {
<<<<<<< HEAD
    	String dates[] = mDateToSubmit.split(" ");
    	String time[] = dates[1].split(":");
    	
    	List addIncidentsData = new ArrayList();
    	AddIncidentData addIncidentData = new AddIncidentData();
    	addIncidentsData.add(addIncidentData);
    	
    	addIncidentData.setIncidentTitle(mIncidentTitle.getText().toString());
    	addIncidentData.setIncidentDesc(mIncidentDesc.getText().toString());
    	addIncidentData.setIncidentDate(dates[0]);
    	addIncidentData.setIncidentHour(Integer.parseInt(time[0]));
    	addIncidentData.setIncidentMinute(Integer.parseInt(time[1]));
    	addIncidentData.setIncidentAmPm(dates[2]);
    	addIncidentData.setIncidentCategories(Util.implode(mVectorCategories));
    	addIncidentData.setIncidentLocName(mIncidentLocation.getText().toString());
    	addIncidentData.setIncidentLocLatitude(String.valueOf(sLatitude));
    	addIncidentData.setIncidentLocLongitude(String.valueOf(sLongitude));
    	addIncidentData.setIncidentPhoto(UshahidiPref.fileName);
    	addIncidentData.setPersonFirst(UshahidiPref.firstname);
    	addIncidentData.setPersonLast(UshahidiPref.lastname);
    	addIncidentData.setPersonEmail(UshahidiPref.email);
    	
    	//add it to database.
    	return UshahidiApplication.mDb.addIncidents(addIncidentsData);
=======
        String dates[] = mDateToSubmit.split(" ");
        String time[] = dates[1].split(":");

        List addIncidentsData = new ArrayList();
        AddIncidentData addIncidentData = new AddIncidentData();
        addIncidentsData.add(addIncidentData);

        addIncidentData.setIncidentTitle(mIncidentTitle.getText().toString());
        addIncidentData.setIncidentDesc(mIncidentDesc.getText().toString());
        addIncidentData.setIncidentDate(dates[0]);
        addIncidentData.setIncidentHour(Integer.parseInt(time[0]));
        addIncidentData.setIncidentMinute(Integer.parseInt(time[1]));
        addIncidentData.setIncidentAmPm(dates[2]);
        addIncidentData.setIncidentCategories(Util.implode(mVectorCategories));
        addIncidentData.setIncidentLocName(mIncidentLocation.getText().toString());
        addIncidentData.setIncidentLocLatitude(String.valueOf(sLatitude));
        addIncidentData.setIncidentLocLongitude(String.valueOf(sLongitude));
        addIncidentData.setIncidentPhoto(UshahidiService.fileName);
        addIncidentData.setPersonFirst(UshahidiService.firstname);
        addIncidentData.setPersonLast(UshahidiService.lastname);
        addIncidentData.setPersonEmail(UshahidiService.email);

        // add it to database.
        return UshahidiApplication.mDb.addIncidents(addIncidentsData);
>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
    }

    /**
Solution content
     * @author henryaddo
     */
    public long addToDb() {

        String dates[] = mDateToSubmit.split(" ");
        String time[] = dates[1].split(":");

        List addIncidentsData = new ArrayList();
        AddIncidentData addIncidentData = new AddIncidentData();
        addIncidentsData.add(addIncidentData);

        addIncidentData.setIncidentTitle(mIncidentTitle.getText().toString());
        addIncidentData.setIncidentDesc(mIncidentDesc.getText().toString());
        addIncidentData.setIncidentDate(dates[0]);
        addIncidentData.setIncidentHour(Integer.parseInt(time[0]));
        addIncidentData.setIncidentMinute(Integer.parseInt(time[1]));
        addIncidentData.setIncidentAmPm(dates[2]);
        addIncidentData.setIncidentCategories(Util.implode(mVectorCategories));
        addIncidentData.setIncidentLocName(mIncidentLocation.getText().toString());
        addIncidentData.setIncidentLocLatitude(String.valueOf(sLatitude));
        addIncidentData.setIncidentLocLongitude(String.valueOf(sLongitude));
        addIncidentData.setIncidentPhoto(UshahidiPref.fileName);
        addIncidentData.setPersonFirst(UshahidiPref.firstname);
        addIncidentData.setPersonLast(UshahidiPref.lastname);
        addIncidentData.setPersonEmail(UshahidiPref.email);

        // add it to database.
        return UshahidiApplication.mDb.addIncidents(addIncidentsData);

    }

    /**
File
AddIncident.java
Developer's decision
Version 1
Kind of conflict
Comment
Method invocation
Return statement
Variable
Chunk
Conflicting content
     * @author henryaddo
     */
    public boolean postToOnline() {
<<<<<<< HEAD
    	
    	String dates[] = mDateToSubmit.split(" ");
    	String time[] = dates[1].split(":");
    	String categories = Util.implode(mVectorCategories);
    	
    	final SharedPreferences settings = getSharedPreferences(
				PREFS_NAME, 0);
    	
    	StringBuilder urlBuilder = new StringBuilder(settings.getString("Domain", ""));
    	urlBuilder.append("/api");
    	
    	mParams.put("task","report");
		mParams.put("incident_title", mIncidentTitle.getText().toString());
		mParams.put("incident_description", mIncidentDesc.getText().toString()); 
		mParams.put("incident_date", dates[0]); 
		mParams.put("incident_hour", time[0]); 
		mParams.put("incident_minute", time[1]);
		mParams.put("incident_ampm", dates[2].toLowerCase());
		mParams.put("incident_category", categories);
		mParams.put("latitude", String.valueOf(sLatitude));
		mParams.put("longitude", String.valueOf(sLongitude)); 
		mParams.put("location_name", mIncidentLocation.getText().toString());
		mParams.put("person_first", UshahidiPref.firstname);
		mParams.put("person_last", UshahidiPref.lastname);
		mParams.put("person_email", UshahidiPref.email);
		mParams.put("filename", UshahidiPref.fileName);
		
		try {
			return UshahidiHttpClient.PostFileUpload(urlBuilder.toString(), mParams);
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		
=======

        String dates[] = mDateToSubmit.split(" ");
        String time[] = dates[1].split(":");
        String categories = Util.implode(mVectorCategories);

        final SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

        StringBuilder urlBuilder = new StringBuilder(settings.getString("Domain", ""));
        urlBuilder.append("/api");

        mParams.put("task", "report");
        mParams.put("incident_title", mIncidentTitle.getText().toString());
        mParams.put("incident_description", mIncidentDesc.getText().toString());
        mParams.put("incident_date", dates[0]);
        mParams.put("incident_hour", time[0]);
        mParams.put("incident_minute", time[1]);
        mParams.put("incident_ampm", dates[2].toLowerCase());
        mParams.put("incident_category", categories);
        mParams.put("latitude", String.valueOf(sLatitude));
        mParams.put("longitude", String.valueOf(sLongitude));
        mParams.put("location_name", mIncidentLocation.getText().toString());
        mParams.put("person_first", UshahidiService.firstname);
        mParams.put("person_last", UshahidiService.lastname);
        mParams.put("person_email", UshahidiService.email);
        mParams.put("filename", UshahidiService.fileName);

        try {
            return UshahidiHttpClient.PostFileUpload(urlBuilder.toString(), mParams);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
    }

    /**
Solution content
     * @author henryaddo
     */
    public boolean postToOnline() {

        String dates[] = mDateToSubmit.split(" ");
        String time[] = dates[1].split(":");
        String categories = Util.implode(mVectorCategories);

        final SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

        StringBuilder urlBuilder = new StringBuilder(settings.getString("Domain", ""));
        urlBuilder.append("/api");

        mParams.put("task", "report");
        mParams.put("incident_title", mIncidentTitle.getText().toString());
        mParams.put("incident_description", mIncidentDesc.getText().toString());
        mParams.put("incident_date", dates[0]);
        mParams.put("incident_hour", time[0]);
        mParams.put("incident_minute", time[1]);
        mParams.put("incident_ampm", dates[2].toLowerCase());
        mParams.put("incident_category", categories);
        mParams.put("latitude", String.valueOf(sLatitude));
        mParams.put("longitude", String.valueOf(sLongitude));
        mParams.put("location_name", mIncidentLocation.getText().toString());
        mParams.put("person_first", UshahidiPref.firstname);
        mParams.put("person_last", UshahidiPref.lastname);
        mParams.put("person_email", UshahidiPref.email);
        mParams.put("filename", UshahidiPref.fileName);

        try {
            return UshahidiHttpClient.PostFileUpload(urlBuilder.toString(), mParams);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
File
AddIncident.java
Developer's decision
Version 1
Kind of conflict
Method invocation
Try statement
Variable
Chunk
Conflicting content
	}
    
        }
        return 1;
    }
<<<<<<< HEAD
    
    //thread class
	private class AddReportsTask extends AsyncTask  {
		
		protected Integer status;
		protected Context appContext;
		@Override
		protected void onPreExecute() {
			setProgressBarIndeterminateVisibility(true);

		}
		
		@Override 
		protected Integer doInBackground(Void... mParams) {
			if( Util.isConnected(AddIncident.this) ){
				
				if( !postToOnline() ) {
					status = 1; // fail
				}else { 
					
					status = 0; // success
				}
			}else {
				addToDb();
				status = 2; // no internet connection
			}
			return status;
		}
		
		@Override
		protected void onPostExecute(Integer result)
		{
			if( result == 2 ){
				Util.showToast(appContext, R.string.report_successfully_added_offline);
			}else if( result == 1 ) { 
				Util.showToast(appContext, R.string.failed_to_add_report_online);
			}else if( result == 0 ) {
				clearFields();
				//after a successful upload, delete the file
                File f = new File(UshahidiPref.savePath + UshahidiPref.fileName);
				if(f.exists()){
					f.delete();
				}
				Util.showToast(appContext, R.string.report_successfully_added_online);
			}
			setProgressBarIndeterminateVisibility(false);
		}
=======

    // thread class
    private class AddReportsTask extends AsyncTask {

        protected Integer status;

        protected Context appContext;

        @Override
        protected void onPreExecute() {
            setProgressBarIndeterminateVisibility(true);

        }

        @Override
        protected Integer doInBackground(Void... mParams) {
            if (Util.isConnected(AddIncident.this)) {

                if (!postToOnline()) {
                    status = 1; // fail
                } else {

                    status = 0; // success
                }
            } else {
                addToDb();
                status = 2; // no internet connection
            }
            return status;
        }

        @Override
        protected void onPostExecute(Integer result) {
            if (result == 2) {
                Util.showToast(appContext, R.string.report_successfully_added_offline);
            } else if (result == 1) {
                Util.showToast(appContext, R.string.failed_to_add_report_online);
            } else if (result == 0) {
                clearFields();
                // after a successful upload, delete the file
                File f = new File(UshahidiService.savePath + UshahidiService.fileName);
                if (f.exists()) {
                    f.delete();
                }
                Util.showToast(appContext, R.string.report_successfully_added_online);
            }
            setProgressBarIndeterminateVisibility(false);
        }

    }

>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
}
Solution content
        }
        return 1;
    }

    // thread class
    private class AddReportsTask extends AsyncTask {

        protected Integer status;

        protected Context appContext;

        @Override
        protected void onPreExecute() {
            setProgressBarIndeterminateVisibility(true);

        }

        @Override
        protected Integer doInBackground(Void... mParams) {
            if (Util.isConnected(AddIncident.this)) {

                if (!postToOnline()) {
                    status = 1; // fail
                } else {

                    status = 0; // success
                }
            } else {
                addToDb();
                status = 2; // no internet connection
            }
            return status;
        }

        @Override
        protected void onPostExecute(Integer result) {
            if (result == 2) {
                Util.showToast(appContext, R.string.report_successfully_added_offline);
            } else if (result == 1) {
                Util.showToast(appContext, R.string.failed_to_add_report_online);
            } else if (result == 0) {
                clearFields();
                // after a successful upload, delete the file
                File f = new File(UshahidiPref.savePath + UshahidiPref.fileName);
                if (f.exists()) {
                    f.delete();
                }
                Util.showToast(appContext, R.string.report_successfully_added_online);
            }
            setProgressBarIndeterminateVisibility(false);
        }

    }

}
File
AddIncident.java
Developer's decision
Version 1
Kind of conflict
Class declaration
Comment
Chunk
Conflicting content
}

public class ImageCaptureCallback implements PictureCallback {

<<<<<<< HEAD
	private static Random random = new Random();
	
	protected static String randomString() {
		return Long.toString(random.nextLong(), 10);
	}
	
	public ImageCaptureCallback() {
	
	}
	
	public void onPictureTaken(byte[] data, Camera camera) {
		
		try {
			
			String filename = "ushandroid_" + randomString() + ".jpg";
			ImageManager.writeImage(data, filename);
			UshahidiPref.fileName = filename;
			
		} catch (final Exception ex) {
			ex.printStackTrace();
		}
		
	}
=======
    private static Random random = new Random();

    protected static String randomString() {
        return Long.toString(random.nextLong(), 10);
    }

    public ImageCaptureCallback() {

    }

    public void onPictureTaken(byte[] data, Camera camera) {

        try {

            String filename = "ushandroid_" + randomString() + ".jpg";
            ImageManager.writeImage(data, filename);
            UshahidiService.fileName = filename;

        } catch (final Exception ex) {
            ex.printStackTrace();
        }

    }
>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
Solution content
public class ImageCaptureCallback implements PictureCallback {

    private static Random random = new Random();

    protected static String randomString() {
        return Long.toString(random.nextLong(), 10);
    }

    public ImageCaptureCallback() {

    }

    public void onPictureTaken(byte[] data, Camera camera) {

        try {

            String filename = "ushandroid_" + randomString() + ".jpg";
            ImageManager.writeImage(data, filename);
            UshahidiPref.fileName = filename;

        } catch (final Exception ex) {
            ex.printStackTrace();
        }

    }

}
File
ImageCaptureCallback.java
Developer's decision
Version 1
Kind of conflict
Attribute
Method declaration
Method invocation
Chunk
Conflicting content
import  android.graphics.drawable.BitmapDrawable;

public class ImageManager {
<<<<<<< HEAD
	//Images
	public static Drawable getImages(String fileName) {
		
		Drawable d = null;
		BitmapDrawable bD = new BitmapDrawable(UshahidiPref.savePath + fileName);
		d = bD.mutate();
		/*FileInputStream fIn;
		if( !TextUtils.isEmpty( fileName) ) {
			try {
				fIn = new FileInputStream(UshahidiPref.savePath + fileName);
				d = Drawable.createFromStream(fIn, "src");
			} catch (FileNotFoundException e) {
			
				e.printStackTrace();
			}
		}*/
	
		return d;
	}
	
	
	public static void saveImage() {
		byte[] is;
		for (String image : UshahidiService.mNewIncidentsImages) {
			if (!TextUtils.isEmpty(image)) {
				File f = new File(UshahidiPref.savePath + image);
				if (!f.exists()) {
					try {
						is = UshahidiHttpClient.fetchImage(UshahidiPref.domain+"/media/uploads/"+image);
						if( is != null ) {
							writeImage( is, image );
						}
					} catch (MalformedURLException e) {
						
						e.printStackTrace();
					} catch (IOException e) {
						
						e.printStackTrace();
					}
				
				}
			}
		}
		
	}
	
	public static void saveThumbnail() {
		byte[] is;
    public static Drawable getImages(String fileName) {

		for (String image : UshahidiService.mNewIncidentsThumbnails) {
			if(!TextUtils.isEmpty(image )) {
				File f = new File(UshahidiPref.savePath + image);
				if(!f.exists()) {
					try {
						is = UshahidiHttpClient.fetchImage(UshahidiPref.domain+"/media/uploads/"+image);
						if( is != null ) {
							writeImage(is, image);
						}
					} catch (MalformedURLException e) {
						
						e.printStackTrace();
					} catch (IOException e) {
						
						e.printStackTrace();
					}
				
				}
			}
		}
		
	}
	
	public static void writeImage(byte[] data, String filename) {
		
		deleteImage(filename);
		
		if( data != null ) {
			FileOutputStream fOut;	
			try {
				fOut = new FileOutputStream(UshahidiPref.savePath + filename);
				fOut.write(data);
				fOut.flush();
				fOut.close();
			} catch (final FileNotFoundException e) {
			
				e.printStackTrace();
			} catch (final IOException e) {
			
				e.printStackTrace();
			}
		}
		
	}
	
	public static void deleteImage(String filename) {
		
		File f = new File(UshahidiPref.savePath + filename);
		if (f.exists()){
			f.delete();
		}
	}
	
	public static Bitmap getBitmap(String fileName) {
	    Bitmap bitMap = BitmapFactory.decodeFile(UshahidiPref.savePath + fileName);
	    return bitMap;
	}
	
=======
    // Images
        Drawable d = null;

        FileInputStream fIn;
        if (!TextUtils.isEmpty(fileName)) {
            try {
                fIn = new FileInputStream(UshahidiService.savePath + fileName);
                d = Drawable.createFromStream(fIn, "src");
            } catch (FileNotFoundException e) {

                e.printStackTrace();
            }
        }

        return d;
    }

    public static void saveImage() {
        byte[] is;
        for (String image : UshahidiService.mNewIncidentsImages) {
            if (!TextUtils.isEmpty(image)) {
                File f = new File(UshahidiService.savePath + image);
                if (!f.exists()) {
                    try {
                        is = UshahidiHttpClient.fetchImage(UshahidiService.domain
                                + "/media/uploads/" + image);
                        if (is != null) {
                            writeImage(is, image);
                        }
                    } catch (MalformedURLException e) {

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

                        e.printStackTrace();
                    }

                }
            }
        }

    }

    public static void saveThumbnail() {
        byte[] is;
        for (String image : UshahidiService.mNewIncidentsThumbnails) {
            if (!TextUtils.isEmpty(image)) {
                File f = new File(UshahidiService.savePath + image);
                if (!f.exists()) {
                    try {
                        is = UshahidiHttpClient.fetchImage(UshahidiService.domain
                                + "/media/uploads/" + image);
                        if (is != null) {
                            writeImage(is, image);
                        }
                    } catch (MalformedURLException e) {

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

                        e.printStackTrace();
                    }

                }
            }
        }

    }

    public static void writeImage(byte[] data, String filename) {

        deleteImage(filename);

        if (data != null) {
            FileOutputStream fOut;
            try {
                fOut = new FileOutputStream(UshahidiService.savePath + filename);
                fOut.write(data);
                fOut.flush();
                fOut.close();
            } catch (final FileNotFoundException e) {

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

                e.printStackTrace();
            }
        }

    }

    public static void deleteImage(String filename) {

        File f = new File(UshahidiService.savePath + filename);
        if (f.exists()) {
            f.delete();
        }
    }

>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
}
Solution content
public class ImageManager {

    // Images
    public static Drawable getImages(String fileName) {

        Drawable d = null;
        BitmapDrawable bD = new BitmapDrawable(UshahidiPref.savePath + fileName);
        d = bD.mutate();
        /*
         * FileInputStream fIn; if( !TextUtils.isEmpty( fileName) ) { try { fIn
         * = new FileInputStream(UshahidiPref.savePath + fileName); d =
         * Drawable.createFromStream(fIn, "src"); } catch (FileNotFoundException
         * e) { e.printStackTrace(); } }
         */

        return d;
    }

    public static void saveImage() {
        byte[] is;
        for (String image : UshahidiService.mNewIncidentsImages) {
            if (!TextUtils.isEmpty(image)) {
                File f = new File(UshahidiPref.savePath + image);
                if (!f.exists()) {
                    try {
                        is = UshahidiHttpClient.fetchImage(UshahidiPref.domain + "/media/uploads/"
                                + image);
                        if (is != null) {
                            writeImage(is, image);
                        }
                    } catch (MalformedURLException e) {

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

                        e.printStackTrace();
                    }

                }
            }
        }

    }

    public static void saveThumbnail() {
        byte[] is;
        for (String image : UshahidiService.mNewIncidentsThumbnails) {
            if (!TextUtils.isEmpty(image)) {
                File f = new File(UshahidiPref.savePath + image);
                if (!f.exists()) {
                    try {
                        is = UshahidiHttpClient.fetchImage(UshahidiPref.domain + "/media/uploads/"
                                + image);
                        if (is != null) {
                            writeImage(is, image);
                        }
                    } catch (MalformedURLException e) {

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

                        e.printStackTrace();
                    }

                }
            }
        }

    }

    public static void writeImage(byte[] data, String filename) {

        deleteImage(filename);

        if (data != null) {
            FileOutputStream fOut;
            try {
                fOut = new FileOutputStream(UshahidiPref.savePath + filename);
                fOut.write(data);
                fOut.flush();
                fOut.close();
            } catch (final FileNotFoundException e) {

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

                e.printStackTrace();
            }
        }

    }

    public static void deleteImage(String filename) {

        File f = new File(UshahidiPref.savePath + filename);
        if (f.exists()) {
            f.delete();
        }
    }

    public static Bitmap getBitmap(String fileName) {
        Bitmap bitMap = BitmapFactory.decodeFile(UshahidiPref.savePath + fileName);
        return bitMap;
    }

}
File
ImageManager.java
Developer's decision
Manual
Kind of conflict
Comment
Method declaration
Chunk
Conflicting content
}
        }
		private static Random random = new Random();
import android.util.Log;

public class SaveIncidentsImage extends Thread {
<<<<<<< HEAD
		private byte[] mData;
		public String filename;
		
		protected static String randomString() {
			return Long.toString(random.nextLong(), 36);
		}
		
		public SaveIncidentsImage(byte[] data){
			this.mData = data;
		}
		
		@Override
		public void run() {
			
			filename = "pictureupload" + randomString() + ".jpg";
			
			Log.i("Capture Me", "What: "+ filename);
			
			ImageManager.writeImage(mData, filename);
			UshahidiPref.fileName = filename;
			
			File f = new File(UshahidiPref.savePath + filename);
			if(f.exists()){
				f.delete();
			}
		}
	}
=======
    private byte[] mData;

    private static Random random = new Random();

    public String filename;

    protected static String randomString() {
        return Long.toString(random.nextLong(), 36);
    }

    public SaveIncidentsImage(byte[] data) {
        this.mData = data;
    }

    @Override
    public void run() {

        filename = "pictureupload" + randomString() + ".jpg";

        Log.i("Capture Me", "What: " + filename);

        ImageManager.writeImage(mData, filename);
        UshahidiService.fileName = filename;

        File f = new File(UshahidiService.savePath + filename);
        if (f.exists()) {
            f.delete();
    }
>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
Solution content
        return Long.toString(random.nextLong(), 36);
    }

import android.util.Log;

public class SaveIncidentsImage extends Thread {

    private byte[] mData;

    private static Random random = new Random();

    public String filename;

    protected static String randomString() {
    public SaveIncidentsImage(byte[] data) {
        this.mData = data;
    }

    @Override
    public void run() {

        filename = "pictureupload" + randomString() + ".jpg";

        Log.i("Capture Me", "What: " + filename);

        ImageManager.writeImage(mData, filename);
        UshahidiPref.fileName = filename;

        File f = new File(UshahidiPref.savePath + filename);
        if (f.exists()) {
            f.delete();
        }
    }
}
File
SaveIncidentsImage.java
Developer's decision
Version 1
Kind of conflict
Annotation
Attribute
Method declaration
Method invocation
Chunk
Conflicting content
    private String fromAddress = "";

    private String messageBody = "";
<<<<<<< HEAD
	private static final Object mStartingServiceSync = new Object();
	private static final String TAG = "Ushahidi";
	private static PowerManager.WakeLock mStartingService;
	private HashMap params = new HashMap();
	private Context mContext;

	@Override
	public void onCreate() {
	    
		HandlerThread thread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND);
	    thread.start();
	    mContext = getApplicationContext();
	    UshahidiPref.loadSettings(mContext);
	    mServiceLooper = thread.getLooper();
	    mServiceHandler = new ServiceHandler(mServiceLooper);
	}

	@Override
	public void onStart(Intent intent, int startId) {
	    
		//int mResultCode = intent != null ? intent.getIntExtra("result", 0) : 0;
	    Message msg = mServiceHandler.obtainMessage();
	    msg.arg1 = startId;
	    msg.obj = intent;
	    mServiceHandler.sendMessage(msg);
	}

	@Override
	public void onDestroy() {
	    
		mServiceLooper.quit();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	private final class ServiceHandler extends Handler {
		public ServiceHandler(Looper looper) {
			super(looper);
	    }

		@Override
	    public void handleMessage(Message msg) {
			
			int serviceId = msg.arg1;
			Intent intent = (Intent) msg.obj;
			String action = intent.getAction();
			//String dataType = intent.getType();

			if (ACTION_SMS_RECEIVED.equals(action)) {
				handleSmsReceived(intent);
			} 

			finishStartingService(SmsReceiverService.this, serviceId);
	    }
	}

	/**
	 * Handle receiving a SMS message
	 */
	private void handleSmsReceived(Intent intent) {
		
	    Bundle bundle = intent.getExtras();
	    UshahidiPref.loadSettings(mContext);
	    
	    if (bundle != null) {
	    	SmsMessage[] messages = getMessagesFromIntent(intent);
	    	SmsMessage sms = messages[0];
	    	if (messages != null) {
	    		//extract message details phone number and the message body
	    		fromAddress = sms.getDisplayOriginatingAddress();
	    		
	    		String body;
	    		if (messages.length == 1 || sms.isReplace()) {
	    			body = sms.getDisplayMessageBody();
	    		} else {
	    			StringBuilder bodyText = new StringBuilder();
	    			for (int i = 0; i < messages.length; i++) {
	    				bodyText.append(messages[i].getMessageBody());
	    			}
	    			body = bodyText.toString();
	    		}
	    		messageBody = body;
	    	}
	    }
	    
	    // post sms message to ushahidi
	    if( UshahidiPref.smsUpdate ) {
	    	if( Util.isConnected(SmsReceiverService.this) ){
	    		if( !this.postToUshahidi() ) {
	    			this.showNotification(messageBody, R.string.sms_failed);
	    		} else {
	    			this.showNotification(messageBody, R.string.sms_sent);
	    		}
	    	}
	    }
	}

	
	private boolean postToUshahidi() {
		UshahidiPref.loadSettings(mContext);
		params.put("username", UshahidiPref.username);
		StringBuilder urlBuilder = new StringBuilder(UshahidiPref.domain);
		
    	urlBuilder.append("/api");
    	params.put("task","sms");
				PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
				mStartingService = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
	            	"Sms messages .SmsReceiverService");
		params.put("password", UshahidiPref.password); 
		params.put("message_from", fromAddress); 
		params.put("message_description",messageBody); 
		
		try {
			return UshahidiHttpClient.postSmsToUshahidi(urlBuilder.toString(), params);
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	public static final SmsMessage[] getMessagesFromIntent(Intent intent) {
		Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
	    if (messages == null) {
	    	return null;
	    }
	    if (messages.length == 0) {
	    	return null;
	    }

	    byte[][] pduObjs = new byte[messages.length][];

	    for (int i = 0; i < messages.length; i++) {
	      pduObjs[i] = (byte[]) messages[i];
	    }
	    byte[][] pdus = new byte[pduObjs.length][];
	    int pduCount = pdus.length;
	    SmsMessage[] msgs = new SmsMessage[pduCount];
	    for (int i = 0; i < pduCount; i++) {
	    	pdus[i] = pduObjs[i];
	    	msgs[i] = SmsMessage.createFromPdu(pdus[i]);
	    }
	    return msgs;
	}

	  
	/**
	 * Start the service to process the current event notifications, acquiring the
	 * wake lock before returning to ensure that the service will run.
	 */
	public static void beginStartingService(Context context, Intent intent) {
		synchronized (mStartingServiceSync) {
	      
			if (mStartingService == null) {
				mStartingService.setReferenceCounted(false);
			}
	      
			mStartingService.acquire();
			context.startService(intent);
		}
	}

	/**
	 * Called back by the service when it has finished processing notifications,
	 * releasing the wake lock if the service is now stopping.
	 */
	public static void finishStartingService(Service service, int startId) {
		synchronized (mStartingServiceSync) {
	      
			if (mStartingService != null) {
	      		if (service.stopSelfResult(startId)) {
	      			mStartingService.release();
	      		}
	      	}
		}
	}
	
	/**
	 * Show a notification
	 * 
	 * @param String message to display
	 * @param String notification title
	 */
	private void showNotification(String message, int notification_title ) {
		
		Intent baseIntent = new Intent(this, Settings.class);
=======

    private static final Object mStartingServiceSync = new Object();

    private static final String TAG = "Ushahidi";

    private static PowerManager.WakeLock mStartingService;

    private HashMap params = new HashMap();

    private Context mContext;

    @Override
    public void onCreate() {

        HandlerThread thread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();
        mContext = getApplicationContext();
        UshahidiService.loadSettings(mContext);
        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

    @Override
    public void onStart(Intent intent, int startId) {

            if (messages != null) {
        Object[] messages = (Object[])intent.getSerializableExtra("pdus");
        // int mResultCode = intent != null ? intent.getIntExtra("result", 0) :
        // 0;
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }

    @Override
    public void onDestroy() {

        mServiceLooper.quit();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {

            int serviceId = msg.arg1;
            Intent intent = (Intent)msg.obj;
            String action = intent.getAction();
            // String dataType = intent.getType();

            if (ACTION_SMS_RECEIVED.equals(action)) {
                handleSmsReceived(intent);
            }

            finishStartingService(SmsReceiverService.this, serviceId);
        }
    }

    /**
     * Handle receiving a SMS message
     */
    private void handleSmsReceived(Intent intent) {

        Bundle bundle = intent.getExtras();
        UshahidiService.loadSettings(mContext);

        if (bundle != null) {
            SmsMessage[] messages = getMessagesFromIntent(intent);
            SmsMessage sms = messages[0];
                // extract message details phone number and the message body
                fromAddress = sms.getDisplayOriginatingAddress();

                String body;
                if (messages.length == 1 || sms.isReplace()) {
                    body = sms.getDisplayMessageBody();
                } else {
                    StringBuilder bodyText = new StringBuilder();
                    for (int i = 0; i < messages.length; i++) {
                        bodyText.append(messages[i].getMessageBody());
                    }
                    body = bodyText.toString();
                }
                messageBody = body;
            }
        }

        // post sms message to ushahidi
        if (UshahidiService.smsUpdate) {
            if (Util.isConnected(SmsReceiverService.this)) {
                if (!this.postToUshahidi()) {
                    this.showNotification(messageBody, R.string.sms_failed);
                } else {
                    this.showNotification(messageBody, R.string.sms_sent);
                }
            }
        }
    }

    private boolean postToUshahidi() {
        UshahidiService.loadSettings(mContext);
        StringBuilder urlBuilder = new StringBuilder(UshahidiService.domain);

        urlBuilder.append("/api");
        params.put("task", "sms");
        params.put("username", UshahidiService.username);
        params.put("password", UshahidiService.password);
        params.put("message_from", fromAddress);
        params.put("message_description", messageBody);

        try {
            return UshahidiHttpClient.postSmsToUshahidi(urlBuilder.toString(), params);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static final SmsMessage[] getMessagesFromIntent(Intent intent) {
        if (messages == null) {
    public static void finishStartingService(Service service, int startId) {
        synchronized (mStartingServiceSync) {
            return null;
        }
        if (messages.length == 0) {
            return null;
        }

        byte[][] pduObjs = new byte[messages.length][];

        for (int i = 0; i < messages.length; i++) {
            pduObjs[i] = (byte[])messages[i];
        }
        byte[][] pdus = new byte[pduObjs.length][];
        int pduCount = pdus.length;
        SmsMessage[] msgs = new SmsMessage[pduCount];
        for (int i = 0; i < pduCount; i++) {
            pdus[i] = pduObjs[i];
            msgs[i] = SmsMessage.createFromPdu(pdus[i]);
        }
        return msgs;
    }

    /**
     * Start the service to process the current event notifications, acquiring
     * the wake lock before returning to ensure that the service will run.
     */
    public static void beginStartingService(Context context, Intent intent) {
        synchronized (mStartingServiceSync) {

            if (mStartingService == null) {
                PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
                mStartingService = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                        "Sms messages .SmsReceiverService");
                mStartingService.setReferenceCounted(false);
            }

            mStartingService.acquire();
            context.startService(intent);
        }
    }

    /**
     * Called back by the service when it has finished processing notifications,
     * releasing the wake lock if the service is now stopping.
     */

            if (mStartingService != null) {
                if (service.stopSelfResult(startId)) {
                    mStartingService.release();
                }
            }
        }
    }

    /**
     * Show a notification
     * 
     * @param String message to display
     * @param String notification title
     */
    private void showNotification(String message, int notification_title) {

        Intent baseIntent = new Intent(this, Settings.class);
>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
        baseIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Solution content
        params.put("task", "sms");
    private String fromAddress = "";

    private String messageBody = "";

    private static final Object mStartingServiceSync = new Object();

    private static final String TAG = "Ushahidi";

    private static PowerManager.WakeLock mStartingService;
        urlBuilder.append("/api");
     * Show a notification
                    body = sms.getDisplayMessageBody();
                } else {
    private HashMap params = new HashMap();

    private Context mContext;

    @Override
    public void onCreate() {

        HandlerThread thread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();
        mContext = getApplicationContext();
        UshahidiPref.loadSettings(mContext);
        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

    @Override
    public void onStart(Intent intent, int startId) {

        // int mResultCode = intent != null ? intent.getIntExtra("result", 0) :
        // 0;
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }

    @Override
    public void onDestroy() {

        mServiceLooper.quit();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {

            int serviceId = msg.arg1;
            Intent intent = (Intent)msg.obj;
            String action = intent.getAction();
            // String dataType = intent.getType();

            if (ACTION_SMS_RECEIVED.equals(action)) {
                handleSmsReceived(intent);
            }

            finishStartingService(SmsReceiverService.this, serviceId);
        }
    }

    /**
     * Handle receiving a SMS message
     */
    private void handleSmsReceived(Intent intent) {

        Bundle bundle = intent.getExtras();
        UshahidiPref.loadSettings(mContext);

        if (bundle != null) {
            SmsMessage[] messages = getMessagesFromIntent(intent);
            SmsMessage sms = messages[0];
            if (messages != null) {
                // extract message details phone number and the message body
                fromAddress = sms.getDisplayOriginatingAddress();

                String body;
                if (messages.length == 1 || sms.isReplace()) {
                    StringBuilder bodyText = new StringBuilder();
                    for (int i = 0; i < messages.length; i++) {
                        bodyText.append(messages[i].getMessageBody());
                    }
                    body = bodyText.toString();
                }
                messageBody = body;
            }
        }

        // post sms message to ushahidi
        if (UshahidiPref.smsUpdate) {
            if (Util.isConnected(SmsReceiverService.this)) {
                if (!this.postToUshahidi()) {
                    this.showNotification(messageBody, R.string.sms_failed);
                } else {
                    this.showNotification(messageBody, R.string.sms_sent);
                }
            }
        }
    }

    private boolean postToUshahidi() {
        UshahidiPref.loadSettings(mContext);
        StringBuilder urlBuilder = new StringBuilder(UshahidiPref.domain);

        params.put("username", UshahidiPref.username);
        params.put("password", UshahidiPref.password);
        params.put("message_from", fromAddress);
        params.put("message_description", messageBody);

        try {
            return UshahidiHttpClient.postSmsToUshahidi(urlBuilder.toString(), params);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static final SmsMessage[] getMessagesFromIntent(Intent intent) {
        Object[] messages = (Object[])intent.getSerializableExtra("pdus");
        if (messages == null) {
            return null;
        }
        if (messages.length == 0) {
            return null;
        }

        byte[][] pduObjs = new byte[messages.length][];

        for (int i = 0; i < messages.length; i++) {
            pduObjs[i] = (byte[])messages[i];
        }
        byte[][] pdus = new byte[pduObjs.length][];
        int pduCount = pdus.length;
        SmsMessage[] msgs = new SmsMessage[pduCount];
        for (int i = 0; i < pduCount; i++) {
            pdus[i] = pduObjs[i];
            msgs[i] = SmsMessage.createFromPdu(pdus[i]);
        }
        return msgs;
    }

    /**
     * Start the service to process the current event notifications, acquiring
     * the wake lock before returning to ensure that the service will run.
     */
    public static void beginStartingService(Context context, Intent intent) {
        synchronized (mStartingServiceSync) {

            if (mStartingService == null) {
                PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
                mStartingService = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                        "Sms messages .SmsReceiverService");
                mStartingService.setReferenceCounted(false);
            }

            mStartingService.acquire();
            context.startService(intent);
        }
    }

    /**
     * Called back by the service when it has finished processing notifications,
     * releasing the wake lock if the service is now stopping.
     */
    public static void finishStartingService(Service service, int startId) {
        synchronized (mStartingServiceSync) {

            if (mStartingService != null) {
                if (service.stopSelfResult(startId)) {
                    mStartingService.release();
                }
            }
        }
    }

    /**
     * 
     * @param String message to display
     * @param String notification title
     */
    private void showNotification(String message, int notification_title) {

        Intent baseIntent = new Intent(this, Settings.class);

        baseIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
File
SmsReceiverService.java
Developer's decision
Combination
Kind of conflict
Annotation
Attribute
Class declaration
Comment
Method declaration
Method invocation
Method signature
Variable
Chunk
Conflicting content
            // return;

        }

        setContentView(R.layout.main);
        mHandler = new Handler();
        bundle = new Bundle();
<<<<<<< HEAD
        //load settings
        if( UshahidiPref.domain.length() == 0 ) {
        	UshahidiPref.loadSettings(this);
        }
        
        //check if domain has been set
        if(UshahidiPref.domain.length() == 0 ) {
        	
        	//means this is a new install or the settings have been corrupted, prompt them!
			mHandler.post(mDisplayPrompt);
			//This return statement had to be commented out bcos it will not
			//allow the initialisation of the buttons below.
			//return;
 
=======
        // load settings
        if (UshahidiService.domain.length() == 0) {
            UshahidiService.loadSettings(this);
        }

        // check if domain has been set
        if (UshahidiService.domain.length() == 0) {

            // means this is a new install or the settings have been corrupted,
            // prompt them!
            mHandler.post(mDisplayPrompt);
            // This return statement had to be commented out bcos it will not
>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
            // allow the initialisation of the buttons below.
        listBtn = (Button)findViewById(R.id.incident_list);
Solution content
        setContentView(R.layout.main);
        mHandler = new Handler();
        bundle = new Bundle();

        // load settings
        if (UshahidiPref.domain.length() == 0) {
            UshahidiPref.loadSettings(this);
        }

        // check if domain has been set
        if (UshahidiPref.domain.length() == 0) {

            // means this is a new install or the settings have been corrupted,
            // prompt them!
            mHandler.post(mDisplayPrompt);
            // This return statement had to be commented out bcos it will not
            // allow the initialisation of the buttons below.
            // return;

        }

        listBtn = (Button)findViewById(R.id.incident_list);
File
Ushahidi.java
Developer's decision
Combination
Kind of conflict
Comment
If statement
Method invocation
Chunk
Conflicting content
    public static String username = "";

    public static String password = "";

import android.util.Log;

public class UshahidiService extends Service {
<<<<<<< HEAD
	
	
	private static final String TAG = "Ushahidi - New Updates"; 
=======

    public static boolean httpRunning = false;

    public static boolean AutoFetch = false;

    public static boolean smsUpdate = false;

    public static boolean vibrate = false;

    public static boolean ringtone = false;

    public static boolean flashLed = false;

    public static int countries = 0;

    public static int AutoUpdateDelay = 0;

    public static final int NOTIFICATION_ID = 1;

    public static final String PREFS_NAME = "UshahidiService";

    public static String incidentsResponse = "";

    public static String categoriesResponse = "";

    public static String savePath = "";

    public static String domain = "";

    public static String firstname = "";

    public static String lastname = "";

    public static String email = "";

    public static String totalReports = "";

    public static String fileName = "";

    public static String total_reports = "";

    private static final String TAG = "Ushahidi - New Updates";

>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
    public static final String NEW_USHAHIDI_REPORT_FOUND = "New_Ushahidi_Report_Found";

    public static Vector mNewIncidentsImages = new Vector();
Solution content
import android.util.Log;

public class UshahidiService extends Service {

    private static final String TAG = "Ushahidi - New Updates";

    public static boolean httpRunning = false;

    public static boolean AutoFetch = false;

    public static boolean smsUpdate = false;

    public static boolean vibrate = false;

    public static boolean ringtone = false;

    public static boolean flashLed = false;

    public static int countries = 0;

    public static int AutoUpdateDelay = 0;

    public static final int NOTIFICATION_ID = 1;

    public static final String PREFS_NAME = "UshahidiService";

    public static String incidentsResponse = "";

    public static String categoriesResponse = "";

    public static String savePath = "";

    public static String domain = "";

    public static String firstname = "";

    public static String lastname = "";

    public static String email = "";

    public static String totalReports = "";

    public static String fileName = "";

    public static String total_reports = "";

    public static String username = "";

    public static String password = "";

    public static final String NEW_USHAHIDI_REPORT_FOUND = "New_Ushahidi_Report_Found";

    public static Vector mNewIncidentsImages = new Vector();
File
UshahidiService.java
Developer's decision
Combination
Kind of conflict
Attribute
Chunk
Conflicting content
	 
	@Override
        }
    }

<<<<<<< HEAD
    
	private Runnable mUpdateTimeTask = new Runnable() {
		public void run() {
			
			UshahidiPref.saveSettings(getApplicationContext());
			
			Util.fetchReports(UshahidiService.this);
				
			showNotification(UshahidiPref.total_reports);
			mHandler.postAtTime(mUpdateTimeTask, SystemClock.uptimeMillis() + (
			        1000 * 60 * UshahidiPref.AutoUpdateDelay));	
				
		}
	};
	
	
	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}
	
	private final IBinder mBinder = new LocalBinder();
	
	@Override 
	public void onCreate() {
		super.onCreate();
		queue = new QueueThread("ushahidi");
		mHandler = new Handler();
		UshahidiPref.loadSettings(UshahidiService.this);
		if(UshahidiPref.AutoFetch){
			Log.i("Service ","Service is checked to start.");
			mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
			mHandler.postDelayed(mUpdateTimeTask, (1000 * 60 * UshahidiPref.AutoUpdateDelay));
		
		} else {
			Log.i("Service ","Service is unchecked.");
		}
		
		final Thread tr = new Thread() {
			@Override
			public void run() {
				while(true){
					queue.GetQueueItem().start();
				}
			}
		};
		tr.start();
	}
	
	public void onDestroy() {
		super.onDestroy();
		
		mNotificationManager.cancel(UshahidiPref.NOTIFICATION_ID);
		
		// Tell the user we stopped.
		stopService(new Intent(UshahidiService.this, UshahidiService.class));
		
	}
	
	public static void AddThreadToQueue(Thread tr){
		//	if( tr != null)
		//queue.AddQueueItem(tr);
	}
	
	private void showNotification(String tickerText) {
=======
    private Runnable mUpdateTimeTask = new Runnable() {
        public void run() {

            UshahidiService.saveSettings(getApplicationContext());

            Util.fetchReports(UshahidiService.this);

            showNotification(total_reports);
            mHandler.postAtTime(mUpdateTimeTask, SystemClock.uptimeMillis()
                    + (1000 * 60 * AutoUpdateDelay));

        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    private final IBinder mBinder = new LocalBinder();

    @Override
    public void onCreate() {
        super.onCreate();
        queue = new QueueThread("ushahidi");
        mHandler = new Handler();
        loadSettings(UshahidiService.this);
        if (AutoFetch) {
            Log.i("Service ", "Service is checked to start.");
            mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
            mHandler.postDelayed(mUpdateTimeTask, (1000 * 60 * AutoUpdateDelay));

        } else {
            Log.i("Service ", "Service is unchecked.");
        }

        final Thread tr = new Thread() {
            @Override
            public void run() {
                while (true) {
                    queue.GetQueueItem().start();
                }
            }
        };
        tr.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mNotificationManager.cancel(NOTIFICATION_ID);

        // Tell the user we stopped.
        stopService(new Intent(UshahidiService.this, UshahidiService.class));

    }

    public static void AddThreadToQueue(Thread tr) {
        // if( tr != null)
        // queue.AddQueueItem(tr);
    }

    private void showNotification(String tickerText) {
>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
        // This is what should be launched if the user selects our notification.
        Intent baseIntent = new Intent(this, IncidentsTab.class);
        baseIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Solution content
    @Override

    @Override
        }
    }

    private Runnable mUpdateTimeTask = new Runnable() {
        public void run() {

            UshahidiPref.saveSettings(getApplicationContext());

            Util.fetchReports(UshahidiService.this);

            showNotification(UshahidiPref.total_reports);
            mHandler.postAtTime(mUpdateTimeTask, SystemClock.uptimeMillis()
                    + (1000 * 60 * UshahidiPref.AutoUpdateDelay));

        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    private final IBinder mBinder = new LocalBinder();
    public void onCreate() {
        super.onCreate();
        queue = new QueueThread("ushahidi");
        mHandler = new Handler();
        UshahidiPref.loadSettings(UshahidiService.this);
        if (UshahidiPref.AutoFetch) {
            Log.i("Service ", "Service is checked to start.");
            mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
            mHandler.postDelayed(mUpdateTimeTask, (1000 * 60 * UshahidiPref.AutoUpdateDelay));

        } else {
            Log.i("Service ", "Service is unchecked.");
        }

        final Thread tr = new Thread() {
            @Override
            public void run() {
                while (true) {
                    queue.GetQueueItem().start();
                }
            }
        };
        tr.start();
    }

    public void onDestroy() {
        super.onDestroy();

        mNotificationManager.cancel(UshahidiPref.NOTIFICATION_ID);

        // Tell the user we stopped.
        stopService(new Intent(UshahidiService.this, UshahidiService.class));

    }

    public static void AddThreadToQueue(Thread tr) {
        // if( tr != null)
        // queue.AddQueueItem(tr);
    }

    private void showNotification(String tickerText) {

        // This is what should be launched if the user selects our notification.
        Intent baseIntent = new Intent(this, IncidentsTab.class);
        baseIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
File
UshahidiService.java
Developer's decision
Version 1
Kind of conflict
Annotation
Attribute
Method declaration
Method invocation
Method signature
Chunk
Conflicting content
	    }
	        itemcount--;
        newUshahidiReportNotification.flags = Notification.FLAG_AUTO_CANCEL;
        newUshahidiReportNotification.defaults = Notification.DEFAULT_ALL;
        newUshahidiReportNotification.setLatestEventInfo(this, TAG, tickerText, contentIntent);
<<<<<<< HEAD
        if( UshahidiPref.ringtone ){ 
        	//set the ringer
        	Uri ringURI = Uri.fromFile(new File("/system/media/audio/ringtones/ringer.mp3"));
        	newUshahidiReportNotification.sound = ringURI; 
        }
        
        if( UshahidiPref.vibrate ){
        	double vibrateLength = 100*Math.exp(0.53*20);
        	long[] vibrate = new long[] {100, 100, (long)vibrateLength };
        	newUshahidiReportNotification.vibrate = vibrate;
        	
        	if( UshahidiPref.flashLed ){
        		int color = Color.BLUE;    
	        // Send it back
	        return item;
        		newUshahidiReportNotification.ledARGB = color;
        	}
        	
        	newUshahidiReportNotification.ledOffMS = (int)vibrateLength;
        	newUshahidiReportNotification.ledOnMS = (int)vibrateLength;
        	newUshahidiReportNotification.flags = newUshahidiReportNotification.flags |  Notification.FLAG_SHOW_LIGHTS;
        }
        
        mNotificationManager.notify(UshahidiPref.NOTIFICATION_ID, newUshahidiReportNotification);
	}
	
	
	/**
	 * Clear stored data
	 */
	public boolean clearCache() {
		
		return getDb().clearData();
	}
	

	public class QueueThread {
	    protected Vector    queue;
	    protected int       itemcount;
	    protected String    queueName;
	    public QueueThread(String name) {
	        queue = new Vector();
	        queueName = name;
	        itemcount = 0;
	    }
	    // Get an item from the vector.  Wait if no items available
	    public synchronized Thread GetQueueItem() {
	        Thread   item = null;
	        // If no items available, drop into wait() call
	        if (itemcount == 0) {
	            try {
	                wait();
	            } catch (InterruptedException e) {
	            	//Somebody woke me up!
	            }
	        }
	        // Get first item from vector, remove it and decrement item count.
	        item = queue.firstElement();
	        queue.removeElement(item);
	    // Place an item onto vector. Signal threads that an item is available.
	    public synchronized void AddQueueItem(Thread o) {
	        itemcount++;
	        queue.addElement(o);
	        notify();
	    }
	    // Handy place to put a separate notify call - used during shutdown.
	    public synchronized void BumpQueue() {
	        notify();
	    }
	}
 
=======
        if (ringtone) {
            // set the ringer
            Uri ringURI = Uri.fromFile(new File("/system/media/audio/ringtones/ringer.mp3"));
            newUshahidiReportNotification.sound = ringURI;
        }

        if (vibrate) {
            double vibrateLength = 100 * Math.exp(0.53 * 20);
            long[] vibrate = new long[] {
                    100, 100, (long)vibrateLength
            };
            newUshahidiReportNotification.vibrate = vibrate;

            if (flashLed) {
                int color = Color.BLUE;
                newUshahidiReportNotification.ledARGB = color;
            }

            newUshahidiReportNotification.ledOffMS = (int)vibrateLength;
            newUshahidiReportNotification.ledOnMS = (int)vibrateLength;
            newUshahidiReportNotification.flags = newUshahidiReportNotification.flags
                    | Notification.FLAG_SHOW_LIGHTS;
        }

        mNotificationManager.notify(NOTIFICATION_ID, newUshahidiReportNotification);
    }

    /**
     * Clear stored data
     */
    public boolean clearCache() {

        return getDb().clearData();
    }

    public static void loadSettings(Context context) {
        final SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);

        final String path = context.getDir("", MODE_PRIVATE).toString();

        savePath = settings.getString("savePath", path);

        editor.commit();

    }

    public class QueueThread {
        domain = settings.getString("Domain", "");
        firstname = settings.getString("Firstname", "");
        lastname = settings.getString("Lastname", "");
        email = settings.getString("Email", "");
        countries = settings.getInt("Countries", 0);
        AutoUpdateDelay = settings.getInt("AutoUpdateDelay", 5);
        AutoFetch = settings.getBoolean("AutoFetch", false);
        totalReports = settings.getString("TotalReports", "");
        smsUpdate = settings.getBoolean("SmsUpdate", false);
        username = settings.getString("Username", "");
        password = settings.getString("Password", "");

        // make sure folder exists
        final File dir = new File(UshahidiService.savePath);
        dir.mkdirs();

    }

    public static void saveSettings(Context context) {

        final SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
        final SharedPreferences.Editor editor = settings.edit();

        editor.putString("Domain", domain.trim());
        editor.putString("Firstname", firstname);
        editor.putString("Lastname", lastname);

        if (Util.validateEmail(settings.getString("Email", ""))) {
            editor.putString("Email", email);
        }

        editor.putString("savePath", savePath);
        editor.putInt("AutoUpdateDelay", AutoUpdateDelay);
        editor.putBoolean("AutoFetch", AutoFetch);
        editor.putString("TotalReports", totalReports);
        editor.putBoolean("SmsUpdate", smsUpdate);
        editor.putString("Username", username);
        editor.putString("Password", password);
        protected Vector queue;

        protected int itemcount;

        protected String queueName;

        public QueueThread(String name) {
            queue = new Vector();
            queueName = name;
            itemcount = 0;
        }

        // Get an item from the vector. Wait if no items available
        public synchronized Thread GetQueueItem() {
            Thread item = null;
            // If no items available, drop into wait() call
            if (itemcount == 0) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    // Somebody woke me up!
                }
            }
            // Get first item from vector, remove it and decrement item count.
            item = queue.firstElement();
            queue.removeElement(item);
            itemcount--;
            // Send it back
            return item;
        }

        // Place an item onto vector. Signal threads that an item is available.
        public synchronized void AddQueueItem(Thread o) {
            itemcount++;
            queue.addElement(o);
            notify();
        }

        // Handy place to put a separate notify call - used during shutdown.
        public synchronized void BumpQueue() {
            notify();
        }
    }

>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
}
Solution content
        // Get an item from the vector. Wait if no items available
        public synchronized Thread GetQueueItem() {
            Thread item = null;
        newUshahidiReportNotification.flags = Notification.FLAG_AUTO_CANCEL;
        newUshahidiReportNotification.defaults = Notification.DEFAULT_ALL;
        newUshahidiReportNotification.setLatestEventInfo(this, TAG, tickerText, contentIntent);

        if (UshahidiPref.ringtone) {
            // set the ringer
            Uri ringURI = Uri.fromFile(new File("/system/media/audio/ringtones/ringer.mp3"));
            newUshahidiReportNotification.sound = ringURI;
        }

        if (UshahidiPref.vibrate) {
            double vibrateLength = 100 * Math.exp(0.53 * 20);
            long[] vibrate = new long[] {
                    100, 100, (long)vibrateLength
            };
            newUshahidiReportNotification.vibrate = vibrate;

            if (UshahidiPref.flashLed) {
                int color = Color.BLUE;
                newUshahidiReportNotification.ledARGB = color;
            }

            newUshahidiReportNotification.ledOffMS = (int)vibrateLength;
            newUshahidiReportNotification.ledOnMS = (int)vibrateLength;
            newUshahidiReportNotification.flags = newUshahidiReportNotification.flags
                    | Notification.FLAG_SHOW_LIGHTS;
        }

        mNotificationManager.notify(UshahidiPref.NOTIFICATION_ID, newUshahidiReportNotification);
    }

    /**
     * Clear stored data
     */
    public boolean clearCache() {

        return getDb().clearData();
    }

    public class QueueThread {
        protected Vector queue;

        protected int itemcount;

        protected String queueName;

        public QueueThread(String name) {
            queue = new Vector();
            queueName = name;
            itemcount = 0;
        }

            // If no items available, drop into wait() call
            if (itemcount == 0) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    // Somebody woke me up!
                }
            }
            // Get first item from vector, remove it and decrement item count.
            item = queue.firstElement();
            queue.removeElement(item);
            itemcount--;
            // Send it back
            return item;
        }

        // Place an item onto vector. Signal threads that an item is available.
        public synchronized void AddQueueItem(Thread o) {
            itemcount++;
            queue.addElement(o);
            notify();
        }

        // Handy place to put a separate notify call - used during shutdown.
        public synchronized void BumpQueue() {
            notify();
        }
    }

}
File
UshahidiService.java
Developer's decision
Version 1
Kind of conflict
Class declaration
Comment
If statement
Method declaration
Method invocation
Chunk
Conflicting content
	}
	
	/**
				
			} else {
	 * @param second
				return "";
			}
	 * @return
	 */
			
    /**
	 * @param value
	 * @return
	 */
		}
		return formatted;

public class Util {

<<<<<<< HEAD
public class Util{

	private static NetworkInfo networkInfo;
	private static List mNewIncidents;
	private static List mNewCategories;
	private static JSONObject jsonObject;
	private static Pattern pattern;
	 * Limit a string to defined length
	 * 
	public static int toInt( String value){
	 * @param int limit - the total length 
	public static String joinString(String first, String second ) {
		return first.concat(second);
	}
	
	/**
	 * Converts a string integer 
	 * @param string limited - the limited string
	 */
	private static Matcher matcher;

		//NetworkInfo info
		
	private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@" +
		if(networkInfo == null || !networkInfo.isConnected()){  
	        return false;  
	    } 
	    return true; 
			"[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
	
	/**
	 * joins two strings together
	 * @param first
	     
		return Integer.parseInt(value);
	}
	
	/**
	 * Capitalize any string given to it.
	 * @param text
	 * @return capitalized string
	 */
	public static String capitalizeString( String text ) {
		return text.substring(0,1).toUpperCase() + text.substring(1);
	}
	
	/**
	 * Create csv
	 * @param Vector text
	 * 
	 * @return csv
	 */
	public static String implode( Vector text ) {
		String implode = "";
		int i = 0;
		for( String value : text ) {
			implode += i == text.size() -1 ? value : value+",";
			i++;
		}
		
		return implode;
	}
	
	/**
	 * Is there internet connection
	 */
	public static boolean isConnected(Context context )  {
		  
		ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

		networkInfo = connectivity.getActiveNetworkInfo();
	public static String limitString( String value, int length ) {
		StringBuilder buf = new StringBuilder(value);
		if( buf.length() > length ) {
			buf.setLength(length);
			buf.append(" ...");
		}
		return buf.toString();
	}
	
	/**
	 * Fetch reports details from the internet
	 * 
	 * @param context - the activity calling this method.
	 */
	public static void fetchReports( final Context context ) {
		try {
			  if( Util.isConnected(context)) {

				  if(Categories.getAllCategoriesFromWeb() ) {
					  mNewCategories = HandleXml.processCategoriesXml(UshahidiPref.categoriesResponse);
				  }

				  if(Incidents.getAllIncidentsFromWeb()){
					  mNewIncidents =  HandleXml.processIncidentsXml( UshahidiPref.incidentsResponse ); 
				  }
				  
				  UshahidiPref.total_reports = mNewCategories.size()+" Categories -- " +  mNewIncidents.size()+ " Reports";
				  
				  UshahidiApplication.mDb.addCategories(mNewCategories, false);
				  UshahidiApplication.mDb.addIncidents(mNewIncidents, false);
				  
			  } else {
				  return;
			  }
		  	} catch (IOException e) {
				//means there was a problem getting it
		  	} 
	}
	
	/**
	 * Format date into more readable format.
	 * 
	 * @param  date - the date to be formatted.
	 * @return String
	 */
	public static String formatDate( String dateFormat, String date, String toFormat ) {
	
		String formatted = "";
		
		DateFormat formatter = new SimpleDateFormat(dateFormat);
		try {
			Date dateStr = formatter.parse(date);
			formatted = formatter.format(dateStr);
			Date formatDate = formatter.parse(formatted);
			formatter = new SimpleDateFormat(toFormat);
			formatted = formatter.format(formatDate);
		
		} catch (ParseException e) {
			
			e.printStackTrace();
	}
	
	
	
	/**
	 * Extract Ushahidi payload JSON data
	 * 
	 * @apram json_data - the json data to be formatted.
	 * @return String 
	 */
	public static boolean extractPayloadJSON( String json_data ) {
	
		try {
			jsonObject = new JSONObject(json_data);
			return jsonObject.getJSONObject("payload").getBoolean("success");
		
		} catch (JSONException e) {
			
			e.printStackTrace();
		}
		
		return false;
	}
	
	/**
	 * Extract Google geocode JSON data
	 * 
	 * @apram json_data - the json data to be formatted.
	 * @return String 
	 */
	public static String getFromLocation( double latitude, double longitude, Context context ) {
		String json_data = "";
		int status =  0;
		JSONArray jsonArray;
		try {
			if( Util.isConnected(context)) {
				json_data = UshahidiGeocoder.reverseGeocode(latitude, longitude);
			} else {
				return "";
			}
			
			jsonObject = new JSONObject(json_data);
			
			status = jsonObject.getJSONObject("Status").getInt("code");
			
			if( status == 200 ) {
				jsonArray = jsonObject.getJSONArray("Placemark");
			
				return jsonArray.getJSONObject(0).getJSONObject("AddressDetails").getJSONObject("Country").
					getJSONObject("AdministrativeArea").
					getJSONObject("Locality").getString("LocalityName");
		} catch (JSONException e) {
			return "";
			//e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
		
		return "";
	}
	
	/**
	 * process reports
	 * 0 - successful
	 * 1 - failed fetching categories
	 * 2 - failed fetching reports
	 * 3 - non ushahidi instance
	 * 4 - No internet connection
	 * 
	 * @return int - status
	 */
	public static int processReports( Context context ) {
		
		try {
			if( Util.isConnected(context)) {
				 
				if(Categories.getAllCategoriesFromWeb()) {
						
					mNewCategories = HandleXml.processCategoriesXml(UshahidiPref.categoriesResponse); 
				} else {
					return 1;
				}
				
				if( Incidents.getAllIncidentsFromWeb() ){
					mNewIncidents =  HandleXml.processIncidentsXml( UshahidiPref.incidentsResponse );
					
				} else {
					return 1;
				}
				
				if(mNewCategories != null && mNewIncidents != null ) {
					 UshahidiApplication.mDb.addCategories(mNewCategories, false);
					 UshahidiApplication.mDb.addIncidents(mNewIncidents, false);
					 return 0;
				 
				 } else {
					 return 1;
				 }
				  

				} else {
					return 4;
				}
		} catch (IOException e) {
			//means there was a problem getting it
		}
		return 0;
	}
	
	/**
	 * Show toast
	 * 
	 * @param Context - the application's context
	 * @param Int - string resource id
	 * 
	 * @return void
	 */
	public static void showToast(Context context, int i ) {
		int duration = Toast.LENGTH_SHORT;
		Toast.makeText(context, i, duration).show();
	}
	
	/**
	 * Validates an email address
	 * Credits: http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/
	 * 
	 * @param String - email address to be validated
	 * 
	 * @return boolean
	 */
	public static boolean validateEmail( String emailAddress) {
		if( !emailAddress.equals("") ) {
			pattern = Pattern.compile(EMAIL_PATTERN);
			matcher = pattern.matcher(emailAddress);
			return matcher.matches();
		}
		return true;
	}
	
	/**
	 * Validate an Ushahidi instance
	 * 
	 * @param String - URL to be validated.
	 * 
	 * @return boolean
	 */
	public static boolean validateUshahidiInstance( String ushahidiUrl ) {
		//make an http get request to a dummy api call
		//TODO improve on how to do this
		boolean status = false;
		try {
		    URL url = new URL(ushahidiUrl);
		    URLConnection conn = url.openConnection();
		    conn.connect();
		    status = true;
		} catch (MalformedURLException e) {
		    status = false;
		} catch (IOException e) {
		    status = true;
		}

		return status;
	}
=======
    private static NetworkInfo networkInfo;

    private static List mNewIncidents;

    private static List mNewCategories;

    private static JSONObject jsonObject;

    private static Pattern pattern;

    private static Matcher matcher;

    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    /**
     * joins two strings together
     * 
     * @param first
     * @param second
     * @return
     */
    public static String joinString(String first, String second) {
        return first.concat(second);
    }

    /**
     * Converts a string integer
     * 
     * @param value
     * @return
     */
    public static int toInt(String value) {
        return Integer.parseInt(value);
    }

    /**
     * Capitalize any string given to it.
     * 
     * @param text
     * @return capitalized string
     */
    public static String capitalizeString(String text) {
        return text.substring(0, 1).toUpperCase() + text.substring(1);
    }

    /**
     * Create csv
     * 
     * @param Vector text
     * @return csv
     */
    public static String implode(Vector text) {
        String implode = "";
        int i = 0;
        for (String value : text) {
            implode += i == text.size() - 1 ? value : value + ",";
            i++;
        }

        return implode;
    }

    /**
     * Is there internet connection
     */
    public static boolean isConnected(Context context) {

        ConnectivityManager connectivity = (ConnectivityManager)context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        networkInfo = connectivity.getActiveNetworkInfo();
        // NetworkInfo info

        if (networkInfo == null || !networkInfo.isConnected()) {
            return false;
        }
        return true;

    }

    /**
     * Limit a string to defined length
     * 
     * @param int limit - the total length
     * @param string limited - the limited string
     */
    public static String limitString(String value, int length) {
        StringBuilder buf = new StringBuilder(value);
        if (buf.length() > length) {
            buf.setLength(length);
            buf.append(" ...");
        }
        return buf.toString();
    }

    /**
     * Fetch reports details from the internet
     * 
     * @param context - the activity calling this method.
     */
    public static void fetchReports(final Context context) {
        try {
            if (Util.isConnected(context)) {

                if (Categories.getAllCategoriesFromWeb()) {
                    mNewCategories = HandleXml
                            .processCategoriesXml(UshahidiService.categoriesResponse);
                }

                if (Incidents.getAllIncidentsFromWeb()) {
                    mNewIncidents = HandleXml
                            .processIncidentsXml(UshahidiService.incidentsResponse);
                }

                UshahidiService.total_reports = mNewCategories.size() + " Categories -- "
                        + mNewIncidents.size() + " Reports";

                UshahidiApplication.mDb.addCategories(mNewCategories, false);
                UshahidiApplication.mDb.addIncidents(mNewIncidents, false);

            } else {
                return;
            }
        } catch (IOException e) {
            // means there was a problem getting it
        }
    }

    /**
     * Format date into more readable format.
     * 
     * @param date - the date to be formatted.
     * @return String
     */
    public static String formatDate(String dateFormat, String date, String toFormat) {

        String formatted = "";

        DateFormat formatter = new SimpleDateFormat(dateFormat);
        try {
            Date dateStr = formatter.parse(date);
            formatted = formatter.format(dateStr);
            Date formatDate = formatter.parse(formatted);
            formatter = new SimpleDateFormat(toFormat);
            formatted = formatter.format(formatDate);

        } catch (ParseException e) {

            e.printStackTrace();
        }
        return formatted;
    }

    /**
     * Extract Ushahidi payload JSON data
     * 
     * @apram json_data - the json data to be formatted.
     * @return String
     */
    public static boolean extractPayloadJSON(String json_data) {

        try {
            jsonObject = new JSONObject(json_data);
            return jsonObject.getJSONObject("payload").getBoolean("success");

        } catch (JSONException e) {

            e.printStackTrace();
        }

        return false;
    }

    /**
     * Extract Google geocode JSON data
     * 
     * @apram json_data - the json data to be formatted.
     * @return String
     */
    public static String getFromLocation(double latitude, double longitude, Context context) {
        String json_data = "";
        int status = 0;
        JSONArray jsonArray;
        try {
            if (Util.isConnected(context)) {
                json_data = UshahidiGeocoder.reverseGeocode(latitude, longitude);
            } else {
                return "";
            }

            jsonObject = new JSONObject(json_data);

            status = jsonObject.getJSONObject("Status").getInt("code");

            if (status == 200) {
                jsonArray = jsonObject.getJSONArray("Placemark");

                return jsonArray.getJSONObject(0).getJSONObject("AddressDetails")
                        .getJSONObject("Country").getJSONObject("AdministrativeArea")
                        .getJSONObject("Locality").getString("LocalityName");

            } else {
                return "";
            }

        } catch (JSONException e) {
            return "";
            // e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
        }

        return "";
    }

     * process reports 0 - successful 1 - failed fetching categories 2 - failed
     * fetching reports 3 - non ushahidi instance 4 - No internet connection
     * 
     * @return int - status
     */
    public static int processReports(Context context) {

        try {
            if (Util.isConnected(context)) {

                if (Categories.getAllCategoriesFromWeb()) {

                    mNewCategories = HandleXml
                            .processCategoriesXml(UshahidiService.categoriesResponse);
                } else {
                    return 1;
                }

                if (Incidents.getAllIncidentsFromWeb()) {
                    mNewIncidents = HandleXml
                            .processIncidentsXml(UshahidiService.incidentsResponse);

                } else {
                    return 1;
                }

                if (mNewCategories != null && mNewIncidents != null) {
                    UshahidiApplication.mDb.addCategories(mNewCategories, false);
                    UshahidiApplication.mDb.addIncidents(mNewIncidents, false);
                    return 0;

                } else {
                    return 1;
                }

            } else {
                return 4;
            }
        } catch (IOException e) {
            // means there was a problem getting it
        }
        return 0;
    }

    /**
     * Show toast
     * 
     * @param Context - the application's context
     * @param Int - string resource id
     * @return void
     */
    public static void showToast(Context context, int i) {
        int duration = Toast.LENGTH_SHORT;
        Toast.makeText(context, i, duration).show();
    }

    /**
     * Validates an email address Credits:
     * http://www.mkyong.com/regular-expressions
     * /how-to-validate-email-address-with-regular-expression/
     * 
     * @param String - email address to be validated
     * @return boolean
     */
    public static boolean validateEmail(String emailAddress) {
        if (!emailAddress.equals("")) {
            pattern = Pattern.compile(EMAIL_PATTERN);
            matcher = pattern.matcher(emailAddress);
            return matcher.matches();
        }
        return true;
    }

    /**
     * Validate an Ushahidi instance
     * 
     * @param String - URL to be validated.
     * @return boolean
     */
    public static boolean validateUshahidiInstance(String ushahidiUrl) {
        // make an http get request to a dummy api call
        // TODO improve on how to do this
        boolean status = false;
        try {
            URL url = new URL(ushahidiUrl);
            URLConnection conn = url.openConnection();
            conn.connect();
            status = true;
        } catch (MalformedURLException e) {
            status = false;
        } catch (IOException e) {
            status = true;
        }

        return status;
    }
>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146

}
Solution content
    }

    /**
        if (networkInfo == null || !networkInfo.isConnected()) {
            return false;
        }
        return true;
                if (Categories.getAllCategoriesFromWeb()) {

public class Util {

    private static NetworkInfo networkInfo;

    private static List mNewIncidents;

    private static List mNewCategories;

    private static JSONObject jsonObject;

    private static Pattern pattern;

    private static Matcher matcher;

    private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    /**
     * joins two strings together
     * 
     * @param first
     * @param second
     * @return
     */
    public static String joinString(String first, String second) {
        return first.concat(second);
    }

    /**
     * Converts a string integer
     * 
     * @param value
     * @return
     */
    public static int toInt(String value) {
        return Integer.parseInt(value);
    }

    /**
     * Capitalize any string given to it.
     * 
     * @param text
     * @return capitalized string
     */
    public static String capitalizeString(String text) {
        return text.substring(0, 1).toUpperCase() + text.substring(1);
    }

    /**
     * Create csv
     * 
     * @param Vector text
     * @return csv
     */
    public static String implode(Vector text) {
        String implode = "";
        int i = 0;
        for (String value : text) {
            implode += i == text.size() - 1 ? value : value + ",";
            i++;
        }

        return implode;
    }

    /**
     * Is there internet connection
     */
    public static boolean isConnected(Context context) {

        ConnectivityManager connectivity = (ConnectivityManager)context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        networkInfo = connectivity.getActiveNetworkInfo();
        // NetworkInfo info


    }

    /**
     * Limit a string to defined length
     * 
     * @param int limit - the total length
     * @param string limited - the limited string
     */
    public static String limitString(String value, int length) {
        StringBuilder buf = new StringBuilder(value);
        if (buf.length() > length) {
            buf.setLength(length);
            buf.append(" ...");
        }
        return buf.toString();
    }

    /**
     * Fetch reports details from the internet
     * 
     * @param context - the activity calling this method.
     */
    public static void fetchReports(final Context context) {
        try {
            if (Util.isConnected(context)) {

            if (Util.isConnected(context)) {
                    mNewCategories = HandleXml
                            .processCategoriesXml(UshahidiPref.categoriesResponse);
                }
                json_data = UshahidiGeocoder.reverseGeocode(latitude, longitude);
            } else {
        int status = 0;
        JSONArray jsonArray;
        try {
                if (Incidents.getAllIncidentsFromWeb()) {
                    mNewIncidents = HandleXml.processIncidentsXml(UshahidiPref.incidentsResponse);
                }

                UshahidiPref.total_reports = mNewCategories.size() + " Categories -- "
                        + mNewIncidents.size() + " Reports";

                UshahidiApplication.mDb.addCategories(mNewCategories, false);
                UshahidiApplication.mDb.addIncidents(mNewIncidents, false);

            } else {
                return;
            }
        } catch (IOException e) {
            // means there was a problem getting it
        }
    }

    /**
     * Format date into more readable format.
     * 
     * @param date - the date to be formatted.
     * @return String
     */
    public static String formatDate(String dateFormat, String date, String toFormat) {

        String formatted = "";

        DateFormat formatter = new SimpleDateFormat(dateFormat);
        try {
            Date dateStr = formatter.parse(date);
            formatted = formatter.format(dateStr);
            Date formatDate = formatter.parse(formatted);
            formatter = new SimpleDateFormat(toFormat);
            formatted = formatter.format(formatDate);

        } catch (ParseException e) {

            e.printStackTrace();
        }
        return formatted;
    }

    /**
     * Extract Ushahidi payload JSON data
     * 
     * @apram json_data - the json data to be formatted.
     * @return String
     */
    public static boolean extractPayloadJSON(String json_data) {

        try {
            jsonObject = new JSONObject(json_data);
            return jsonObject.getJSONObject("payload").getBoolean("success");

        } catch (JSONException e) {

            e.printStackTrace();
        }

        return false;
    }

    /**
     * Extract Google geocode JSON data
     * 
     * @apram json_data - the json data to be formatted.
     * @return String
     */
    public static String getFromLocation(double latitude, double longitude, Context context) {
        String json_data = "";
                return "";
            }

            jsonObject = new JSONObject(json_data);

            status = jsonObject.getJSONObject("Status").getInt("code");

            if (status == 200) {
                jsonArray = jsonObject.getJSONArray("Placemark");

                return jsonArray.getJSONObject(0).getJSONObject("AddressDetails")
                        .getJSONObject("Country").getJSONObject("AdministrativeArea")
                        .getJSONObject("Locality").getString("LocalityName");

            } else {
                return "";
            }

        } catch (JSONException e) {
            return "";
            // e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
        }

        return "";
     * process reports 0 - successful 1 - failed fetching categories 2 - failed
     * fetching reports 3 - non ushahidi instance 4 - No internet connection
     * 
     * @return int - status
     */
    public static int processReports(Context context) {

        try {
            if (Util.isConnected(context)) {

                if (Categories.getAllCategoriesFromWeb()) {

                    mNewCategories = HandleXml
                            .processCategoriesXml(UshahidiPref.categoriesResponse);
                } else {
                    return 1;
                }

                if (Incidents.getAllIncidentsFromWeb()) {
                    mNewIncidents = HandleXml.processIncidentsXml(UshahidiPref.incidentsResponse);

                } else {
                    return 1;
                }

                if (mNewCategories != null && mNewIncidents != null) {
                    UshahidiApplication.mDb.addCategories(mNewCategories, false);
                    UshahidiApplication.mDb.addIncidents(mNewIncidents, false);
                    return 0;

                } else {
                    return 1;
                }

            } else {
                return 4;
            }
        } catch (IOException e) {
            // means there was a problem getting it
        }
        return 0;
    }

    /**
     * Show toast
     * 
     * @param Context - the application's context
     * @param Int - string resource id
     * @return void
     */
    public static void showToast(Context context, int i) {
        int duration = Toast.LENGTH_SHORT;
        Toast.makeText(context, i, duration).show();
    }

    /**
     * Validates an email address Credits:
     * http://www.mkyong.com/regular-expressions
     * /how-to-validate-email-address-with-regular-expression/
     * 
     * @param String - email address to be validated
     * @return boolean
     */
    public static boolean validateEmail(String emailAddress) {
        if (!emailAddress.equals("")) {
            pattern = Pattern.compile(EMAIL_PATTERN);
            matcher = pattern.matcher(emailAddress);
            return matcher.matches();
        }
        return true;
    }

    /**
     * Validate an Ushahidi instance
     * 
     * @param String - URL to be validated.
     * @return boolean
     */
    public static boolean validateUshahidiInstance(String ushahidiUrl) {
        // make an http get request to a dummy api call
        // TODO improve on how to do this
        boolean status = false;
        try {
            URL url = new URL(ushahidiUrl);
            URLConnection conn = url.openConnection();
            conn.connect();
            status = true;
        } catch (MalformedURLException e) {
            status = false;
        } catch (IOException e) {
            status = true;
        }

        return status;
    }

}
File
Util.java
Developer's decision
Manual
Kind of conflict
Attribute
Class signature
Comment
Method declaration
Chunk
Conflicting content
    private Button uploadPhotoButton;

    private EditText checkinMessageText;
<<<<<<< HEAD
    private ImageView mCheckImgPrev;
    private TextView mSelectedPhotoText;
    
=======

    private EditText mSelectedPhoto;

>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
    // Photo functionality
    private String mFilename = "";
Solution content
    private String mFilename = "";

    private Button uploadPhotoButton;

    private EditText checkinMessageText;

    private ImageView mCheckImgPrev;

    private TextView mSelectedPhotoText;

    // Photo functionality
File
CheckinActivity.java
Developer's decision
Version 1
Kind of conflict
Attribute
Chunk
Conflicting content
        super.onCreate(savedInstanceState);
        setContentView(R.layout.checkin);

<<<<<<< HEAD
        checkinButton = (Button) findViewById(R.id.perform_checkin_button);
        uploadPhotoButton = (Button) findViewById(R.id.upload_checkin_photo_button);
        checkinMessageText = (EditText) findViewById(R.id.checkin_message_text);
        mCheckImgPrev = (ImageView) findViewById(R.id.checkin_img_prev);
        mSelectedPhotoText = (TextView) findViewById(R.id.checkin_selected_photo_label);
        mSelectedPhotoText.setVisibility(View.GONE);
=======
        checkinButton = (Button)findViewById(R.id.perform_checkin_button);
        uploadPhotoButton = (Button)findViewById(R.id.upload_checkin_photo_button);
        checkinMessageText = (EditText)findViewById(R.id.checkin_message_text);
        mSelectedPhoto = (EditText)findViewById(R.id.checkin_selected_photo_text);

>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
        // Perform the checkin
        checkinButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
Solution content
        super.onCreate(savedInstanceState);
        setContentView(R.layout.checkin);

        checkinButton = (Button)findViewById(R.id.perform_checkin_button);
        uploadPhotoButton = (Button)findViewById(R.id.upload_checkin_photo_button);
        checkinMessageText = (EditText)findViewById(R.id.checkin_message_text);
        mCheckImgPrev = (ImageView)findViewById(R.id.checkin_img_prev);
        mSelectedPhotoText = (TextView)findViewById(R.id.checkin_selected_photo_label);
        mSelectedPhotoText.setVisibility(View.GONE);

        // Perform the checkin
        checkinButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
File
CheckinActivity.java
Developer's decision
Version 1
Kind of conflict
Attribute
Cast expression
Method invocation
Chunk
Conflicting content
    }

    @Override
<<<<<<< HEAD
=======
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        populateMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        populateMenu(menu);

        return (super.onCreateOptionsMenu(menu));
    }

    @Override
>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // The preferences returned if the request code is what we had given
Solution content
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // The preferences returned if the request code is what we had given
File
CheckinActivity.java
Developer's decision
Version 1
Kind of conflict
Annotation
Method declaration
Chunk
Conflicting content
                if (mBundle != null && !mBundle.isEmpty()) {
                    selectedPhoto = mBundle.getString("name");
<<<<<<< HEAD
					NetworkServices.fileName = mBundle.getString("name");
					mSelectedPhotoText.setVisibility(View.VISIBLE);
					mCheckImgPrev.setImageDrawable(ImageManager.getImages(NetworkServices.fileName));
				}
				break;

            case REQUEST_CODE_IMAGE:
				if(resultCode != RESULT_OK){
					return;
				}

				Uri uri = data.getData();
				Bitmap b = null;

				try {
					b = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
				} catch (FileNotFoundException e) {
					break;
				} catch (IOException e) {
					break;
				}

				ByteArrayOutputStream byteArrayos = new ByteArrayOutputStream();

				try {
					b.compress(Bitmap.CompressFormat.JPEG, 75, byteArrayos);
					byteArrayos.flush();
				} catch (OutOfMemoryError e){
					break;
				} catch (IOException e) {
					break;
				}

				mFilename = "android_pic_upload" + randomString() + ".jpg";
				ImageManager.writeImage(byteArrayos.toByteArray(), mFilename);
				UshahidiPref.fileName = mFilename;
                selectedPhoto = mFilename;
				
				break;
		}
=======
                    NetworkServices.fileName = mBundle.getString("name");
                    mSelectedPhoto.setText(NetworkServices.fileName);
                }
                break;

            case REQUEST_CODE_IMAGE:
                if (resultCode != RESULT_OK) {
                    return;
                }

                Uri uri = data.getData();
                Bitmap b = null;

                try {
                    b = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                } catch (FileNotFoundException e) {
                    break;
                } catch (IOException e) {
                    break;
                }

                ByteArrayOutputStream byteArrayos = new ByteArrayOutputStream();

                try {
                    b.compress(Bitmap.CompressFormat.JPEG, 75, byteArrayos);
                    byteArrayos.flush();
                } catch (OutOfMemoryError e) {
                    break;
                } catch (IOException e) {
                    break;
                }

                mFilename = "android_pic_upload" + randomString() + ".jpg";
                ImageManager.writeImage(byteArrayos.toByteArray(), mFilename);
                UshahidiService.fileName = mFilename;
                selectedPhoto = mFilename;
                mSelectedPhoto.setText(UshahidiService.fileName);
                break;
        }
>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
    }

    private static Random random = new Random();
Solution content
                if (mBundle != null && !mBundle.isEmpty()) {
                    selectedPhoto = mBundle.getString("name");
                    NetworkServices.fileName = mBundle.getString("name");
                    mSelectedPhotoText.setVisibility(View.VISIBLE);
                    mCheckImgPrev
                            .setImageDrawable(ImageManager.getImages(NetworkServices.fileName));
                }
                break;

            case REQUEST_CODE_IMAGE:
                if (resultCode != RESULT_OK) {
                    return;
                }

                Uri uri = data.getData();
                Bitmap b = null;

                try {
                    b = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
                } catch (FileNotFoundException e) {
                    break;
                } catch (IOException e) {
                    break;
                }

                ByteArrayOutputStream byteArrayos = new ByteArrayOutputStream();

                try {
                    b.compress(Bitmap.CompressFormat.JPEG, 75, byteArrayos);
                    byteArrayos.flush();
                } catch (OutOfMemoryError e) {
                    break;
                } catch (IOException e) {
                    break;
                }

                mFilename = "android_pic_upload" + randomString() + ".jpg";
                ImageManager.writeImage(byteArrayos.toByteArray(), mFilename);
                UshahidiPref.fileName = mFilename;
                selectedPhoto = mFilename;

                break;
        }
    }

    private static Random random = new Random();
File
CheckinActivity.java
Developer's decision
Version 1
Kind of conflict
Attribute
Break statement
Case statement
If statement
Method invocation
Try statement
Variable
Chunk
Conflicting content
        // Post data online and close the progress dialog

        // Initialize the settings
<<<<<<< HEAD
        UshahidiPref.loadSettings(CheckinActivity.this);
        
        String ushahidiDomain = UshahidiPref.domain;
        String firstname = UshahidiPref.firstname;
        String lastname = UshahidiPref.lastname;
        String email = UshahidiPref.email;
        
        NetworkServices.postToOnline(Util.IMEI(CheckinActivity.this), ushahidiDomain, checkinDetails, 
        		LocationServices.location, selectedPhoto,firstname,lastname,email);
=======
        UshahidiService.loadSettings(CheckinActivity.this);

        String ushahidiDomain = UshahidiService.domain;
        String firstname = UshahidiService.firstname;
        String lastname = UshahidiService.lastname;
        String email = UshahidiService.email;
>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146

        NetworkServices.postToOnline(Util.IMEI(CheckinActivity.this), ushahidiDomain,
                checkinDetails, LocationServices.location, selectedPhoto, firstname, lastname,
Solution content
        // Post data online and close the progress dialog

        // Initialize the settings
        UshahidiPref.loadSettings(CheckinActivity.this);

        String ushahidiDomain = UshahidiPref.domain;
        String firstname = UshahidiPref.firstname;
        String lastname = UshahidiPref.lastname;
        String email = UshahidiPref.email;

        NetworkServices.postToOnline(Util.IMEI(CheckinActivity.this), ushahidiDomain,
                checkinDetails, LocationServices.location, selectedPhoto, firstname, lastname,
                email);

        NetworkServices.postToOnline(Util.IMEI(CheckinActivity.this), ushahidiDomain,
                checkinDetails, LocationServices.location, selectedPhoto, firstname, lastname,
File
CheckinActivity.java
Developer's decision
Version 1
Kind of conflict
Method invocation
Variable
Chunk
Conflicting content
        LocationServices.getLocation(this);
    }

<<<<<<< HEAD
}
=======
    private void populateMenu(Menu menu) {
        MenuItem i;
        // Create the menu here
    }
}
>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
Solution content
        LocationServices.getLocation(this);
    }

}
File
CheckinActivity.java
Developer's decision
Version 1
Kind of conflict
Method declaration
Chunk
Conflicting content
    CheckinItemizedOverlay itemizedOverlay;

    protected void onCreate(Bundle savedInstance) {
<<<<<<< HEAD
=======
        boolean firstPoint = true;
        GeoPoint centerGeoPoint = new GeoPoint(0, 0);

>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
        super.onCreate(savedInstance);
        
        UshahidiPref.loadSettings(CheckinMap.this);
Solution content
    CheckinItemizedOverlay itemizedOverlay;

    protected void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);

        UshahidiPref.loadSettings(CheckinMap.this);
File
CheckinMap.java
Developer's decision
Version 1
Kind of conflict
Method invocation
Variable
Chunk
Conflicting content
                req.setParameter("photo", new File(UshahidiPref.savePath + params.get("filename")));
=======
            req.setParameter("lastname", params.get("lastname"));
            req.setParameter("email", params.get("email"));

<<<<<<< HEAD
             Log.i("HTTP Client:", "filename:" + UshahidiPref.savePath + params.get("filename"));

             if( !TextUtils.isEmpty(params.get("filename")) || !(params.get("filename").equals("")))
            Log.i("HTTP Client:", "filename:" + UshahidiService.savePath + params.get("filename"));

            if (!TextUtils.isEmpty(params.get("filename")) || !(params.get("filename").equals("")))
                req.setParameter("photo",
                        new File(UshahidiService.savePath + params.get("filename")));
>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146

            InputStream serverInput = req.post();
Solution content
            req.setParameter("lastname", params.get("lastname"));
            req.setParameter("email", params.get("email"));


             Log.i("HTTP Client:", "filename:" + UshahidiPref.savePath + params.get("filename"));

             if( !TextUtils.isEmpty(params.get("filename")) || !(params.get("filename").equals("")))
                req.setParameter("photo", new File(UshahidiPref.savePath + params.get("filename")));


            InputStream serverInput = req.post();
File
NetworkServices.java
Developer's decision
Version 1
Kind of conflict
If statement
Method invocation
Chunk
Conflicting content
    public static String getCheckins(String URL, String mobileId, String checkinId) {
        StringBuilder fullUrl = new StringBuilder(URL);
<<<<<<< HEAD
    	fullUrl.append("/api");
    	Log.i("Domain URL: ", "URL: "+fullUrl);
=======
        fullUrl.append("/api");

>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
        try {
            URL url = new URL(fullUrl.toString());
            ClientHttpRequest req = new ClientHttpRequest(url);
Solution content
    public static String getCheckins(String URL, String mobileId, String checkinId) {
        StringBuilder fullUrl = new StringBuilder(URL);
    	fullUrl.append("/api");
    	Log.i("Domain URL: ", "URL: "+fullUrl);
        try {
            URL url = new URL(fullUrl.toString());
            ClientHttpRequest req = new ClientHttpRequest(url);
File
NetworkServices.java
Developer's decision
Version 1
Kind of conflict
Method invocation
Chunk
Conflicting content
import android.util.Log;

public class UshahidiDatabase {
<<<<<<< HEAD
	private static final String TAG = "UshahidiDatabase";

	public static final String INCIDENT_ID = "_id";
	public static final String INCIDENT_TITLE = "incident_title";
	public static final String INCIDENT_DESC = "incident_desc";
	public static final String INCIDENT_DATE = "incident_date";
	public static final String INCIDENT_MODE = "incident_mode";
	public static final String INCIDENT_VERIFIED = "incident_verified";
	public static final String INCIDENT_LOC_NAME = "incident_loc_name";
	public static final String INCIDENT_LOC_LATITUDE = "incident_loc_latitude";
	public static final String INCIDENT_LOC_LONGITUDE = "incident_loc_longitude";
	public static final String INCIDENT_CATEGORIES = "incident_categories";
	public static final String INCIDENT_MEDIA = "incident_media";
	public static final String INCIDENT_IMAGE = "incident_image";
	public static final String INCIDENT_IS_UNREAD = "is_unread";
	
	public static final String CATEGORY_ID = "_id";
	public static final String CATEGORY_TITLE = "category_title";
	public static final String CATEGORY_DESC = "category_desc";
	public static final String CATEGORY_COLOR = "category_color";
	public static final String CATEGORY_IS_UNREAD = "is_unread";
  
  	/**
	
	public static final String ADD_INCIDENT_ID = "_id";
	public static final String ADD_INCIDENT_TITLE = "incident_title";
        @Override
		+ CATEGORY_DESC + " TEXT, " 
	public static final String ADD_INCIDENT_DESC = "incident_desc";
	public static final String ADD_INCIDENT_DATE = "incident_date";
	public static final String ADD_INCIDENT_HOUR = "incident_hour";
	public static final String ADD_INCIDENT_MINUTE = "incident_minute";
	public static final String ADD_INCIDENT_AMPM = "incident_ampm";
	public static final String ADD_INCIDENT_CATEGORIES = "incident_categories";
	public static final String ADD_INCIDENT_LOC_NAME = "incident_loc_name";
	public static final String ADD_INCIDENT_LOC_LATITUDE = "incident_loc_latitude";
	public static final String ADD_INCIDENT_LOC_LONGITUDE = "incident_loc_longitude";
	public static final String ADD_INCIDENT_PHOTO = "incident_photo";
	public static final String ADD_INCIDENT_VIDEO =  "incident_video";
	public static final String ADD_INCIDENT_NEWS = "incident_news";
	public static final String ADD_PERSON_FIRST = "person_first";
	public static final String ADD_PERSON_LAST = "person_last";
	public static final String ADD_PERSON_EMAIL = "person_email";
 	
	public static final String[] INCIDENTS_COLUMNS = new String[] {	INCIDENT_ID,
		INCIDENT_TITLE, INCIDENT_DESC, INCIDENT_DATE, INCIDENT_MODE, INCIDENT_VERIFIED,
		INCIDENT_LOC_NAME,INCIDENT_LOC_LATITUDE,INCIDENT_LOC_LONGITUDE,INCIDENT_CATEGORIES,
		INCIDENT_MEDIA,INCIDENT_IMAGE, INCIDENT_IS_UNREAD
	};
	
	public static final String[] CATEGORIES_COLUMNS = new String[] { CATEGORY_ID,
		CATEGORY_TITLE,CATEGORY_DESC,CATEGORY_COLOR, CATEGORY_IS_UNREAD
	};
	
	public static final String[] ADD_INCIDENTS_COLUMNS = new String[] {
		ADD_INCIDENT_ID,
		ADD_INCIDENT_TITLE, ADD_INCIDENT_DESC, ADD_INCIDENT_DATE, ADD_INCIDENT_HOUR, ADD_INCIDENT_MINUTE,
		ADD_INCIDENT_AMPM,ADD_INCIDENT_CATEGORIES,INCIDENT_LOC_NAME,INCIDENT_LOC_LATITUDE,INCIDENT_LOC_LONGITUDE,
		ADD_INCIDENT_PHOTO,ADD_INCIDENT_VIDEO,ADD_INCIDENT_NEWS,ADD_PERSON_FIRST,ADD_PERSON_LAST,ADD_PERSON_EMAIL
	};
	
	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDb;
	private static final String DATABASE_NAME = "ushahidi_db";
	private static final String INCIDENTS_TABLE = "incidents";
	private static final String ADD_INCIDENTS_TABLE = "add_incidents";
	private static final String CATEGORIES_TABLE = "categories";
	private static final int DATABASE_VERSION = 10;

  // NOTE: the incident ID is used as the row ID.
  // Furthermore, if a row already exists, an insert will replace
  // the old row upon conflict.
	
	private static final String INCIDENTS_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS " + INCIDENTS_TABLE + " ("
		+ INCIDENT_ID + " INTEGER PRIMARY KEY ON CONFLICT REPLACE, "  
		+ INCIDENT_TITLE + " TEXT NOT NULL, "
		+ INCIDENT_DESC + " TEXT, "
		+ INCIDENT_DATE + " DATE NOT NULL, "
		+ INCIDENT_MODE + " INTEGER, "
		+ INCIDENT_VERIFIED + " INTEGER, "
		+ INCIDENT_LOC_NAME + " TEXT NOT NULL, "
		+ INCIDENT_LOC_LATITUDE + " TEXT NOT NULL, "
		+ INCIDENT_LOC_LONGITUDE + " TEXT NOT NULL, "
		+ INCIDENT_CATEGORIES + " TEXT NOT NULL, "
		+ INCIDENT_MEDIA + " TEXT, "
		+ INCIDENT_IMAGE + " TEXT, "
		+ INCIDENT_IS_UNREAD + " BOOLEAN NOT NULL "
		+ ")";
	
	private static final String ADD_INCIDENTS_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS " + ADD_INCIDENTS_TABLE + " ("
	+ ADD_INCIDENT_ID + " INTEGER PRIMARY KEY , "  
	+ ADD_INCIDENT_TITLE + " TEXT NOT NULL, "
	+ ADD_INCIDENT_DESC + " TEXT, "
	+ INCIDENT_DATE + " DATE NOT NULL, "
	+ ADD_INCIDENT_HOUR + " INTEGER, "
	+ ADD_INCIDENT_MINUTE + " INTEGER, "
	+ ADD_INCIDENT_AMPM + " TEXT NOT NULL, "
	+ ADD_INCIDENT_CATEGORIES + " TEXT NOT NULL, "
	+ ADD_INCIDENT_LOC_NAME + " TEXT NOT NULL, "
	+ ADD_INCIDENT_LOC_LATITUDE + " TEXT NOT NULL, "
	+ ADD_INCIDENT_LOC_LONGITUDE + " TEXT NOT NULL, "
	+ ADD_INCIDENT_PHOTO + " TEXT, "
	+ ADD_INCIDENT_VIDEO + " TEXT, "
	+ ADD_INCIDENT_NEWS + " TEXT, "
	+ ADD_PERSON_FIRST + " TEXT, "
	+ ADD_PERSON_LAST + " TEXT, "
	+ ADD_PERSON_EMAIL + " TEXT "
	+ ")";
	
	
	private static final String CATEGORIES_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS " + CATEGORIES_TABLE + " ("
		+ CATEGORY_ID + " INTEGER PRIMARY KEY ON CONFLICT REPLACE, "
		+ CATEGORY_TITLE + " TEXT NOT NULL, " 
    		db.execSQL(String.format( "INSERT INTO %s (%s) SELECT %s FROM temp_%s", CATEGORIES_TABLE, catsCols, catsCols, CATEGORIES_TABLE));
		+ CATEGORY_COLOR + " TEXT, "
		+ CATEGORY_IS_UNREAD + " BOOLEAN NOT NULL "
		+ ")";
	

	private final Context mContext;

	private static class DatabaseHelper extends SQLiteOpenHelper {
		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(INCIDENTS_TABLE_CREATE);
    		db.execSQL(CATEGORIES_TABLE_CREATE);
    		db.execSQL(ADD_INCIDENTS_TABLE_CREATE);
		}

    	@Override
    	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    		Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
    				+ newVersion + " which destroys all old data");
    		List incidentsColumns;
    		List categoriesColumns;
    		List addIncidentColumns;
    		// upgrade incident table
    		db.execSQL(INCIDENTS_TABLE_CREATE);
    		incidentsColumns = UshahidiDatabase.getColumns(db, INCIDENTS_TABLE);
    		db.execSQL("ALTER TABLE "  + INCIDENTS_TABLE + " RENAME TO temp_" + INCIDENTS_TABLE);
    		db.execSQL(INCIDENTS_TABLE_CREATE);
    		incidentsColumns.retainAll(UshahidiDatabase.getColumns(db, INCIDENTS_TABLE));
    		String cols = UshahidiDatabase.join(incidentsColumns, ",");
    		db.execSQL(String.format( "INSERT INTO %s (%s) SELECT %s FROM temp_%s", INCIDENTS_TABLE, cols, cols, INCIDENTS_TABLE));
    		db.execSQL("DROP TABLE IF EXISTS temp_" + INCIDENTS_TABLE);
    		
    		// upgrade category table
    		db.execSQL(CATEGORIES_TABLE_CREATE);
    		categoriesColumns = UshahidiDatabase.getColumns(db, CATEGORIES_TABLE);
    		db.execSQL("ALTER TABLE "  + CATEGORIES_TABLE + " RENAME TO temp_" + CATEGORIES_TABLE);
    		db.execSQL(CATEGORIES_TABLE_CREATE);
    		categoriesColumns.retainAll(UshahidiDatabase.getColumns(db, CATEGORIES_TABLE));
    		String catsCols = UshahidiDatabase.join(categoriesColumns, ",");
    		db.execSQL("DROP TABLE IF EXISTS temp_" + CATEGORIES_TABLE);
    		
    		// upgrade add incident table
    		db.execSQL(ADD_INCIDENTS_TABLE_CREATE);
    		addIncidentColumns = UshahidiDatabase.getColumns(db, ADD_INCIDENTS_TABLE);
    		db.execSQL("ALTER TABLE "  + ADD_INCIDENTS_TABLE + " RENAME TO temp_" + ADD_INCIDENTS_TABLE);
    		db.execSQL(ADD_INCIDENTS_TABLE_CREATE);
    		addIncidentColumns.retainAll(UshahidiDatabase.getColumns(db, ADD_INCIDENTS_TABLE));
    		String addIncidentCols = UshahidiDatabase.join(addIncidentColumns, ",");
    		db.execSQL(String.format( "INSERT INTO %s (%s) SELECT %s FROM temp_%s", ADD_INCIDENTS_TABLE, addIncidentCols, addIncidentCols, ADD_INCIDENTS_TABLE));
    		db.execSQL("DROP TABLE IF EXISTS temp_" + ADD_INCIDENTS_TABLE);
    		
      		onCreate(db);
    	}
    	
    	
	}

	/**
	 * Credits http://goo.gl/7kOpU
	 * @param db
	 * @param tableName
	 * @return
	 */
	public static List getColumns(SQLiteDatabase db, String tableName) {
		List ar = null;
		Cursor c = null;
		
		try {
			c = db.rawQuery("SELECT * FROM "+tableName+" LIMIT 1", null);
			
			if ( c!= null) {
				ar = new ArrayList(Arrays.asList(c.getColumnNames()));
			}
			
		}catch(Exception e){	
			Log.v(tableName, e.getMessage(), e);
			e.printStackTrace();
		} finally {
			if (c!= null)
				c.close();
		}
		return ar;
	}
	
	public static String join(List list, String delim) {
		StringBuilder buf = new StringBuilder();
		int num = list.size();
		for ( int i = 0; i < num; i++){
			if (i != 0)
				buf.append(delim);

			buf.append((String) list.get(i));
		}
		return buf.toString();
	}
	
	public UshahidiDatabase(Context context) {
		this.mContext = context;
	}

  	public UshahidiDatabase open() throws SQLException {
  		mDbHelper = new DatabaseHelper(mContext);
	  	mDb = mDbHelper.getWritableDatabase();

	  	return this;
  	}

  	public void close() {
  		mDbHelper.close();
  	}

  	public long createIncidents(IncidentsData incidents, boolean isUnread) {
  		ContentValues initialValues = new ContentValues();
  		
    	initialValues.put(INCIDENT_ID, incidents.getIncidentId());
    	initialValues.put(INCIDENT_TITLE, incidents.getIncidentTitle());
    	initialValues.put(INCIDENT_DESC, incidents.getIncidentDesc());
    	initialValues.put(INCIDENT_DATE, incidents.getIncidentDate());
    	initialValues.put(INCIDENT_MODE, incidents.getIncidentMode());
    	initialValues.put(INCIDENT_VERIFIED, incidents.getIncidentVerified());
    	initialValues.put(INCIDENT_LOC_NAME, incidents.getIncidentLocation());
    	initialValues.put(INCIDENT_LOC_LATITUDE, incidents.getIncidentLocLatitude());
    	initialValues.put(INCIDENT_LOC_LONGITUDE, incidents.getIncidentLocLongitude());
    	initialValues.put(INCIDENT_CATEGORIES, incidents.getIncidentCategories());
    	initialValues.put(INCIDENT_MEDIA, incidents.getIncidentThumbnail());
    	
    	initialValues.put(INCIDENT_IMAGE, incidents.getIncidentImage());
    	initialValues.put(INCIDENT_IS_UNREAD, isUnread);

    	return mDb.insert(INCIDENTS_TABLE, null, initialValues);
  	}
  	
  	public long createAddIncident(AddIncidentData addIncident) {
  		ContentValues initialValues = new ContentValues();
  		
    	initialValues.put(ADD_INCIDENT_TITLE, addIncident.getIncidentTitle());
    	initialValues.put(ADD_INCIDENT_DESC, addIncident.getIncidentDesc());
    	initialValues.put(ADD_INCIDENT_DATE, addIncident.getIncidentDate());
    	initialValues.put(ADD_INCIDENT_HOUR, addIncident.getIncidentHour());
    	initialValues.put(ADD_INCIDENT_MINUTE, addIncident.getIncidentMinute());
    	initialValues.put(ADD_INCIDENT_AMPM, addIncident.getIncidentAmPm());
    	initialValues.put(ADD_INCIDENT_CATEGORIES, addIncident.getIncidentCategories());
    	initialValues.put(INCIDENT_LOC_NAME, addIncident.getIncidentLocName());
    	initialValues.put(INCIDENT_LOC_LATITUDE, addIncident.getIncidentLocLatitude());
    	initialValues.put(INCIDENT_LOC_LONGITUDE, addIncident.getIncidentLocLongitude());
    	initialValues.put(ADD_INCIDENT_PHOTO, addIncident.getIncidentPhoto());
    	initialValues.put(ADD_INCIDENT_VIDEO, addIncident.getIncidentVideo());
    	initialValues.put(ADD_INCIDENT_NEWS, addIncident.getIncidentNews());
    	initialValues.put(ADD_PERSON_FIRST, addIncident.getPersonFirst());
    	initialValues.put(ADD_PERSON_LAST, addIncident.getPersonLast());
    	initialValues.put(ADD_PERSON_EMAIL, addIncident.getPersonEmail());
    	
  		return mDb.insert(ADD_INCIDENTS_TABLE, null, initialValues);
  	}

  	public long createCategories(CategoriesData categories, boolean isUnread) {
  		ContentValues initialValues = new ContentValues();
  		initialValues.put(CATEGORY_ID, categories.getCategoryId());
  		initialValues.put(CATEGORY_TITLE, categories.getCategoryTitle());
  		initialValues.put(CATEGORY_DESC, categories.getCategoryDescription());
  		initialValues.put(CATEGORY_COLOR, categories.getCategoryColor());
  		initialValues.put(CATEGORY_IS_UNREAD, isUnread);
  		return mDb.insert(CATEGORIES_TABLE, null, initialValues);
  	}

  	public int addNewIncidentsAndCountUnread(ArrayList newIncidents) {
  		addIncidents(newIncidents, true);
  		return fetchUnreadCount();
  	}

  public Cursor fetchAllIncidents() {
    return mDb.query(INCIDENTS_TABLE, INCIDENTS_COLUMNS, null, null, null, null, INCIDENT_DATE
        + " DESC");
  }
  
  public Cursor fetchAllOfflineIncidents() {
	  return mDb.query(ADD_INCIDENTS_TABLE, ADD_INCIDENTS_COLUMNS, null, null, null, null, 
			  ADD_INCIDENT_ID + " DESC");
  }
    // NOTE: the incident ID is used as the row ID.
  public Cursor fetchAllCategories() {
    return mDb.query(CATEGORIES_TABLE, CATEGORIES_COLUMNS, null, null, null, null, CATEGORY_ID
        + " DESC");
  }

  	public Cursor fetchIncidentsByCategories( String filter ) {
  	    
  		String likeFilter = '%' + filter + '%';
  		String sql = "SELECT * FROM "+INCIDENTS_TABLE+" WHERE "+INCIDENT_CATEGORIES+" LIKE ? ORDER BY "
  			+INCIDENT_TITLE+" COLLATE NOCASE";
  		return mDb.rawQuery(sql, new String[] { likeFilter } );
  	}
  
  	public Cursor fetchIncidentsById( String id ) {
  		  		String sql = "SELECT * FROM "+INCIDENTS_TABLE+" WHERE "+INCIDENT_ID+" = ? ORDER BY "
  			+INCIDENT_TITLE+" COLLATE NOCASE";
  		return mDb.rawQuery(sql, new String[] { id } );
  	}

  	public boolean clearData() {
  		
  		deleteAllIncidents();
  		deleteAllCategories();
  		return true;
  		
  	}

  	public boolean deleteAllIncidents() {
  		return mDb.delete(INCIDENTS_TABLE, null, null) > 0;
  	}

  	public boolean deleteAllCategories() {
  		return mDb.delete(CATEGORIES_TABLE, null, null) > 0;
  	}

  	public boolean deleteCategory(int id) {
  		return mDb.delete(CATEGORIES_TABLE, CATEGORY_ID + "=" + id, null) > 0;
  	}
  	
  	/**
  	 * Clear the offline table for adding incidents
  	 * @return boolean
  	 */
  	public boolean deleteAddIncidents() {
  		return mDb.delete(ADD_INCIDENTS_TABLE, null, null ) > 0;
  	}

  	public void markAllIncidentssRead() {
	  ContentValues values = new ContentValues();
    	values.put(INCIDENT_IS_UNREAD, 0);
    	mDb.update(INCIDENTS_TABLE, values, null, null);
  	}

  	public void markAllCategoriesRead() {
	  ContentValues values = new ContentValues();
    	values.put(CATEGORY_IS_UNREAD, 0);
    	mDb.update(CATEGORIES_TABLE, values, null, null);
  	}

  	public int fetchMaxId() {
  		Cursor mCursor = mDb.rawQuery("SELECT MAX(" + INCIDENT_ID + ") FROM "
        + INCIDENTS_TABLE, null);

  		int result = 0;

  		if (mCursor == null) {
  			return result;
  		}

  		mCursor.moveToFirst();
  		result = mCursor.getInt(0);
  		mCursor.close();

  		return result;
  	}

  	public int fetchUnreadCount() {
  		Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + INCIDENT_ID + ") FROM "
  				+ INCIDENTS_TABLE + " WHERE " + INCIDENT_IS_UNREAD + " = 1", null);

  		int result = 0;

  		if (mCursor == null) {
  			return result;
  		}

  		mCursor.moveToFirst();
  		result = mCursor.getInt(0);
  		mCursor.close();

  		return result;
  	}

  	/*public int fetchMaxCategoryId(boolean isSent) {
  		Cursor mCursor = mDb.rawQuery("SELECT MAX(" + CATEGORY_ID + ") FROM " + CATEGORIES_TABLE
  				+ " WHERE " + CATEGORIES_IS_SENT + " = ?", new String[] { isSent ? "1" : "0" });

  		int result = 0;

  		if (mCursor == null) {
  			return result;
  		}

  		mCursor.moveToFirst();
  		result = mCursor.getInt(0);
  		mCursor.close();

  		return result;
  	}*/


  	 * Adds new incidents to be posted online to the db.
    public static final String INCIDENT_DESC = "incident_desc";
  	public int addNewCategoryAndCountUnread(List categories) {
  		addCategories(categories, true);

  		return fetchUnreadCategoriesCount();
  	}

  	public int fetchCategoriesCount() {
  		Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + CATEGORY_ID + ") FROM "
  				+ CATEGORIES_TABLE, null);

  		int result = 0;

  		if (mCursor == null) {
  			return result;
  		}

    mCursor.moveToFirst();
    result = mCursor.getInt(0);
    mCursor.close();

    return result;
  }
  
  	private int fetchUnreadCategoriesCount() {
  		Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + CATEGORY_ID + ") FROM "
  				+ CATEGORIES_TABLE + " WHERE " + CATEGORY_IS_UNREAD + " = 1", null);

  		int result = 0;

  		if (mCursor == null) {
  			return result;
  		}

  		mCursor.moveToFirst();
  		result = mCursor.getInt(0);
  		mCursor.close();

  		return result;
  	}

  	public void addIncidents(List incidents, boolean isUnread) {
  		try {
  			mDb.beginTransaction();

  			for (IncidentsData incident : incidents) {
  				createIncidents(incident, isUnread);
  			}

  			limitRows(INCIDENTS_TABLE, Integer.parseInt(UshahidiPref.totalReports), INCIDENT_ID);
  			mDb.setTransactionSuccessful();
  		} finally {
  			mDb.endTransaction();
  		}
  	}
  	
  	 * @param List addIncidents
  	 */
  	public long addIncidents(List addIncidents ) {
  		long rowId = 0;
  		try {
  			mDb.beginTransaction();
  			for( AddIncidentData addIncident: addIncidents ) {
  				rowId = createAddIncident(addIncident);
  			}
  			mDb.setTransactionSuccessful();
  			
  		} finally {
  			mDb.endTransaction();
  		}
  		
  		return rowId;
  	}

  	public void addCategories(List categories, boolean isUnread) {
  		try {
  			mDb.beginTransaction();

  			for (CategoriesData category : categories) {
  				createCategories(category, isUnread);
  			}

  			mDb.setTransactionSuccessful();
  		} finally {
  			mDb.endTransaction();
  		}
  	}

  	public int limitRows(String tablename, int limit, String KEY_ID) {
  		Cursor cursor = mDb.rawQuery("SELECT " + KEY_ID + " FROM " + tablename
  				+ " ORDER BY " + KEY_ID + " DESC LIMIT 1 OFFSET ?",
  				new String[] { limit - 1 + "" });

  		int deleted = 0;

  		if (cursor != null && cursor.moveToFirst()) {
  			int limitId = cursor.getInt(0);
  			deleted = mDb.delete(tablename, KEY_ID + "<" + limitId, null);
  		}

  		cursor.close();

  		return deleted;
  	}
=======
    private static final String TAG = "UshahidiDatabase";

    public static final String INCIDENT_ID = "_id";

    public static final String INCIDENT_TITLE = "incident_title";



    public static final String ADD_INCIDENT_LOC_NAME = "incident_loc_name";

    private static final int DATABASE_VERSION = 10;

    public static final String INCIDENT_DATE = "incident_date";

    public static final String INCIDENT_MODE = "incident_mode";

    public static final String INCIDENT_VERIFIED = "incident_verified";

    public static final String INCIDENT_LOC_NAME = "incident_loc_name";

    public static final String INCIDENT_LOC_LATITUDE = "incident_loc_latitude";

    public static final String INCIDENT_LOC_LONGITUDE = "incident_loc_longitude";

    public static final String INCIDENT_CATEGORIES = "incident_categories";

    public static final String INCIDENT_MEDIA = "incident_media";

    public static final String INCIDENT_IMAGE = "incident_image";

    public static final String INCIDENT_IS_UNREAD = "is_unread";

    public static final String CATEGORY_ID = "_id";

    public static final String CATEGORY_TITLE = "category_title";

    public static final String CATEGORY_DESC = "category_desc";

    public static final String CATEGORY_COLOR = "category_color";

    public static final String CATEGORY_IS_UNREAD = "is_unread";

    public static final String ADD_INCIDENT_ID = "_id";

    public static final String ADD_INCIDENT_TITLE = "incident_title";

    public static final String ADD_INCIDENT_DESC = "incident_desc";

    public static final String ADD_INCIDENT_DATE = "incident_date";

    public static final String ADD_INCIDENT_HOUR = "incident_hour";

    public static final String ADD_INCIDENT_MINUTE = "incident_minute";

    public static final String ADD_INCIDENT_AMPM = "incident_ampm";

    public static final String ADD_INCIDENT_CATEGORIES = "incident_categories";
    public static final String ADD_INCIDENT_LOC_LATITUDE = "incident_loc_latitude";

    public static final String ADD_INCIDENT_LOC_LONGITUDE = "incident_loc_longitude";

    public static final String ADD_INCIDENT_PHOTO = "incident_photo";

    public static final String ADD_INCIDENT_VIDEO = "incident_video";

    public static final String ADD_INCIDENT_NEWS = "incident_news";

    public static final String ADD_PERSON_FIRST = "person_first";

    public static final String ADD_PERSON_LAST = "person_last";

    public static final String ADD_PERSON_EMAIL = "person_email";

    public static final String[] INCIDENTS_COLUMNS = new String[] {
            INCIDENT_ID, INCIDENT_TITLE, INCIDENT_DESC, INCIDENT_DATE, INCIDENT_MODE,
            INCIDENT_VERIFIED, INCIDENT_LOC_NAME, INCIDENT_LOC_LATITUDE, INCIDENT_LOC_LONGITUDE,
            INCIDENT_CATEGORIES, INCIDENT_MEDIA, INCIDENT_IMAGE, INCIDENT_IS_UNREAD
    };

    public static final String[] CATEGORIES_COLUMNS = new String[] {
            CATEGORY_ID, CATEGORY_TITLE, CATEGORY_DESC, CATEGORY_COLOR, CATEGORY_IS_UNREAD
    };

    public static final String[] ADD_INCIDENTS_COLUMNS = new String[] {
            ADD_INCIDENT_ID, ADD_INCIDENT_TITLE, ADD_INCIDENT_DESC, ADD_INCIDENT_DATE,
            ADD_INCIDENT_HOUR, ADD_INCIDENT_MINUTE, ADD_INCIDENT_AMPM, ADD_INCIDENT_CATEGORIES,
            INCIDENT_LOC_NAME, INCIDENT_LOC_LATITUDE, INCIDENT_LOC_LONGITUDE, ADD_INCIDENT_PHOTO,
            ADD_INCIDENT_VIDEO, ADD_INCIDENT_NEWS, ADD_PERSON_FIRST, ADD_PERSON_LAST,
            ADD_PERSON_EMAIL
    };

    private DatabaseHelper mDbHelper;

    private SQLiteDatabase mDb;

    private static final String DATABASE_NAME = "ushahidi_db";

    private static final String INCIDENTS_TABLE = "incidents";

    private static final String ADD_INCIDENTS_TABLE = "add_incidents";

    private static final String CATEGORIES_TABLE = "categories";

            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
    // Furthermore, if a row already exists, an insert will replace
    // the old row upon conflict.

    private static final String INCIDENTS_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS "
            + INCIDENTS_TABLE + " (" + INCIDENT_ID + " INTEGER PRIMARY KEY ON CONFLICT REPLACE, "
            + INCIDENT_TITLE + " TEXT NOT NULL, " + INCIDENT_DESC + " TEXT, " + INCIDENT_DATE
            + " DATE NOT NULL, " + INCIDENT_MODE + " INTEGER, " + INCIDENT_VERIFIED + " INTEGER, "
            + INCIDENT_LOC_NAME + " TEXT NOT NULL, " + INCIDENT_LOC_LATITUDE + " TEXT NOT NULL, "
            + INCIDENT_LOC_LONGITUDE + " TEXT NOT NULL, " + INCIDENT_CATEGORIES
            + " TEXT NOT NULL, " + INCIDENT_MEDIA + " TEXT, " + INCIDENT_IMAGE + " TEXT, "
            + INCIDENT_IS_UNREAD + " BOOLEAN NOT NULL " + ")";

    private static final String ADD_INCIDENTS_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS "
            + ADD_INCIDENTS_TABLE + " (" + ADD_INCIDENT_ID + " INTEGER PRIMARY KEY , "
            + ADD_INCIDENT_TITLE + " TEXT NOT NULL, " + ADD_INCIDENT_DESC + " TEXT, "
            + INCIDENT_DATE + " DATE NOT NULL, " + ADD_INCIDENT_HOUR + " INTEGER, "
            + ADD_INCIDENT_MINUTE + " INTEGER, " + ADD_INCIDENT_AMPM + " TEXT NOT NULL, "
            + ADD_INCIDENT_CATEGORIES + " TEXT NOT NULL, " + ADD_INCIDENT_LOC_NAME
            + " TEXT NOT NULL, " + ADD_INCIDENT_LOC_LATITUDE + " TEXT NOT NULL, "
            + ADD_INCIDENT_LOC_LONGITUDE + " TEXT NOT NULL, " + ADD_INCIDENT_PHOTO + " TEXT, "
            + ADD_INCIDENT_VIDEO + " TEXT, " + ADD_INCIDENT_NEWS + " TEXT, " + ADD_PERSON_FIRST
            + " TEXT, " + ADD_PERSON_LAST + " TEXT, " + ADD_PERSON_EMAIL + " TEXT " + ")";

    private static final String CATEGORIES_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS "
            + CATEGORIES_TABLE + " (" + CATEGORY_ID + " INTEGER PRIMARY KEY ON CONFLICT REPLACE, "
            + CATEGORY_TITLE + " TEXT NOT NULL, " + CATEGORY_DESC + " TEXT, " + CATEGORY_COLOR
            + " TEXT, " + CATEGORY_IS_UNREAD + " BOOLEAN NOT NULL " + ")";

    private final Context mContext;

    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {

        public void onCreate(SQLiteDatabase db) {
            db.execSQL(INCIDENTS_TABLE_CREATE);
            db.execSQL(CATEGORIES_TABLE_CREATE);
            db.execSQL(ADD_INCIDENTS_TABLE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion
                    + " which destroys all old data");
            List incidentsColumns;
            List categoriesColumns;
            List addIncidentColumns;
            // upgrade incident table
            db.execSQL(INCIDENTS_TABLE_CREATE);
            incidentsColumns = UshahidiDatabase.getColumns(db, INCIDENTS_TABLE);
            db.execSQL("ALTER TABLE " + INCIDENTS_TABLE + " RENAME TO temp_" + INCIDENTS_TABLE);
            db.execSQL(INCIDENTS_TABLE_CREATE);
            incidentsColumns.retainAll(UshahidiDatabase.getColumns(db, INCIDENTS_TABLE));
            String cols = UshahidiDatabase.join(incidentsColumns, ",");
            db.execSQL(String.format("INSERT INTO %s (%s) SELECT %s FROM temp_%s", INCIDENTS_TABLE,
                    cols, cols, INCIDENTS_TABLE));
            db.execSQL("DROP TABLE IF EXISTS temp_" + INCIDENTS_TABLE);

            // upgrade category table
            db.execSQL(CATEGORIES_TABLE_CREATE);
            categoriesColumns = UshahidiDatabase.getColumns(db, CATEGORIES_TABLE);
            db.execSQL("ALTER TABLE " + CATEGORIES_TABLE + " RENAME TO temp_" + CATEGORIES_TABLE);
            db.execSQL(CATEGORIES_TABLE_CREATE);
            categoriesColumns.retainAll(UshahidiDatabase.getColumns(db, CATEGORIES_TABLE));
            String catsCols = UshahidiDatabase.join(categoriesColumns, ",");
            db.execSQL(String.format("INSERT INTO %s (%s) SELECT %s FROM temp_%s",
                    CATEGORIES_TABLE, catsCols, catsCols, CATEGORIES_TABLE));
            db.execSQL("DROP TABLE IF EXISTS temp_" + CATEGORIES_TABLE);

            // upgrade add incident table
            db.execSQL(ADD_INCIDENTS_TABLE_CREATE);
            addIncidentColumns = UshahidiDatabase.getColumns(db, ADD_INCIDENTS_TABLE);
        values.put(INCIDENT_IS_UNREAD, 0);
        initialValues.put(ADD_INCIDENT_HOUR, addIncident.getIncidentHour());
            db.execSQL("ALTER TABLE " + ADD_INCIDENTS_TABLE + " RENAME TO temp_"
                    + ADD_INCIDENTS_TABLE);
            db.execSQL(ADD_INCIDENTS_TABLE_CREATE);
            addIncidentColumns.retainAll(UshahidiDatabase.getColumns(db, ADD_INCIDENTS_TABLE));
            String addIncidentCols = UshahidiDatabase.join(addIncidentColumns, ",");
            db.execSQL(String.format("INSERT INTO %s (%s) SELECT %s FROM temp_%s",
                    ADD_INCIDENTS_TABLE, addIncidentCols, addIncidentCols, ADD_INCIDENTS_TABLE));
            db.execSQL("DROP TABLE IF EXISTS temp_" + ADD_INCIDENTS_TABLE);

            onCreate(db);
        }

    }

    /**
     * Credits http://goo.gl/7kOpU
     * 
     * @param db
     * @param tableName
     * @return
     */
    public static List getColumns(SQLiteDatabase db, String tableName) {
        List ar = null;
        Cursor c = null;

        try {
            c = db.rawQuery("SELECT * FROM " + tableName + " LIMIT 1", null);

            if (c != null) {
                ar = new ArrayList(Arrays.asList(c.getColumnNames()));
            }

        } catch (Exception e) {
            Log.v(tableName, e.getMessage(), e);
            e.printStackTrace();
        } finally {
            if (c != null)
                c.close();
        }
        return ar;
    }

    public static String join(List list, String delim) {
        StringBuilder buf = new StringBuilder();
        int num = list.size();
        for (int i = 0; i < num; i++) {
            if (i != 0)
                buf.append(delim);
            buf.append((String)list.get(i));
        }
        return buf.toString();
    }

    public UshahidiDatabase(Context context) {
        this.mContext = context;
    }

    public UshahidiDatabase open() throws SQLException {
        mDbHelper = new DatabaseHelper(mContext);
        mDb = mDbHelper.getWritableDatabase();

        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    public long createIncidents(IncidentsData incidents, boolean isUnread) {
        ContentValues initialValues = new ContentValues();

        initialValues.put(INCIDENT_ID, incidents.getIncidentId());
        initialValues.put(INCIDENT_TITLE, incidents.getIncidentTitle());
        initialValues.put(INCIDENT_DESC, incidents.getIncidentDesc());
        initialValues.put(INCIDENT_DATE, incidents.getIncidentDate());
        initialValues.put(INCIDENT_MODE, incidents.getIncidentMode());
        initialValues.put(INCIDENT_VERIFIED, incidents.getIncidentVerified());
        initialValues.put(INCIDENT_LOC_NAME, incidents.getIncidentLocation());
        initialValues.put(INCIDENT_LOC_LATITUDE, incidents.getIncidentLocLatitude());
        initialValues.put(INCIDENT_LOC_LONGITUDE, incidents.getIncidentLocLongitude());
        initialValues.put(INCIDENT_CATEGORIES, incidents.getIncidentCategories());
        initialValues.put(INCIDENT_MEDIA, incidents.getIncidentThumbnail());

        initialValues.put(INCIDENT_IMAGE, incidents.getIncidentImage());
        initialValues.put(INCIDENT_IS_UNREAD, isUnread);

        return mDb.insert(INCIDENTS_TABLE, null, initialValues);
    }

    public long createAddIncident(AddIncidentData addIncident) {
        ContentValues initialValues = new ContentValues();

        initialValues.put(ADD_INCIDENT_TITLE, addIncident.getIncidentTitle());
        initialValues.put(ADD_INCIDENT_DESC, addIncident.getIncidentDesc());
        initialValues.put(ADD_INCIDENT_DATE, addIncident.getIncidentDate());
        initialValues.put(ADD_INCIDENT_MINUTE, addIncident.getIncidentMinute());
    public Cursor fetchAllCategories() {
        initialValues.put(ADD_INCIDENT_AMPM, addIncident.getIncidentAmPm());
        initialValues.put(ADD_INCIDENT_CATEGORIES, addIncident.getIncidentCategories());
        initialValues.put(INCIDENT_LOC_NAME, addIncident.getIncidentLocName());
        initialValues.put(INCIDENT_LOC_LATITUDE, addIncident.getIncidentLocLatitude());
        initialValues.put(INCIDENT_LOC_LONGITUDE, addIncident.getIncidentLocLongitude());
        initialValues.put(ADD_INCIDENT_PHOTO, addIncident.getIncidentPhoto());
        initialValues.put(ADD_INCIDENT_VIDEO, addIncident.getIncidentVideo());
        initialValues.put(ADD_INCIDENT_NEWS, addIncident.getIncidentNews());
        initialValues.put(ADD_PERSON_FIRST, addIncident.getPersonFirst());
        initialValues.put(ADD_PERSON_LAST, addIncident.getPersonLast());
        initialValues.put(ADD_PERSON_EMAIL, addIncident.getPersonEmail());

        return mDb.insert(ADD_INCIDENTS_TABLE, null, initialValues);
    }

    public long createCategories(CategoriesData categories, boolean isUnread) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(CATEGORY_ID, categories.getCategoryId());
        initialValues.put(CATEGORY_TITLE, categories.getCategoryTitle());
        initialValues.put(CATEGORY_DESC, categories.getCategoryDescription());
        initialValues.put(CATEGORY_COLOR, categories.getCategoryColor());
        initialValues.put(CATEGORY_IS_UNREAD, isUnread);
        return mDb.insert(CATEGORIES_TABLE, null, initialValues);
    }

    public int addNewIncidentsAndCountUnread(ArrayList newIncidents) {
        addIncidents(newIncidents, true);
        return fetchUnreadCount();
    }

    public Cursor fetchAllIncidents() {
        return mDb.query(INCIDENTS_TABLE, INCIDENTS_COLUMNS, null, null, null, null, INCIDENT_DATE
                + " DESC");
    }

    public Cursor fetchAllOfflineIncidents() {
        return mDb.query(ADD_INCIDENTS_TABLE, ADD_INCIDENTS_COLUMNS, null, null, null, null,
                ADD_INCIDENT_ID + " DESC");
    }
        return mDb.query(CATEGORIES_TABLE, CATEGORIES_COLUMNS, null, null, null, null, CATEGORY_ID
                + " DESC");
    }

    public Cursor fetchIncidentsByCategories(String filter) {

        String likeFilter = '%' + filter + '%';
        String sql = "SELECT * FROM " + INCIDENTS_TABLE + " WHERE " + INCIDENT_CATEGORIES
                + " LIKE ? ORDER BY " + INCIDENT_TITLE + " COLLATE NOCASE";
        return mDb.rawQuery(sql, new String[] {
            likeFilter
        });
    }

    public Cursor fetchIncidentsById(String id) {
        String sql = "SELECT * FROM " + INCIDENTS_TABLE + " WHERE " + INCIDENT_ID
                + " = ? ORDER BY " + INCIDENT_TITLE + " COLLATE NOCASE";
        return mDb.rawQuery(sql, new String[] {
            id
        });
    }

    public boolean clearData() {

        deleteAllIncidents();
        deleteAllCategories();
        return true;

    }

    public boolean deleteAllIncidents() {
        return mDb.delete(INCIDENTS_TABLE, null, null) > 0;
    }

    public boolean deleteAllCategories() {
        return mDb.delete(CATEGORIES_TABLE, null, null) > 0;
    }

    public boolean deleteCategory(int id) {
        return mDb.delete(CATEGORIES_TABLE, CATEGORY_ID + "=" + id, null) > 0;
    }

    /**
     * Clear the offline table for adding incidents
     * 
     * @return boolean
     */
    public boolean deleteAddIncidents() {
        return mDb.delete(ADD_INCIDENTS_TABLE, null, null) > 0;
    }

    public void markAllIncidentssRead() {
        ContentValues values = new ContentValues();
        mDb.update(INCIDENTS_TABLE, values, null, null);
    }

    public void markAllCategoriesRead() {
        ContentValues values = new ContentValues();
        values.put(CATEGORY_IS_UNREAD, 0);
        mDb.update(CATEGORIES_TABLE, values, null, null);
    }

    public int fetchMaxId() {
        Cursor mCursor = mDb.rawQuery("SELECT MAX(" + INCIDENT_ID + ") FROM " + INCIDENTS_TABLE,
                null);

        int result = 0;

        if (mCursor == null) {
            return result;
        }

        mCursor.moveToFirst();
        result = mCursor.getInt(0);
        mCursor.close();

        return result;
    }

    public int fetchUnreadCount() {
        Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + INCIDENT_ID + ") FROM " + INCIDENTS_TABLE
                + " WHERE " + INCIDENT_IS_UNREAD + " = 1", null);

        int result = 0;

        if (mCursor == null) {
            return result;
        }

        mCursor.moveToFirst();
        result = mCursor.getInt(0);
        mCursor.close();

        return result;
    }

    /*
     * public int fetchMaxCategoryId(boolean isSent) { Cursor mCursor =
     * mDb.rawQuery("SELECT MAX(" + CATEGORY_ID + ") FROM " + CATEGORIES_TABLE +
     * " WHERE " + CATEGORIES_IS_SENT + " = ?", new String[] { isSent ? "1" :
     * "0" }); int result = 0; if (mCursor == null) { return result; }
     * mCursor.moveToFirst(); result = mCursor.getInt(0); mCursor.close();
     * return result; }
     */

    public int addNewCategoryAndCountUnread(List categories) {
        addCategories(categories, true);

        return fetchUnreadCategoriesCount();
    }

    public int fetchCategoriesCount() {
        Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + CATEGORY_ID + ") FROM " + CATEGORIES_TABLE,
                null);

        int result = 0;

        if (mCursor == null) {
            return result;
        }

        mCursor.moveToFirst();
        result = mCursor.getInt(0);
        mCursor.close();

        return result;
    }

    private int fetchUnreadCategoriesCount() {
        Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + CATEGORY_ID + ") FROM " + CATEGORIES_TABLE
                + " WHERE " + CATEGORY_IS_UNREAD + " = 1", null);

        int result = 0;

        if (mCursor == null) {
            return result;
        }

        mCursor.moveToFirst();
        result = mCursor.getInt(0);
        mCursor.close();

        return result;
    }

    public void addIncidents(List incidents, boolean isUnread) {
        try {
            mDb.beginTransaction();

            for (IncidentsData incident : incidents) {
                createIncidents(incident, isUnread);
            }

            limitRows(INCIDENTS_TABLE, Integer.parseInt(UshahidiService.totalReports), INCIDENT_ID);
            mDb.setTransactionSuccessful();
        } finally {
            mDb.endTransaction();
        }
    }

    /**
     * Adds new incidents to be posted online to the db.
     * 
     * @param List addIncidents
     */
    public long addIncidents(List addIncidents) {
        long rowId = 0;
        try {
            mDb.beginTransaction();
            for (AddIncidentData addIncident : addIncidents) {
                rowId = createAddIncident(addIncident);
            }
            mDb.setTransactionSuccessful();

        } finally {
            mDb.endTransaction();
        }

        return rowId;
    }

    public void addCategories(List categories, boolean isUnread) {
        try {
            mDb.beginTransaction();

            for (CategoriesData category : categories) {
                createCategories(category, isUnread);
            }

            mDb.setTransactionSuccessful();
        } finally {
            mDb.endTransaction();
        }
    }

    public int limitRows(String tablename, int limit, String KEY_ID) {
        Cursor cursor = mDb.rawQuery("SELECT " + KEY_ID + " FROM " + tablename + " ORDER BY "
                + KEY_ID + " DESC LIMIT 1 OFFSET ?", new String[] {
            limit - 1 + ""
        });

        int deleted = 0;

        if (cursor != null && cursor.moveToFirst()) {
            int limitId = cursor.getInt(0);
            deleted = mDb.delete(tablename, KEY_ID + "<" + limitId, null);
        }

        cursor.close();

        return deleted;
    }
>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146

}
Solution content
    /*
import android.util.Log;

public class UshahidiDatabase {

    private static final String TAG = "UshahidiDatabase";

    public static final String INCIDENT_ID = "_id";

    public static final String INCIDENT_TITLE = "incident_title";

    public static final String INCIDENT_DESC = "incident_desc";

    public static final String INCIDENT_DATE = "incident_date";

    public static final String INCIDENT_MODE = "incident_mode";

    public static final String INCIDENT_VERIFIED = "incident_verified";

    public static final String INCIDENT_LOC_NAME = "incident_loc_name";

    public static final String INCIDENT_LOC_LATITUDE = "incident_loc_latitude";

    public static final String INCIDENT_LOC_LONGITUDE = "incident_loc_longitude";

    public static final String INCIDENT_CATEGORIES = "incident_categories";

    public static final String INCIDENT_MEDIA = "incident_media";

    public static final String INCIDENT_IMAGE = "incident_image";

    public static final String INCIDENT_IS_UNREAD = "is_unread";

    public static final String CATEGORY_ID = "_id";

    public static final String CATEGORY_TITLE = "category_title";

    public static final String CATEGORY_DESC = "category_desc";

    public static final String CATEGORY_COLOR = "category_color";

    public static final String CATEGORY_IS_UNREAD = "is_unread";

    public static final String ADD_INCIDENT_ID = "_id";

    public static final String ADD_INCIDENT_TITLE = "incident_title";

    public static final String ADD_INCIDENT_DESC = "incident_desc";

    public static final String ADD_INCIDENT_DATE = "incident_date";

    public static final String ADD_INCIDENT_HOUR = "incident_hour";

    public static final String ADD_INCIDENT_MINUTE = "incident_minute";

    public static final String ADD_INCIDENT_AMPM = "incident_ampm";

    public static final String ADD_INCIDENT_CATEGORIES = "incident_categories";

    public static final String ADD_INCIDENT_LOC_NAME = "incident_loc_name";

    public static final String ADD_INCIDENT_LOC_LATITUDE = "incident_loc_latitude";

    public static final String ADD_INCIDENT_LOC_LONGITUDE = "incident_loc_longitude";

    public static final String ADD_INCIDENT_PHOTO = "incident_photo";

    public static final String ADD_INCIDENT_VIDEO = "incident_video";

    public static final String ADD_INCIDENT_NEWS = "incident_news";

    public static final String ADD_PERSON_FIRST = "person_first";

    public static final String ADD_PERSON_LAST = "person_last";

    public static final String ADD_PERSON_EMAIL = "person_email";

    public static final String[] INCIDENTS_COLUMNS = new String[] {
            INCIDENT_ID, INCIDENT_TITLE, INCIDENT_DESC, INCIDENT_DATE, INCIDENT_MODE,
            INCIDENT_VERIFIED, INCIDENT_LOC_NAME, INCIDENT_LOC_LATITUDE, INCIDENT_LOC_LONGITUDE,
            INCIDENT_CATEGORIES, INCIDENT_MEDIA, INCIDENT_IMAGE, INCIDENT_IS_UNREAD
    };


            db.execSQL(INCIDENTS_TABLE_CREATE);

        return result;
    }
    public static final String[] CATEGORIES_COLUMNS = new String[] {
            CATEGORY_ID, CATEGORY_TITLE, CATEGORY_DESC, CATEGORY_COLOR, CATEGORY_IS_UNREAD
    };

    public static final String[] ADD_INCIDENTS_COLUMNS = new String[] {
            ADD_INCIDENT_ID, ADD_INCIDENT_TITLE, ADD_INCIDENT_DESC, ADD_INCIDENT_DATE,
            ADD_INCIDENT_HOUR, ADD_INCIDENT_MINUTE, ADD_INCIDENT_AMPM, ADD_INCIDENT_CATEGORIES,
            INCIDENT_LOC_NAME, INCIDENT_LOC_LATITUDE, INCIDENT_LOC_LONGITUDE, ADD_INCIDENT_PHOTO,
            ADD_INCIDENT_VIDEO, ADD_INCIDENT_NEWS, ADD_PERSON_FIRST, ADD_PERSON_LAST,
            ADD_PERSON_EMAIL
    };

    private DatabaseHelper mDbHelper;

    private SQLiteDatabase mDb;

    private static final String DATABASE_NAME = "ushahidi_db";

    private static final String INCIDENTS_TABLE = "incidents";

    private static final String ADD_INCIDENTS_TABLE = "add_incidents";

    private static final String CATEGORIES_TABLE = "categories";

    private static final int DATABASE_VERSION = 10;

    // NOTE: the incident ID is used as the row ID.
    // Furthermore, if a row already exists, an insert will replace
    // the old row upon conflict.

    private static final String INCIDENTS_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS "
            + INCIDENTS_TABLE + " (" + INCIDENT_ID + " INTEGER PRIMARY KEY ON CONFLICT REPLACE, "
            + INCIDENT_TITLE + " TEXT NOT NULL, " + INCIDENT_DESC + " TEXT, " + INCIDENT_DATE
            + " DATE NOT NULL, " + INCIDENT_MODE + " INTEGER, " + INCIDENT_VERIFIED + " INTEGER, "
            + INCIDENT_LOC_NAME + " TEXT NOT NULL, " + INCIDENT_LOC_LATITUDE + " TEXT NOT NULL, "
            + INCIDENT_LOC_LONGITUDE + " TEXT NOT NULL, " + INCIDENT_CATEGORIES
            + " TEXT NOT NULL, " + INCIDENT_MEDIA + " TEXT, " + INCIDENT_IMAGE + " TEXT, "
            + INCIDENT_IS_UNREAD + " BOOLEAN NOT NULL " + ")";

    private static final String ADD_INCIDENTS_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS "
            + ADD_INCIDENTS_TABLE + " (" + ADD_INCIDENT_ID + " INTEGER PRIMARY KEY , "
            + ADD_INCIDENT_TITLE + " TEXT NOT NULL, " + ADD_INCIDENT_DESC + " TEXT, "
            + INCIDENT_DATE + " DATE NOT NULL, " + ADD_INCIDENT_HOUR + " INTEGER, "
            + ADD_INCIDENT_MINUTE + " INTEGER, " + ADD_INCIDENT_AMPM + " TEXT NOT NULL, "
            + ADD_INCIDENT_CATEGORIES + " TEXT NOT NULL, " + ADD_INCIDENT_LOC_NAME
            + " TEXT NOT NULL, " + ADD_INCIDENT_LOC_LATITUDE + " TEXT NOT NULL, "
            + ADD_INCIDENT_LOC_LONGITUDE + " TEXT NOT NULL, " + ADD_INCIDENT_PHOTO + " TEXT, "
            + ADD_INCIDENT_VIDEO + " TEXT, " + ADD_INCIDENT_NEWS + " TEXT, " + ADD_PERSON_FIRST
            + " TEXT, " + ADD_PERSON_LAST + " TEXT, " + ADD_PERSON_EMAIL + " TEXT " + ")";

    private static final String CATEGORIES_TABLE_CREATE = "CREATE TABLE IF NOT EXISTS "
            + CATEGORIES_TABLE + " (" + CATEGORY_ID + " INTEGER PRIMARY KEY ON CONFLICT REPLACE, "
            + CATEGORY_TITLE + " TEXT NOT NULL, " + CATEGORY_DESC + " TEXT, " + CATEGORY_COLOR
            + " TEXT, " + CATEGORY_IS_UNREAD + " BOOLEAN NOT NULL " + ")";

    private final Context mContext;

    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(INCIDENTS_TABLE_CREATE);
            db.execSQL(CATEGORIES_TABLE_CREATE);
            db.execSQL(ADD_INCIDENTS_TABLE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion
                    + " which destroys all old data");
            List incidentsColumns;
            List categoriesColumns;
            List addIncidentColumns;
            // upgrade incident table
            db.execSQL(INCIDENTS_TABLE_CREATE);
            incidentsColumns = UshahidiDatabase.getColumns(db, INCIDENTS_TABLE);
            db.execSQL("ALTER TABLE " + INCIDENTS_TABLE + " RENAME TO temp_" + INCIDENTS_TABLE);
    }
            incidentsColumns.retainAll(UshahidiDatabase.getColumns(db, INCIDENTS_TABLE));
            String cols = UshahidiDatabase.join(incidentsColumns, ",");
            db.execSQL(String.format("INSERT INTO %s (%s) SELECT %s FROM temp_%s", INCIDENTS_TABLE,
                    cols, cols, INCIDENTS_TABLE));
            db.execSQL("DROP TABLE IF EXISTS temp_" + INCIDENTS_TABLE);

            // upgrade category table
            db.execSQL(CATEGORIES_TABLE_CREATE);
            categoriesColumns = UshahidiDatabase.getColumns(db, CATEGORIES_TABLE);
            db.execSQL("ALTER TABLE " + CATEGORIES_TABLE + " RENAME TO temp_" + CATEGORIES_TABLE);
            db.execSQL(CATEGORIES_TABLE_CREATE);
            categoriesColumns.retainAll(UshahidiDatabase.getColumns(db, CATEGORIES_TABLE));
            String catsCols = UshahidiDatabase.join(categoriesColumns, ",");
            db.execSQL(String.format("INSERT INTO %s (%s) SELECT %s FROM temp_%s",
                    CATEGORIES_TABLE, catsCols, catsCols, CATEGORIES_TABLE));
            db.execSQL("DROP TABLE IF EXISTS temp_" + CATEGORIES_TABLE);

            // upgrade add incident table
            db.execSQL(ADD_INCIDENTS_TABLE_CREATE);
            addIncidentColumns = UshahidiDatabase.getColumns(db, ADD_INCIDENTS_TABLE);
            db.execSQL("ALTER TABLE " + ADD_INCIDENTS_TABLE + " RENAME TO temp_"
                    + ADD_INCIDENTS_TABLE);
            db.execSQL(ADD_INCIDENTS_TABLE_CREATE);
            addIncidentColumns.retainAll(UshahidiDatabase.getColumns(db, ADD_INCIDENTS_TABLE));
            String addIncidentCols = UshahidiDatabase.join(addIncidentColumns, ",");
            db.execSQL(String.format("INSERT INTO %s (%s) SELECT %s FROM temp_%s",
                    ADD_INCIDENTS_TABLE, addIncidentCols, addIncidentCols, ADD_INCIDENTS_TABLE));
            db.execSQL("DROP TABLE IF EXISTS temp_" + ADD_INCIDENTS_TABLE);

            onCreate(db);
        }

    }

    /**
     * Credits http://goo.gl/7kOpU
     * 
     * @param db
     * @param tableName
     * @return
     */
    public static List getColumns(SQLiteDatabase db, String tableName) {
        List ar = null;
        Cursor c = null;

        try {
            c = db.rawQuery("SELECT * FROM " + tableName + " LIMIT 1", null);

            if (c != null) {
                ar = new ArrayList(Arrays.asList(c.getColumnNames()));
            }

        } catch (Exception e) {
            Log.v(tableName, e.getMessage(), e);
            e.printStackTrace();
        } finally {
            if (c != null)
                c.close();
        }
        return ar;
    }
    public static String join(List list, String delim) {
        StringBuilder buf = new StringBuilder();
        int num = list.size();
        for (int i = 0; i < num; i++) {
            if (i != 0)
                buf.append(delim);
            buf.append((String)list.get(i));
        }
        return buf.toString();
    }

    public UshahidiDatabase(Context context) {
        this.mContext = context;
    }

    public UshahidiDatabase open() throws SQLException {
        mDbHelper = new DatabaseHelper(mContext);
        mDb = mDbHelper.getWritableDatabase();

        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    public long createIncidents(IncidentsData incidents, boolean isUnread) {
        ContentValues initialValues = new ContentValues();

        initialValues.put(INCIDENT_ID, incidents.getIncidentId());
        initialValues.put(INCIDENT_TITLE, incidents.getIncidentTitle());

        initialValues.put(INCIDENT_DESC, incidents.getIncidentDesc());
        initialValues.put(INCIDENT_DATE, incidents.getIncidentDate());
        initialValues.put(INCIDENT_MODE, incidents.getIncidentMode());
        initialValues.put(INCIDENT_VERIFIED, incidents.getIncidentVerified());
        initialValues.put(INCIDENT_LOC_NAME, incidents.getIncidentLocation());
        initialValues.put(INCIDENT_LOC_LATITUDE, incidents.getIncidentLocLatitude());
        initialValues.put(INCIDENT_LOC_LONGITUDE, incidents.getIncidentLocLongitude());
        initialValues.put(INCIDENT_CATEGORIES, incidents.getIncidentCategories());
        initialValues.put(INCIDENT_MEDIA, incidents.getIncidentThumbnail());

        initialValues.put(INCIDENT_IMAGE, incidents.getIncidentImage());
        initialValues.put(INCIDENT_IS_UNREAD, isUnread);

        return mDb.insert(INCIDENTS_TABLE, null, initialValues);
    }

    public long createAddIncident(AddIncidentData addIncident) {
        ContentValues initialValues = new ContentValues();

        initialValues.put(ADD_INCIDENT_TITLE, addIncident.getIncidentTitle());
        initialValues.put(ADD_INCIDENT_DESC, addIncident.getIncidentDesc());
        initialValues.put(ADD_INCIDENT_DATE, addIncident.getIncidentDate());
        initialValues.put(ADD_INCIDENT_HOUR, addIncident.getIncidentHour());
        initialValues.put(ADD_INCIDENT_MINUTE, addIncident.getIncidentMinute());
        initialValues.put(ADD_INCIDENT_AMPM, addIncident.getIncidentAmPm());
        initialValues.put(ADD_INCIDENT_CATEGORIES, addIncident.getIncidentCategories());
        initialValues.put(INCIDENT_LOC_NAME, addIncident.getIncidentLocName());
        initialValues.put(INCIDENT_LOC_LATITUDE, addIncident.getIncidentLocLatitude());
        initialValues.put(INCIDENT_LOC_LONGITUDE, addIncident.getIncidentLocLongitude());
        initialValues.put(ADD_INCIDENT_PHOTO, addIncident.getIncidentPhoto());
        initialValues.put(ADD_INCIDENT_VIDEO, addIncident.getIncidentVideo());
        initialValues.put(ADD_INCIDENT_NEWS, addIncident.getIncidentNews());
        initialValues.put(ADD_PERSON_FIRST, addIncident.getPersonFirst());
        initialValues.put(ADD_PERSON_LAST, addIncident.getPersonLast());
        initialValues.put(ADD_PERSON_EMAIL, addIncident.getPersonEmail());

        return mDb.insert(ADD_INCIDENTS_TABLE, null, initialValues);
    }

    public long createCategories(CategoriesData categories, boolean isUnread) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(CATEGORY_ID, categories.getCategoryId());
        initialValues.put(CATEGORY_TITLE, categories.getCategoryTitle());
        initialValues.put(CATEGORY_DESC, categories.getCategoryDescription());
        initialValues.put(CATEGORY_COLOR, categories.getCategoryColor());
        initialValues.put(CATEGORY_IS_UNREAD, isUnread);
        return mDb.insert(CATEGORIES_TABLE, null, initialValues);
    }

    public int addNewIncidentsAndCountUnread(ArrayList newIncidents) {
        addIncidents(newIncidents, true);
        return fetchUnreadCount();
    }
    public Cursor fetchAllIncidents() {
        return mDb.query(INCIDENTS_TABLE, INCIDENTS_COLUMNS, null, null, null, null, INCIDENT_DATE
                + " DESC");
    }

    public Cursor fetchAllOfflineIncidents() {
        return mDb.query(ADD_INCIDENTS_TABLE, ADD_INCIDENTS_COLUMNS, null, null, null, null,
                ADD_INCIDENT_ID + " DESC");
    }

    public Cursor fetchAllCategories() {
        return mDb.query(CATEGORIES_TABLE, CATEGORIES_COLUMNS, null, null, null, null, CATEGORY_ID
                + " DESC");
    }

    public Cursor fetchIncidentsByCategories(String filter) {

        String likeFilter = '%' + filter + '%';
        String sql = "SELECT * FROM " + INCIDENTS_TABLE + " WHERE " + INCIDENT_CATEGORIES
                + " LIKE ? ORDER BY " + INCIDENT_TITLE + " COLLATE NOCASE";
        return mDb.rawQuery(sql, new String[] {
            likeFilter
        });
    }

    public Cursor fetchIncidentsById(String id) {
        String sql = "SELECT * FROM " + INCIDENTS_TABLE + " WHERE " + INCIDENT_ID
                + " = ? ORDER BY " + INCIDENT_TITLE + " COLLATE NOCASE";
        return mDb.rawQuery(sql, new String[] {
            id
        });
    }

    public boolean clearData() {

        deleteAllIncidents();
        deleteAllCategories();
        return true;

    }

    public boolean deleteAllIncidents() {
        return mDb.delete(INCIDENTS_TABLE, null, null) > 0;
    }

    public boolean deleteAllCategories() {
        return mDb.delete(CATEGORIES_TABLE, null, null) > 0;
    }

    public boolean deleteCategory(int id) {
        return mDb.delete(CATEGORIES_TABLE, CATEGORY_ID + "=" + id, null) > 0;
    }

    /**
     * Clear the offline table for adding incidents
     * 
     * @return boolean
     */
    public boolean deleteAddIncidents() {
        return mDb.delete(ADD_INCIDENTS_TABLE, null, null) > 0;
    }

    public void markAllIncidentssRead() {
        ContentValues values = new ContentValues();
        values.put(INCIDENT_IS_UNREAD, 0);
        mDb.update(INCIDENTS_TABLE, values, null, null);
    }

    public void markAllCategoriesRead() {
        ContentValues values = new ContentValues();
        values.put(CATEGORY_IS_UNREAD, 0);
        mDb.update(CATEGORIES_TABLE, values, null, null);
    }

    public int fetchMaxId() {
        Cursor mCursor = mDb.rawQuery("SELECT MAX(" + INCIDENT_ID + ") FROM " + INCIDENTS_TABLE,
                null);

        int result = 0;

        if (mCursor == null) {
            return result;
        }

        mCursor.moveToFirst();
        result = mCursor.getInt(0);
        mCursor.close();

        return result;
    }

    public int fetchUnreadCount() {
        Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + INCIDENT_ID + ") FROM " + INCIDENTS_TABLE
                + " WHERE " + INCIDENT_IS_UNREAD + " = 1", null);

        int result = 0;

        if (mCursor == null) {
            return result;
        }

        mCursor.moveToFirst();
        result = mCursor.getInt(0);
        mCursor.close();

        return result;
     * public int fetchMaxCategoryId(boolean isSent) { Cursor mCursor =
     * mDb.rawQuery("SELECT MAX(" + CATEGORY_ID + ") FROM " + CATEGORIES_TABLE +
     * " WHERE " + CATEGORIES_IS_SENT + " = ?", new String[] { isSent ? "1" :
     * "0" }); int result = 0; if (mCursor == null) { return result; }
     * mCursor.moveToFirst(); result = mCursor.getInt(0); mCursor.close();
     * return result; }
     */

    public int addNewCategoryAndCountUnread(List categories) {
        addCategories(categories, true);

        return fetchUnreadCategoriesCount();
    }

    public int fetchCategoriesCount() {
        Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + CATEGORY_ID + ") FROM " + CATEGORIES_TABLE,
                null);

        int result = 0;

        if (mCursor == null) {
            return result;
        }

        mCursor.moveToFirst();
        result = mCursor.getInt(0);
        mCursor.close();

        if (cursor != null && cursor.moveToFirst()) {
    private int fetchUnreadCategoriesCount() {
        Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + CATEGORY_ID + ") FROM " + CATEGORIES_TABLE
                + " WHERE " + CATEGORY_IS_UNREAD + " = 1", null);

        int result = 0;

        if (mCursor == null) {
            return result;
        }

        mCursor.moveToFirst();
        result = mCursor.getInt(0);
        mCursor.close();

        return result;
    }

    public void addIncidents(List incidents, boolean isUnread) {
        try {
            mDb.beginTransaction();

            for (IncidentsData incident : incidents) {
                createIncidents(incident, isUnread);
            }

            limitRows(INCIDENTS_TABLE, Integer.parseInt(UshahidiPref.totalReports), INCIDENT_ID);
            mDb.setTransactionSuccessful();
        } finally {
            mDb.endTransaction();
        }
    }

    /**
     * Adds new incidents to be posted online to the db.
     * 
     * @param List addIncidents
     */
    public long addIncidents(List addIncidents) {
        long rowId = 0;
        try {
            mDb.beginTransaction();
            for (AddIncidentData addIncident : addIncidents) {
                rowId = createAddIncident(addIncident);
            }
            mDb.setTransactionSuccessful();

        } finally {
            mDb.endTransaction();
        }

        return rowId;
    }

    public void addCategories(List categories, boolean isUnread) {
        try {
            mDb.beginTransaction();

            for (CategoriesData category : categories) {
                createCategories(category, isUnread);
            }

            mDb.setTransactionSuccessful();
        } finally {
            mDb.endTransaction();
        }
    }

    public int limitRows(String tablename, int limit, String KEY_ID) {
        Cursor cursor = mDb.rawQuery("SELECT " + KEY_ID + " FROM " + tablename + " ORDER BY "
                + KEY_ID + " DESC LIMIT 1 OFFSET ?", new String[] {
            limit - 1 + ""
        });

        int deleted = 0;

            int limitId = cursor.getInt(0);
            deleted = mDb.delete(tablename, KEY_ID + "<" + limitId, null);
        }

        cursor.close();

        return deleted;
    }

}
File
UshahidiDatabase.java
Developer's decision
Combination
Kind of conflict
Attribute
Class declaration
Comment
Method declaration
Method invocation
Chunk
Conflicting content
            return true;

        } else {
import com.ushahidi.android.app.UshahidiPref;

public class Categories {
<<<<<<< HEAD
	
	public static boolean getAllCategoriesFromWeb() throws IOException {
		
		HttpResponse response;
		String categories = "";
		
		StringBuilder uriBuilder = new StringBuilder( UshahidiPref.domain);
		uriBuilder.append("/api?task=categories");
		uriBuilder.append("&resp=xml");
		
		response = UshahidiHttpClient.GetURL( uriBuilder.toString() );
		
		if( response == null ) {
			return false;
		}
		
		final int statusCode = response.getStatusLine().getStatusCode();
		
		if( statusCode == 200 ) {
			categories = UshahidiHttpClient.GetText(response);
			UshahidiPref.categoriesResponse = categories;
			return true;
			
		} else {
			return false;
		}
		
	}
=======

    public static boolean getAllCategoriesFromWeb() throws IOException {

        HttpResponse response;
        String categories = "";

        StringBuilder uriBuilder = new StringBuilder(UshahidiService.domain);
        uriBuilder.append("/api?task=categories");
        uriBuilder.append("&resp=xml");

        response = UshahidiHttpClient.GetURL(uriBuilder.toString());

        if (response == null) {
            return false;
        }

        final int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == 200) {
            categories = UshahidiHttpClient.GetText(response);
            UshahidiService.categoriesResponse = categories;
            return false;
        }

    }
>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146

}
Solution content
import com.ushahidi.android.app.UshahidiPref;

public class Categories {
	
	public static boolean getAllCategoriesFromWeb() throws IOException {
		
		HttpResponse response;
		String categories = "";
		
		StringBuilder uriBuilder = new StringBuilder( UshahidiPref.domain);
		uriBuilder.append("/api?task=categories");
		uriBuilder.append("&resp=xml");
		
		response = UshahidiHttpClient.GetURL( uriBuilder.toString() );
		
		if( response == null ) {
			return false;
		}
		
		final int statusCode = response.getStatusLine().getStatusCode();
		
		if( statusCode == 200 ) {
			categories = UshahidiHttpClient.GetText(response);
			UshahidiPref.categoriesResponse = categories;
			return true;
			
		} else {
			return false;
		}
		
	}

}
File
Categories.java
Developer's decision
Version 1
Kind of conflict
Method declaration
Chunk
Conflicting content
        uriBuilder.append("&limit=" + UshahidiService.totalReports);
import com.ushahidi.android.app.UshahidiPref;

public class Incidents {
<<<<<<< HEAD
	
	public static boolean getAllIncidentsFromWeb() throws IOException {
		HttpResponse response;
		String incidents = "";
		
		StringBuilder uriBuilder = new StringBuilder( UshahidiPref.domain );
		uriBuilder.append("/api?task=incidents");
		uriBuilder.append("&by=all");
		uriBuilder.append("&limit="+UshahidiPref.totalReports);
		uriBuilder.append("&resp=xml");
		
		response = UshahidiHttpClient.GetURL( uriBuilder.toString());
		
		if( response == null ) {
			return false;
		}
		
		final int statusCode = response.getStatusLine().getStatusCode();
		
		if( statusCode == 200 ) {
			
			incidents = UshahidiHttpClient.GetText(response);
			UshahidiPref.incidentsResponse = incidents;
			return true;
		} else {
			return false;
		}
		
	}
	
=======

    public static boolean getAllIncidentsFromWeb() throws IOException {
        HttpResponse response;
        String incidents = "";

        StringBuilder uriBuilder = new StringBuilder(UshahidiService.domain);
        uriBuilder.append("/api?task=incidents");
        uriBuilder.append("&by=all");
        uriBuilder.append("&resp=xml");

        response = UshahidiHttpClient.GetURL(uriBuilder.toString());

        if (response == null) {
            return false;
        }

        final int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == 200) {

            incidents = UshahidiHttpClient.GetText(response);
            UshahidiService.incidentsResponse = incidents;
            return true;
        } else {
            return false;
        }

    }

>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
}
Solution content
import com.ushahidi.android.app.UshahidiPref;

public class Incidents {

    public static boolean getAllIncidentsFromWeb() throws IOException {
        HttpResponse response;
        String incidents = "";

        StringBuilder uriBuilder = new StringBuilder(UshahidiPref.domain);
        uriBuilder.append("/api?task=incidents");
        uriBuilder.append("&by=all");
        uriBuilder.append("&limit=" + UshahidiPref.totalReports);
        uriBuilder.append("&resp=xml");

        response = UshahidiHttpClient.GetURL(uriBuilder.toString());

        if (response == null) {
            return false;
        }

        final int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == 200) {

            incidents = UshahidiHttpClient.GetText(response);
            UshahidiPref.incidentsResponse = incidents;
            return true;
        } else {
            return false;
        }

    }

}
File
Incidents.java
Developer's decision
Version 1
Kind of conflict
Method declaration
Chunk
Conflicting content
				httpost.addHeader("Referer", Referer);
    final public static List blankNVPS = new ArrayList();

    public static HttpResponse GetURL(String URL) throws IOException {
<<<<<<< HEAD
    	UshahidiPref.httpRunning = true;
		
		try {
			//wrap try around because this constructor can throw Error
			final HttpGet httpget = new HttpGet(URL);
			httpget.addHeader("User-Agent", "Ushahidi-Android/1.0)");

			// Post, check and show the result (not really spectacular, but works):
			HttpResponse response =  UshahidiService.httpclient.execute(httpget);
			UshahidiPref.httpRunning = false;
			
			return response;

		} catch (final Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		UshahidiPref.httpRunning = false;
		return null;
    }
    
	public static HttpResponse PostURL(String URL, List data,
			String Referer) throws IOException {
		UshahidiPref.httpRunning = true;
		//Dipo Fix
    	try {
    		//wrap try around because this constructor can throw Error 
			final HttpPost httpost = new HttpPost(URL);
			//org.apache.http.client.methods.
			if(Referer.length() > 0){
			}
			if(data != null){
				try {
            throws IOException {
					//NEED THIS NOW TO FIX ERROR 417
            // org.apache.http.client.methods.
        ClientHttpRequest req = null;
            // wrap try around because this constructor can throw Error

        try {
            final HttpPost httpost = new HttpPost(URL);
					httpost.getParams().setBooleanParameter( "http.protocol.expect-continue", false ); 
					httpost.setEntity(new UrlEncodedFormEntity(data, HTTP.UTF_8));
				} catch (final UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					UshahidiPref.httpRunning = false;
					return null;
				}
			}
	
			// Post, check and show the result (not really spectacular, but works):
			try {
				HttpResponse response =  UshahidiService.httpclient.execute(httpost);
				UshahidiPref.httpRunning = false;
				return response;
	
			} catch (final Exception e) {
	
			} 
    	}
    	catch (final Exception e) {
    		e.printStackTrace();
    	}
    	
		UshahidiPref.httpRunning = false;
		return null;
	}
	
	public static HttpResponse PostURL(String URL, List data) throws IOException {
		return PostURL(URL, data, "");
	}
	
    public static boolean PostFileUpload(String URL, HashMap params) throws IOException{
        ClientHttpRequest req = null;

        try {
             URL url = new URL(URL);
             req = new ClientHttpRequest(url);
             
             req.setParameter("task", params.get("task"));
             req.setParameter("incident_title", params.get("incident_title"));
             req.setParameter("incident_description", params.get("incident_description"));
             req.setParameter("incident_date",params.get("incident_date"));
             req.setParameter("incident_hour", params.get("incident_hour"));
             req.setParameter("incident_minute", params.get("incident_minute"));
             req.setParameter("incident_ampm", params.get("incident_ampm"));
             req.setParameter("incident_category", params.get("incident_category"));
             req.setParameter("latitude", params.get("latitude"));
             req.setParameter("longitude", params.get("longitude"));
             req.setParameter("location_name", params.get("location_name"));
             req.setParameter("person_first", params.get("person_first"));
             req.setParameter("person_last", params.get("person_last"));
             req.setParameter("person_email", params.get("person_email"));
             Log.i("HTTP Client:", "filename:"+UshahidiPref.savePath + params.get("filename"));
             if( !TextUtils.isEmpty( params.get("filename") ))
             req.setParameter("incident_photo[]", new File(UshahidiPref.savePath + params.get("filename")));
             
             
             InputStream serverInput = req.post();
             
             
             if( Util.extractPayloadJSON(GetText(serverInput)) ){
            	 
            	 return true;
             }
             
=======
        UshahidiService.httpRunning = true;

        try {
            // wrap try around because this constructor can throw Error
            final HttpGet httpget = new HttpGet(URL);
            httpget.addHeader("User-Agent", "Ushahidi-Android/1.0)");

            // Post, check and show the result (not really spectacular, but
            // works):
            HttpResponse response = UshahidiService.httpclient.execute(httpget);
            UshahidiService.httpRunning = false;

            return response;

        } catch (final Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        UshahidiService.httpRunning = false;
        return null;
    }

    public static HttpResponse PostURL(String URL, List data, String Referer)
            throws IOException {
        UshahidiService.httpRunning = true;
        // Dipo Fix
        try {
            if (Referer.length() > 0) {
                httpost.addHeader("Referer", Referer);
            }
            if (data != null) {
                try {
                    // NEED THIS NOW TO FIX ERROR 417
                    httpost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
                    httpost.setEntity(new UrlEncodedFormEntity(data, HTTP.UTF_8));
                } catch (final UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    UshahidiService.httpRunning = false;
                    return null;
                }
            }

            // Post, check and show the result (not really spectacular, but
            // works):
            try {
                HttpResponse response = UshahidiService.httpclient.execute(httpost);
                UshahidiService.httpRunning = false;
                return response;

            } catch (final Exception e) {

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

        UshahidiService.httpRunning = false;
        return null;
    }

    public static HttpResponse PostURL(String URL, List data) throws IOException {
        return PostURL(URL, data, "");
    }

    public static boolean PostFileUpload(String URL, HashMap params)
            URL url = new URL(URL);
            req = new ClientHttpRequest(url);

            req.setParameter("task", params.get("task"));
            req.setParameter("incident_title", params.get("incident_title"));
            req.setParameter("incident_description", params.get("incident_description"));
            req.setParameter("incident_date", params.get("incident_date"));
            req.setParameter("incident_hour", params.get("incident_hour"));
            req.setParameter("incident_minute", params.get("incident_minute"));
            req.setParameter("incident_ampm", params.get("incident_ampm"));
            req.setParameter("incident_category", params.get("incident_category"));
            req.setParameter("latitude", params.get("latitude"));
            req.setParameter("longitude", params.get("longitude"));
            req.setParameter("location_name", params.get("location_name"));
            req.setParameter("person_first", params.get("person_first"));
            req.setParameter("person_last", params.get("person_last"));
            req.setParameter("person_email", params.get("person_email"));
            Log.i("HTTP Client:", "filename:" + UshahidiService.savePath + params.get("filename"));
            if (!TextUtils.isEmpty(params.get("filename")))
                req.setParameter("incident_photo[]",
                        new File(UshahidiService.savePath + params.get("filename")));

            InputStream serverInput = req.post();

            if (Util.extractPayloadJSON(GetText(serverInput))) {

                return true;
            }

>>>>>>> 03d4f8b9be578340f7b439172bec824e9e111146
        } catch (MalformedURLException ex) {
            // fall through and return false
        }
Solution content
            }
            throws IOException {
    final public static List blankNVPS = new ArrayList();

    public static HttpResponse GetURL(String URL) throws IOException {

        UshahidiPref.httpRunning = true;

        try {
            // wrap try around because this constructor can throw Error
            final HttpGet httpget = new HttpGet(URL);
            httpget.addHeader("User-Agent", "Ushahidi-Android/1.0)");

            // Post, check and show the result (not really spectacular, but
            // works):
            HttpResponse response = UshahidiService.httpclient.execute(httpget);
            UshahidiPref.httpRunning = false;

            return response;

        } catch (final Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        UshahidiPref.httpRunning = false;
        return null;
    }

    public static HttpResponse PostURL(String URL, List data, String Referer)
        UshahidiPref.httpRunning = true;
        // Dipo Fix
        try {
            // wrap try around because this constructor can throw Error
            final HttpPost httpost = new HttpPost(URL);
            // org.apache.http.client.methods.
            if (Referer.length() > 0) {
                httpost.addHeader("Referer", Referer);
            }
            if (data != null) {
                try {
                    // NEED THIS NOW TO FIX ERROR 417
                    httpost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
                    httpost.setEntity(new UrlEncodedFormEntity(data, HTTP.UTF_8));
                } catch (final UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    UshahidiPref.httpRunning = false;
                    return null;
                }
            }

            // Post, check and show the result (not really spectacular, but
            // works):
            try {
                HttpResponse response = UshahidiService.httpclient.execute(httpost);
                UshahidiPref.httpRunning = false;
                return response;

            } catch (final Exception e) {

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

        UshahidiPref.httpRunning = false;
        return null;
    }

    public static HttpResponse PostURL(String URL, List data) throws IOException {
        return PostURL(URL, data, "");
    }

    public static boolean PostFileUpload(String URL, HashMap params)
            throws IOException {
        ClientHttpRequest req = null;

        try {
            URL url = new URL(URL);
            req = new ClientHttpRequest(url);

            req.setParameter("task", params.get("task"));
            req.setParameter("incident_title", params.get("incident_title"));
            req.setParameter("incident_description", params.get("incident_description"));
            req.setParameter("incident_date", params.get("incident_date"));
            req.setParameter("incident_hour", params.get("incident_hour"));
            req.setParameter("incident_minute", params.get("incident_minute"));
            req.setParameter("incident_ampm", params.get("incident_ampm"));
            req.setParameter("incident_category", params.get("incident_category"));
            req.setParameter("latitude", params.get("latitude"));
            req.setParameter("longitude", params.get("longitude"));
            req.setParameter("location_name", params.get("location_name"));
            req.setParameter("person_first", params.get("person_first"));
            req.setParameter("person_last", params.get("person_last"));
            req.setParameter("person_email", params.get("person_email"));
            Log.i("HTTP Client:", "filename:" + UshahidiPref.savePath + params.get("filename"));
            if (!TextUtils.isEmpty(params.get("filename")))
                req.setParameter("incident_photo[]",
                        new File(UshahidiPref.savePath + params.get("filename")));

            InputStream serverInput = req.post();

            if (Util.extractPayloadJSON(GetText(serverInput))) {

                return true;
            }

        } catch (MalformedURLException ex) {
            // fall through and return false
        }
File
UshahidiHttpClient.java
Developer's decision
Manual
Kind of conflict
If statement
Method declaration
Method invocation
Method signature
Return statement
Try statement
Variable