• Pancho
  • NEWBIE
  • 0 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 10
    Questions
  • 18
    Replies

All of the queries on the sample apps have no Where clauses.  I need to put in a Where clause that limits the query to ownerId= the current user id.

I'm not sure how to capture the current UserId and what that would look like.

 

Here is what I have tried.

 

I edited this function in angular-force.js

            function salesforceSessionRefreshed(creds) {
                // Depending on how we come into this method, `creds` may be callback data from the auth
                // plugin, or an event fired from the plugin.  The data is different between the two.
                var credsData = creds;
                if (creds.data)  // Event sets the `data` object with the auth data.
                    credsData = creds.data;

                SFConfig.client = new forcetk.Client(credsData.clientId, credsData.loginUrl);
                SFConfig.client.setSessionToken(credsData.accessToken, apiVersion, credsData.instanceUrl);
                SFConfig.client.setRefreshToken(credsData.refreshToken);

                //added to get UserID
                var userId = credsData.userId;

                //Set sessionID to angularForce coz profileImages need them
                self.sessionId = SFConfig.client.sessionId;

                callback && callback();
            }

 And then I edited app.js with this where clause, on a custom object.

angular.module('Store', []).factory('Store', function (AngularForceObjectFactory) {
    //Describe the store object
    var objDesc = {
        type: 'Retail_Store__c',
        fields: ['Retailer_Store_Type__c', 'Account_Related_to__r.Name', 'Address_1__c', 'City__c', 'State__c', 'Phone__c',
            'Field_Team_Tier__c', 'Lat__c', 'Long__c', 'Location_Note__c', 'Id'],
        where: 'ownerId='+userId,
        orderBy: 'Account_Related_to__c',
        limit: 20
    };
    var Store = AngularForceObjectFactory(objDesc);

    return Store;
});

 Any Ideas?  Any help is appreciated.

 

  • August 28, 2013
  • Like
  • 0

Hi,

The Force.com REST API Developer Guide says this is how to download attachement content (on p. 40).

 

https://na1.salesforce.com/services/data/v20.0/sobjects/Attachment/001D000000INjVe/body -H "Authorization: Bearer token"

 

In my Android App I am getting an invalid session ID.  Any ideas?

 

 

 

I use the REST api to grab the "Body" of the attachmment so I have the URL for the BLOB,

bodyURL = records.getJSONObject(i).getString("Body").toString();

Then I create my URL

 

imageUrl=client.getClientInfo().instanceUrl+bodyURL+" -H "+'"'+"Authorization: Bearer "+client.getAuthToken()+'"';

 

Then I try and open the URL and stream it down to put into an ImageView.

URL networkUrl = imageUrl;

try { InputStream in = networkUrl.openConnection().getInputStream(); BufferedInputStream bis = new BufferedInputStream(in,1024*8); ByteArrayOutputStream out = new ByteArrayOutputStream(); int len=0; byte[] buffer = new byte[1024]; while((len = bis.read(buffer)) != -1){ out.write(buffer, 0, len); } out.close(); bis.close(); data = Base64.decode(out.toByteArray(), Base64.DEFAULT); //data = out.toByteArray(); networkBitmap = BitmapFactory.decodeByteArray(data, 0, data.length); } catch (IOException e) { e.printStackTrace(); }

....
	    ImageView img = (ImageView) findViewById(R.id.imageViewStore);
	    img.setImageBitmap(networkBitmap);

 

 

 

Hi Guys,

I am new to writing triggers.

I have an object called Store_Visits__c and one called Field_Check_In__c.

In the case that there exists a Field_Check_In__c with the same Owner, Date and StoreID as a Store_Visit__c Owner, Date and StoreID, i want to set Store_Visit.Related_Check_In to the Check_In__c.id.

 

Here is what I have so far:

trigger CheckInTrigger on Store_visit__c (after insert, after update) {

//Find all Field_Check_Ins where owner,date, and storeId matches Store_visit__c owner, date and storeId
List<Field_Check_In__c> cis = [SELECT Id FROM Field_Check_In__c WHERE (CheckIn_Date__c IN : Trigger.new.Actual_Date_of_Visit__c ) AND ( Retail_Store__c IN : Trigger.new.Retail_Store_Visited_del__c ) AND (Owner IN : Trigger.new.Owner)];
	
//Loop through related CheckIns and set Store_visit__c.
    	 for ( Field_Check_In__c c: cis){
				Trigger.new.Related_Field_Check_In__c = c.Id;
				update c;
    	 	}
}

 The error I am getting is "Initial term of field expression must be concrete SObject: List<Store_visit__c>

 

Any ideas?

 

 

Hi Everyone,

I have an app that uploads and downloads jpeg pictures as attachements to custom salesforce.com objects.

The uploading and storing seems to work fine.

Even the downloading seems to work fine, but for some reason my pictures are coming up black in my Android ImageView.

 

I am converting to and from Base64.

Also my file sizes of these pics are relatively small.  Height 100dp and Width 178dp.  Filesize about 14k.

Below is a sample test activity that I created which has the same issue, but less code to look at.

Any help is greatly appreciated.

 

Thanks!

 

import java.io.UnsupportedEncodingException;
import org.json.JSONArray;
import com.salesforce.androidsdk.app.ForceApp;
import com.salesforce.androidsdk.rest.ClientManager.LoginOptions;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.ui.NativeMainActivity;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class ImageTest extends NativeMainActivity {
	
	private RestClient client;
	ProgressDialog progressBar;
	int numPics=0;
	String rName="";
	Bitmap bitmap=null;
	Bitmap bitmapTest=null;
	private byte[] buffer=null;
	public static final String IMAGE_STORE = "StorePic";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_image_test);
	}

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

	@Override
	protected LoginOptions getLoginOptions() {
    	LoginOptions loginOptions = new LoginOptions(
    			null, // login host is chosen by user through the server picker 
    			ForceApp.APP.getPasscodeHash(),
    			getString(R.string.oauth_callback_url),
    			getString(R.string.oauth_client_id),
    			new String[] {"api"});
    	return loginOptions;
	}

	@Override
	protected void onResume(RestClient client) {
        this.client = client; 
		// Show everything
        findViewById(R.id.image_page).setVisibility(View.VISIBLE);		
        try {
			startLoadPicInfo();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} //end on resume	
    
    protected void startLoadPicInfo() throws UnsupportedEncodingException {

	    String sfRequest = "SELECT Name, Id, Body, ParentId, BodyLength FROM Attachment "+
	    		"WHERE (ParentId='a1R50000000I95M') AND (Name='StorePic.jpg') ORDER BY CREATEDDATE DESC LIMIT 1";
			try {
				sendPicRequest(sfRequest);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    }	
	
	private void sendPicRequest(String soql) throws UnsupportedEncodingException {
		RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), soql);
		client.sendAsync(restRequest, new AsyncRequestCallback() {
			@Override
			public void onSuccess(RestRequest request, RestResponse result) {
				try {
					JSONArray records = result.asJSONObject().getJSONArray("records");
					numPics=records.length();
					if (records.length()>0) {
						for (int i = 0; i < records.length(); i++) {
							buffer = Base64.decode(records.getJSONObject(i).getString("Body").getBytes(), Base64.DEFAULT);
							bitmapTest = BitmapFactory.decodeByteArray(buffer , 0, buffer.length);
							records.getJSONObject(i).getString("Name");
							}   //end for loop - loading results
				 	 }  //end if
					} catch (Exception e) {
						onError(e);
						e.printStackTrace();
					}
					
					if (numPics>0) {		     
			        ImageView sPic = (ImageView)findViewById(R.id.imageView1);
					sPic.setImageBitmap(bitmapTest);
					sPic.bringToFront();
					}
			}
			
			@Override
			public void onError(Exception exception) {
                Toast.makeText(ImageTest.this,
                               ImageTest.this.getString(ForceApp.APP.getSalesforceR().stringGenericError(), exception.toString()),
                               Toast.LENGTH_LONG).show();
			}
		});
	}  //end sendPicRequest()   
}  //end ImageTest

 Here is the activity_image_test.xml

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:id="@+id/image_page"
    tools:context=".ImageTest" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ab_solid_example" />

</RelativeLayout>

 

I have an Andoid app that performs multiple salesforce queries to update one screen in an activity.  I am running into a refresh problem with the screen because all of these Salesforce queries are each an asynctask.  I tried putting all of the salesforce calls into a master asynch task so I could use post execute, but that didnt work.  I read about Android loaders here, http://developer.android.com/guide/components/loaders.html   Has anyone used loaders to fix this issue, or is there a different way I can address the issue?  I need to know when all of the salesforce queries are complete so I can refresh the screen.

 

Thanks for your help. =o)

 

Hi everyone,

The template app that comes with the SalesforceSDK is great, but it only has a few examples of SELECT querys.

Can someone show me how to do a INSERT/UPSERT using the native Android SalesforceSDK?

I need to insert records into some custom objects, including a datetime field.  I am not sure how to package it up and put it into a format to allow SOQL to INSERT or UPSERT.

 

Thanks mucho

any help is appreciated.

Hi Everyone,

I know its so easy in APEX code, but I am writing a native Android Java app, and I want to do a query that returns a custom object (Retail_Stores) where the current user is the owner of that object.  I am not sure how to reference the current user or get his id.  Any help is greatly appreciated.  Here is what my current query looks like.

String sfRequest = "SELECT Name, Id, Lat__c, Long__c, Address_1__c, City__c, State__c, Phone__c, Retailer_Store_Type__c, Field_Team_Tier__c FROM Retail_Store__c  WHERE (Retail_Store__c.Owner= :UserInfo.getUserId())  LIMIT "+maxNumStores;

 

Thanks for your consideration and help.

Hi,

I have downloaded and installed the new ADT bundle from Google.

http://developer.android.com/sdk/index.html 

 

I have followed the install directions here:

http://wiki.developerforce.com/page/Getting_Started_with_the_Mobile_SDK_for_Android 

 

There are no errors in the development environment, but when I run the project, I get this error in LogCat:

 

Could not find class 'com.salesforce.androidsdk.ui.SalesforceDroidGapActivity', referenced from method com.salesforce.androidsdk.app.ForceApp.isHybrid

 

I see that class listed under SaleforceSDK/src, which is part of my project.

Any help is greatly appreciated.

 

 

Hi,

I am moving this APEX code over to a JAVA app, and my query is not working.  

Any help is greatly appreciated.

Any ideas?

 

APEX Code:

List<String> zips = new List<String>();

//loaded up the list then I execute this query 

List<Zip_Code_Master__c> zipList= [select name, id, Related_Metro_Area__r.id from Zip_Code_Master__c where name =:zips];

 

 

JAVA Code:

String[] zips = new String[MaxRows];

//loaded up the list then I execute this query

QueryResult queryResults = connection.query("select name, id, Related_Metro_Area__r.id from Zip_Code_Master__c where name IN : zips");

 

JAVA Error:

[MalformedQueryFault [ApiQueryFault [ApiFault exceptionCode='MALFORMED_QUERY'
exceptionMessage='
Zip_Code_Master__c where name IN : zips
^
ERROR at Row:1:Column:80
unexpected token: ':' (Bind variables only allowed in Apex code)'
]
row='1'
column='80'
]

Hi everyone,

Any help with this problem would be greatly appreciated.  I am currently trying to do a custom CSV import in order to automate the process of importing a CSV every day.  I have a VisualForce page that accepts the filename of the CSV file and calls my apex class to do the upload. (both are below) The CSV parser is working fine, after testing.  The problem I am having is with grabbing the related object ids for the import.  The error I am getting is "System.ListException: List index out of bounds: 17

Error is in expression '{!ReadFile}' in page fotaupload Class.FOTAuploader.ReadFile: line 116, column 1"

 

I think my problem is around the section with the comment "//create a list of the related zip code ids"

 

About my objects:

I have a zip code object that is a related list to my Activations object.

 

 

***********************************************************

FOTAuploader.cls

 

 

 

public with sharing class FOTAuploader {

 

    public string nameFile{get;set;}

    public Blob contentFile{get;set;}

    public Integer rowCount{get;set;}

    public Integer colCount{get;set;}

    List<Activations__c> actvstoupload;

    public Zip_Code_Master__c tempZip;

   

 

// taken from stackoverflow.com/questions/10425925/how-to-parse-a-csv-in-salesforce

    public static List<List<String>> parseCSV(String contents,Boolean skipHeaders) {

List<List<String>> allFields = new List<List<String>>();

 

// replace instances where a double quote begins a field containing a comma

// in this case you get a double quote followed by a doubled double quote

// do this for beginning and end of a field

contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');

// now replace all remaining double quotes - we do this so that we can reconstruct

// fields with commas inside assuming they begin and end with a double quote

contents = contents.replaceAll('""','DBLQT');

// we are not attempting to handle fields with a newline inside of them

// so, split on newline to get the spreadsheet rows

List<String> lines = new List<String>();

try {

lines = contents.split('\n');

} catch (System.ListException e) {

System.debug('Limits exceeded?' + e.getMessage());

}

Integer num = 0;

for(String line : lines) {

// check for blank CSV lines (only commas)

if (line.replaceAll(',','').trim().length() == 0) break;

 

List<String> fields = line.split(',');        

List<String> cleanFields = new List<String>();

String compositeField;

Boolean makeCompositeField = false;

for(String field : fields) {

if (field.startsWith('"') && field.endsWith('"')) {

cleanFields.add(field.replaceAll('DBLQT','"'));

} else if (field.startsWith('"')) {

makeCompositeField = true;

compositeField = field;

} else if (field.endsWith('"')) {

compositeField += ',' + field;

cleanFields.add(compositeField.replaceAll('DBLQT','"'));

makeCompositeField = false;

} else if (makeCompositeField) {

compositeField +=  ',' + field;

} else {

cleanFields.add(field.replaceAll('DBLQT','"'));

}

}

 

allFields.add(cleanFields);

}

if (skipHeaders) allFields.remove(0);

return allFields;                

}

 

 

   

    public Pagereference ReadFile()

    {                  

            //create a restore point incase the upload fails it can back out everything.

            Savepoint sp = Database.setSavepoint();

            

        actvstoupload = new List<Activations__c>();      

        List<List<String>> parsedCSV = new List<List<String>>();

        List<String> zips = new List<String>();

       

        //fill up the parsedCSV table

        rowCount = 0;

        colCount = 0;

        if (contentFile != null){

            String fileString = contentFile.toString();

            parsedCSV = parseCSV(fileString, false);

            rowCount = parsedCSV.size();

            for (List<String> row : parsedCSV){

                if (row.size() > colCount){

                    colCount = row.size();

                }

            }

         }

        

      //create a list of the related zip code ids

 

        for (Integer i=1;i<parsedCSV.size();i++)

        {

        zips[i] = parsedCSV[i][6].replaceAll('\"','');

        }

        List<Zip_Code_Master__c> zipList= [select id from Zip_Code_Master__c where name =:zips];

       

       

       

        for (Integer i=1;i<parsedCSV.size();i++)

        {

           

            Activations__c a = new Activations__c();

           

            a.Zip_Code_of_Activation__c = zipList[i].id;

           

           //process quantity field

            a.ActQty__c = Double.valueOf(parsedCSV[i][18].replaceAll('\"',''));    

 

                

                     //process date field  -- filter out the hour and minutes from the Date field.

                     Date dT = date.parse(parsedCSV[i][0].replaceAll('\"','').trim().substringBefore(' '));

            a.Date_entry__c = dT;  //get date from visualforce page 

 

 

            actvstoupload.add(a);

        }

        try{

        insert actvstoupload;

        }

        catch (Exception e)

        {

            Database.rollback(sp);

            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later');

            ApexPages.addMessage(errormsg);

        }   

        return null;

    }

   

    public List<Activations__c> getuploadedActivations()

    {

        if (actvstoupload!= NULL)

            if (actvstoupload.size() > 0)

                return actvstoupload;

            else

                return null;                   

        else

            return null;

    }           

}

 

**********************************************************************************

 

FOTAupload.page

 

<apex:page sidebar="false" controller="FOTAuploader">
<apex:form >
<apex:sectionHeader title="Upload FOTA data from CSV file"/>
<apex:pagemessages />
<apex:pageBlock >
<center>
<apex:inputFile value="{!contentFile}" filename="{!nameFile}" /> <apex:commandButton action="{!ReadFile}" value="Upload File" id="theButton" style="width:70px;"/>
<br/> <br/> <font color="red"> <b>Note: Please use the standard .CSV file from the Retail Activations Portal. </b> </font>
</center>


<apex:pageblocktable value="{!uploadedActivations}" var="actv" rendered="{!NOT(ISNULL(uploadedActivations))}">
<apex:column headerValue="Actv Date">
<apex:outputField value="{!actv.Date_entry__c}"/>
</apex:column>
<apex:column headerValue="Zip">
<apex:outputField value="{!actv.Zip_Code_of_Activation__c}"/>
</apex:column>
<apex:column headerValue="Qty">
<apex:outputField value="{!actv.ActQty__c}"/>
</apex:column>
<apex:column headerValue="City-State">
<apex:outputField value="{!actv.City_State_Concatenation__c}"/>
</apex:column>
</apex:pageblocktable>

</apex:pageBlock>
</apex:form>
</apex:page>

 

All of the queries on the sample apps have no Where clauses.  I need to put in a Where clause that limits the query to ownerId= the current user id.

I'm not sure how to capture the current UserId and what that would look like.

 

Here is what I have tried.

 

I edited this function in angular-force.js

            function salesforceSessionRefreshed(creds) {
                // Depending on how we come into this method, `creds` may be callback data from the auth
                // plugin, or an event fired from the plugin.  The data is different between the two.
                var credsData = creds;
                if (creds.data)  // Event sets the `data` object with the auth data.
                    credsData = creds.data;

                SFConfig.client = new forcetk.Client(credsData.clientId, credsData.loginUrl);
                SFConfig.client.setSessionToken(credsData.accessToken, apiVersion, credsData.instanceUrl);
                SFConfig.client.setRefreshToken(credsData.refreshToken);

                //added to get UserID
                var userId = credsData.userId;

                //Set sessionID to angularForce coz profileImages need them
                self.sessionId = SFConfig.client.sessionId;

                callback && callback();
            }

 And then I edited app.js with this where clause, on a custom object.

angular.module('Store', []).factory('Store', function (AngularForceObjectFactory) {
    //Describe the store object
    var objDesc = {
        type: 'Retail_Store__c',
        fields: ['Retailer_Store_Type__c', 'Account_Related_to__r.Name', 'Address_1__c', 'City__c', 'State__c', 'Phone__c',
            'Field_Team_Tier__c', 'Lat__c', 'Long__c', 'Location_Note__c', 'Id'],
        where: 'ownerId='+userId,
        orderBy: 'Account_Related_to__c',
        limit: 20
    };
    var Store = AngularForceObjectFactory(objDesc);

    return Store;
});

 Any Ideas?  Any help is appreciated.

 

  • August 28, 2013
  • Like
  • 0

Hi Guys,

I am new to writing triggers.

I have an object called Store_Visits__c and one called Field_Check_In__c.

In the case that there exists a Field_Check_In__c with the same Owner, Date and StoreID as a Store_Visit__c Owner, Date and StoreID, i want to set Store_Visit.Related_Check_In to the Check_In__c.id.

 

Here is what I have so far:

trigger CheckInTrigger on Store_visit__c (after insert, after update) {

//Find all Field_Check_Ins where owner,date, and storeId matches Store_visit__c owner, date and storeId
List<Field_Check_In__c> cis = [SELECT Id FROM Field_Check_In__c WHERE (CheckIn_Date__c IN : Trigger.new.Actual_Date_of_Visit__c ) AND ( Retail_Store__c IN : Trigger.new.Retail_Store_Visited_del__c ) AND (Owner IN : Trigger.new.Owner)];
	
//Loop through related CheckIns and set Store_visit__c.
    	 for ( Field_Check_In__c c: cis){
				Trigger.new.Related_Field_Check_In__c = c.Id;
				update c;
    	 	}
}

 The error I am getting is "Initial term of field expression must be concrete SObject: List<Store_visit__c>

 

Any ideas?

 

 

Hi Everyone,

I have an app that uploads and downloads jpeg pictures as attachements to custom salesforce.com objects.

The uploading and storing seems to work fine.

Even the downloading seems to work fine, but for some reason my pictures are coming up black in my Android ImageView.

 

I am converting to and from Base64.

Also my file sizes of these pics are relatively small.  Height 100dp and Width 178dp.  Filesize about 14k.

Below is a sample test activity that I created which has the same issue, but less code to look at.

Any help is greatly appreciated.

 

Thanks!

 

import java.io.UnsupportedEncodingException;
import org.json.JSONArray;
import com.salesforce.androidsdk.app.ForceApp;
import com.salesforce.androidsdk.rest.ClientManager.LoginOptions;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.ui.NativeMainActivity;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class ImageTest extends NativeMainActivity {
	
	private RestClient client;
	ProgressDialog progressBar;
	int numPics=0;
	String rName="";
	Bitmap bitmap=null;
	Bitmap bitmapTest=null;
	private byte[] buffer=null;
	public static final String IMAGE_STORE = "StorePic";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_image_test);
	}

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

	@Override
	protected LoginOptions getLoginOptions() {
    	LoginOptions loginOptions = new LoginOptions(
    			null, // login host is chosen by user through the server picker 
    			ForceApp.APP.getPasscodeHash(),
    			getString(R.string.oauth_callback_url),
    			getString(R.string.oauth_client_id),
    			new String[] {"api"});
    	return loginOptions;
	}

	@Override
	protected void onResume(RestClient client) {
        this.client = client; 
		// Show everything
        findViewById(R.id.image_page).setVisibility(View.VISIBLE);		
        try {
			startLoadPicInfo();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} //end on resume	
    
    protected void startLoadPicInfo() throws UnsupportedEncodingException {

	    String sfRequest = "SELECT Name, Id, Body, ParentId, BodyLength FROM Attachment "+
	    		"WHERE (ParentId='a1R50000000I95M') AND (Name='StorePic.jpg') ORDER BY CREATEDDATE DESC LIMIT 1";
			try {
				sendPicRequest(sfRequest);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    }	
	
	private void sendPicRequest(String soql) throws UnsupportedEncodingException {
		RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), soql);
		client.sendAsync(restRequest, new AsyncRequestCallback() {
			@Override
			public void onSuccess(RestRequest request, RestResponse result) {
				try {
					JSONArray records = result.asJSONObject().getJSONArray("records");
					numPics=records.length();
					if (records.length()>0) {
						for (int i = 0; i < records.length(); i++) {
							buffer = Base64.decode(records.getJSONObject(i).getString("Body").getBytes(), Base64.DEFAULT);
							bitmapTest = BitmapFactory.decodeByteArray(buffer , 0, buffer.length);
							records.getJSONObject(i).getString("Name");
							}   //end for loop - loading results
				 	 }  //end if
					} catch (Exception e) {
						onError(e);
						e.printStackTrace();
					}
					
					if (numPics>0) {		     
			        ImageView sPic = (ImageView)findViewById(R.id.imageView1);
					sPic.setImageBitmap(bitmapTest);
					sPic.bringToFront();
					}
			}
			
			@Override
			public void onError(Exception exception) {
                Toast.makeText(ImageTest.this,
                               ImageTest.this.getString(ForceApp.APP.getSalesforceR().stringGenericError(), exception.toString()),
                               Toast.LENGTH_LONG).show();
			}
		});
	}  //end sendPicRequest()   
}  //end ImageTest

 Here is the activity_image_test.xml

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:id="@+id/image_page"
    tools:context=".ImageTest" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ab_solid_example" />

</RelativeLayout>

 

I have an Andoid app that performs multiple salesforce queries to update one screen in an activity.  I am running into a refresh problem with the screen because all of these Salesforce queries are each an asynctask.  I tried putting all of the salesforce calls into a master asynch task so I could use post execute, but that didnt work.  I read about Android loaders here, http://developer.android.com/guide/components/loaders.html   Has anyone used loaders to fix this issue, or is there a different way I can address the issue?  I need to know when all of the salesforce queries are complete so I can refresh the screen.

 

Thanks for your help. =o)

 

Hi everyone,

The template app that comes with the SalesforceSDK is great, but it only has a few examples of SELECT querys.

Can someone show me how to do a INSERT/UPSERT using the native Android SalesforceSDK?

I need to insert records into some custom objects, including a datetime field.  I am not sure how to package it up and put it into a format to allow SOQL to INSERT or UPSERT.

 

Thanks mucho

any help is appreciated.

Hi Everyone,

I know its so easy in APEX code, but I am writing a native Android Java app, and I want to do a query that returns a custom object (Retail_Stores) where the current user is the owner of that object.  I am not sure how to reference the current user or get his id.  Any help is greatly appreciated.  Here is what my current query looks like.

String sfRequest = "SELECT Name, Id, Lat__c, Long__c, Address_1__c, City__c, State__c, Phone__c, Retailer_Store_Type__c, Field_Team_Tier__c FROM Retail_Store__c  WHERE (Retail_Store__c.Owner= :UserInfo.getUserId())  LIMIT "+maxNumStores;

 

Thanks for your consideration and help.

Hi,

I have downloaded and installed the new ADT bundle from Google.

http://developer.android.com/sdk/index.html 

 

I have followed the install directions here:

http://wiki.developerforce.com/page/Getting_Started_with_the_Mobile_SDK_for_Android 

 

There are no errors in the development environment, but when I run the project, I get this error in LogCat:

 

Could not find class 'com.salesforce.androidsdk.ui.SalesforceDroidGapActivity', referenced from method com.salesforce.androidsdk.app.ForceApp.isHybrid

 

I see that class listed under SaleforceSDK/src, which is part of my project.

Any help is greatly appreciated.

 

 

Hi,

 

Im having trouble importing the SalesforceSDK Project. After it is imported errors appear in:

 

/SalesforceSDK/src/com/salesforce/androidsdk/ui/OAuthWebviewHelper.java

and

/SalesforceSDK/src/com/salesforce/androidsdk/ui/SalesforceR.java

 

saying:

 

"The import com.salesforce.androidsdk.R cannot be resolved".

 

So the R.java is missing, but how can I get it generated?

 

I followed the instructions from the Getting Started Page. http://wiki.developerforce.com/page/Getting_Started_with_the_Mobile_SDK_for_Android

Can someone thell me how to fix this problem?

 

Thanks!

 

 

  • May 27, 2013
  • Like
  • 0

trying using sample native apps, getting this error on every app:

 

 

Caused by: java.lang.ClassNotFoundException: Didn't find class "com.salesforce.androidsdk.sample.CloudTunesApp" on path: /data/app/com.salesforce.androidsdk.sample-1.apk

 

Any idea, what causing it ?

Hi everyone,

Any help with this problem would be greatly appreciated.  I am currently trying to do a custom CSV import in order to automate the process of importing a CSV every day.  I have a VisualForce page that accepts the filename of the CSV file and calls my apex class to do the upload. (both are below) The CSV parser is working fine, after testing.  The problem I am having is with grabbing the related object ids for the import.  The error I am getting is "System.ListException: List index out of bounds: 17

Error is in expression '{!ReadFile}' in page fotaupload Class.FOTAuploader.ReadFile: line 116, column 1"

 

I think my problem is around the section with the comment "//create a list of the related zip code ids"

 

About my objects:

I have a zip code object that is a related list to my Activations object.

 

 

***********************************************************

FOTAuploader.cls

 

 

 

public with sharing class FOTAuploader {

 

    public string nameFile{get;set;}

    public Blob contentFile{get;set;}

    public Integer rowCount{get;set;}

    public Integer colCount{get;set;}

    List<Activations__c> actvstoupload;

    public Zip_Code_Master__c tempZip;

   

 

// taken from stackoverflow.com/questions/10425925/how-to-parse-a-csv-in-salesforce

    public static List<List<String>> parseCSV(String contents,Boolean skipHeaders) {

List<List<String>> allFields = new List<List<String>>();

 

// replace instances where a double quote begins a field containing a comma

// in this case you get a double quote followed by a doubled double quote

// do this for beginning and end of a field

contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');

// now replace all remaining double quotes - we do this so that we can reconstruct

// fields with commas inside assuming they begin and end with a double quote

contents = contents.replaceAll('""','DBLQT');

// we are not attempting to handle fields with a newline inside of them

// so, split on newline to get the spreadsheet rows

List<String> lines = new List<String>();

try {

lines = contents.split('\n');

} catch (System.ListException e) {

System.debug('Limits exceeded?' + e.getMessage());

}

Integer num = 0;

for(String line : lines) {

// check for blank CSV lines (only commas)

if (line.replaceAll(',','').trim().length() == 0) break;

 

List<String> fields = line.split(',');        

List<String> cleanFields = new List<String>();

String compositeField;

Boolean makeCompositeField = false;

for(String field : fields) {

if (field.startsWith('"') && field.endsWith('"')) {

cleanFields.add(field.replaceAll('DBLQT','"'));

} else if (field.startsWith('"')) {

makeCompositeField = true;

compositeField = field;

} else if (field.endsWith('"')) {

compositeField += ',' + field;

cleanFields.add(compositeField.replaceAll('DBLQT','"'));

makeCompositeField = false;

} else if (makeCompositeField) {

compositeField +=  ',' + field;

} else {

cleanFields.add(field.replaceAll('DBLQT','"'));

}

}

 

allFields.add(cleanFields);

}

if (skipHeaders) allFields.remove(0);

return allFields;                

}

 

 

   

    public Pagereference ReadFile()

    {                  

            //create a restore point incase the upload fails it can back out everything.

            Savepoint sp = Database.setSavepoint();

            

        actvstoupload = new List<Activations__c>();      

        List<List<String>> parsedCSV = new List<List<String>>();

        List<String> zips = new List<String>();

       

        //fill up the parsedCSV table

        rowCount = 0;

        colCount = 0;

        if (contentFile != null){

            String fileString = contentFile.toString();

            parsedCSV = parseCSV(fileString, false);

            rowCount = parsedCSV.size();

            for (List<String> row : parsedCSV){

                if (row.size() > colCount){

                    colCount = row.size();

                }

            }

         }

        

      //create a list of the related zip code ids

 

        for (Integer i=1;i<parsedCSV.size();i++)

        {

        zips[i] = parsedCSV[i][6].replaceAll('\"','');

        }

        List<Zip_Code_Master__c> zipList= [select id from Zip_Code_Master__c where name =:zips];

       

       

       

        for (Integer i=1;i<parsedCSV.size();i++)

        {

           

            Activations__c a = new Activations__c();

           

            a.Zip_Code_of_Activation__c = zipList[i].id;

           

           //process quantity field

            a.ActQty__c = Double.valueOf(parsedCSV[i][18].replaceAll('\"',''));    

 

                

                     //process date field  -- filter out the hour and minutes from the Date field.

                     Date dT = date.parse(parsedCSV[i][0].replaceAll('\"','').trim().substringBefore(' '));

            a.Date_entry__c = dT;  //get date from visualforce page 

 

 

            actvstoupload.add(a);

        }

        try{

        insert actvstoupload;

        }

        catch (Exception e)

        {

            Database.rollback(sp);

            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later');

            ApexPages.addMessage(errormsg);

        }   

        return null;

    }

   

    public List<Activations__c> getuploadedActivations()

    {

        if (actvstoupload!= NULL)

            if (actvstoupload.size() > 0)

                return actvstoupload;

            else

                return null;                   

        else

            return null;

    }           

}

 

**********************************************************************************

 

FOTAupload.page

 

<apex:page sidebar="false" controller="FOTAuploader">
<apex:form >
<apex:sectionHeader title="Upload FOTA data from CSV file"/>
<apex:pagemessages />
<apex:pageBlock >
<center>
<apex:inputFile value="{!contentFile}" filename="{!nameFile}" /> <apex:commandButton action="{!ReadFile}" value="Upload File" id="theButton" style="width:70px;"/>
<br/> <br/> <font color="red"> <b>Note: Please use the standard .CSV file from the Retail Activations Portal. </b> </font>
</center>


<apex:pageblocktable value="{!uploadedActivations}" var="actv" rendered="{!NOT(ISNULL(uploadedActivations))}">
<apex:column headerValue="Actv Date">
<apex:outputField value="{!actv.Date_entry__c}"/>
</apex:column>
<apex:column headerValue="Zip">
<apex:outputField value="{!actv.Zip_Code_of_Activation__c}"/>
</apex:column>
<apex:column headerValue="Qty">
<apex:outputField value="{!actv.ActQty__c}"/>
</apex:column>
<apex:column headerValue="City-State">
<apex:outputField value="{!actv.City_State_Concatenation__c}"/>
</apex:column>
</apex:pageblocktable>

</apex:pageBlock>
</apex:form>
</apex:page>

 

Hi all,

 

I have a set of Customer IDs in dataSet variable, I want to build a SOQL with an 'IN' filter in the WHERE clause...but it's not compiling:

 

List<Account> AccIds = [SELECT Id FROM Account WHERE AccountNumber IN =: dataForUpdate];

 

Any idea of what is going on?

 

Greetings, 

 

MGA.

Hi, 

 

I am having trouble getting this query working in a batchable class. 

 

In my start method when I use the following query : 

 

 

String query = 'Select a.Id, a.Name, a.OwnerId ,(Select Id, OwnerId From Contacts) from Account a Where a.Type IN: '+ accTypesToInclude ;
 return Database.getQueryLocator(query);

 

 

I am getting the error :

 

System.QueryException: unexpected token: '(' 

 

Any ideas whats wrong

 

Thanks