connect GPRS using RAS on Pocket PC 2005 - Windows Mobile Development and Hacking General

Hi,
I 'm not able to establish GPRS connection using RasDial on PPC 2005 . It returns always error 633. That means:
"The port is already in use or is not configured for Remote Access dialout.� (See related Microsoft article: ErrMsg: Error 633: The Modem Is Not Installed or Configured...) "
But it works fine in PPC 2003. Does anyone gets RAS API run successfull on WM 5.0 ?
here is my code:
Code:
void ConnectGPRSDlg::connectViaRAS()
{
RASDIALPARAMS rasDialParam;
BOOL bPasswd,bRasEntryFound;
DWORD dwRes, dwSize, dwEntries, dw;
short n_attempts = 5;
HRASCONN g_rasConn = NULL;
CString szError,msg,szResult;
LPRASENTRYNAME lpRasEntry = NULL;
// structure init.
memset(&rasDialParam, 0, sizeof(RASDIALPARAMS));
rasDialParam.dwSize = sizeof (RASDIALPARAMS);
lpRasEntry = new RASENTRYNAME[20];
if(lpRasEntry == NULL)
{
szError.Format( _T("Out of memory") );
msg += szError;
m_editbox.SetWindowTextW(msg);
return;
}
lpRasEntry[0].dwSize = sizeof(RASENTRYNAME);
dwSize = sizeof(RASENTRYNAME) * 20;
dwRes = RasEnumEntries(NULL, NULL, lpRasEntry,
&dwSize, &dwEntries);
if (dwRes != 0)
{
szError.Format( _T("Error getting RAS entries %d"),dwRes );
msg += szError;
}
else
{
szError.Format( _T("got RAS %d entries\r\n "),dwEntries );
msg += szError;
for(dw = 0; dw < dwEntries; dw++)
{
if( 0 == _tcscmp( lpRasEntry[dw].szEntryName, L"T-Mobile Internet" ) )
{
bRasEntryFound = TRUE;
_tcscpy( rasDialParam.szEntryName, lpRasEntry[dw].szEntryName );
szError.Format( _T("found entry: %s\r\n "),lpRasEntry[dw].szEntryName );
msg += szError;
}
}
}
if (!bRasEntryFound) return;
//// connection name
//wcscpy(rasDialParam.szEntryName, _T("T-Mobile Internet") );
//
// parameters from connection structure
dwRes = RasGetEntryDialParams(NULL, &rasDialParam, &bPasswd);
if(dwRes != 0)
{
szResult.Format( _T("getting Dial Params error: %D \r\n") , dwRes );
szResult += szError;
}
else
{
szResult.Format(L"entryname: %s, number: %s \r\n", rasDialParam.szEntryName,rasDialParam.szPhoneNumber);
msg += szResult;
}
// szError.Format( _T("creat new Dial Params...\r\n"));
//msg += szError;
// // Copy in the user credetials.
//_tcscpy( rasDialParam.szEntryName, _T("T-Mobile Internet") );
//_tcscpy( rasDialParam.szUserName, _T("t-mobile") );
//_tcscpy( rasDialParam.szPassword, _T("pwd") );
//_tcscpy( rasDialParam.szPhoneNumber, _T("*99#") );
//_tcscpy( rasDialParam.szCallbackNumber, _T("") );
szResult.Format(L"entryname: %s, number: %s \r\n", rasDialParam.szEntryName,rasDialParam.szPhoneNumber);
msg += szResult;
m_editbox.SetWindowTextW(msg);
do{
// if connection fails, hangup and retry... for 5 attemps
DWORD dwResult = RasDial(NULL,NULL,&rasDialParam,0,NULL,&g_rasConn);
Sleep(2000);
if ( dwResult != 0)
{
szError.Format(L"RAS error: %d \r\n", dwResult);
msg += szError;
m_editbox.SetWindowTextW(msg);
RasHangUp(g_rasConn);
g_rasConn = NULL;
n_attempts--;
}
else {
break;
}
}
while(n_attempts);
if(n_attempts == 0)
{
//AddDebugInfo( L"Can't connect GPRS" );
}
else
{
RASCONNSTATUS rasConStatus;
memset(&rasConStatus, 0, sizeof(RASCONNSTATUS));
rasConStatus.dwSize = sizeof(RASCONNSTATUS);
RasGetConnectStatus(g_rasConn, &rasConStatus);
if(rasConStatus.dwError == 0) {
szResult.Format( L"GPRS connected \r\n" );
msg += szResult;
}
else
{
szResult.Format(L"Ras connect status: %s \r\n", rasConStatus.dwError);
msg += szResult;
}
}
m_editbox.SetWindowTextW(msg);
return;
}

Related

CreateDispatch error $800700C1 - evc4.0 Automation sample ?

Hi !
I testing make Out of procces server on XDA II (MDA II) in eVc++4. I have problems
with this. If i called in client this :
IComMDA m_ComMda;
COleException m_Error;
if (m_ComMda.CreateDispatch(_T("ComMDA.Document"),&m_Error))
{
AfxMessageBox(_T("CreateDispatch - TRUE"),MB_OK,0);
return TRUE;
}
else
{
AfxMessageBox(_T("CreateDispatch - FALSE"),MB_OK,0);
return FALSE;
}
the error occur
==> CreateDispatch returning scode = severity: SEVERITY_ERROR, facility:
FACILITY_WIN32 ($800700C1).
IComMDA is class created from typelibrary :
class IComMDA : public COleDispatchDriver
{
public:
IComMDA() {} // Calls COleDispatchDriver default constructor
IComMDA(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {}
IComMDA(const IComMDA& dispatchSrc) : COleDispatchDriver(dispatchSrc) {}
// Attributes
public:
// Operations
public:
BOOL InitInterface();
};
interface is declared :
[ uuid(713B5595-EF1F-4961-A179-E374E0C82903), version(1.0) ]
library ComMDA
{
importlib("stdole32.tlb");
importlib("stdole2.tlb");
// Primary dispatch interface for CComMDADoc
[ uuid(901AD61B-9974-448a-9E79-7898E0C80FFE) ]
dispinterface IComMDA
{
properties:
// NOTE - ClassWizard will maintain property information here.
// Use extreme caution when editing this section.
//{{AFX_ODL_PROP(CComMDADoc)
//}}AFX_ODL_PROP
methods:
// NOTE - ClassWizard will maintain method information here.
// Use extreme caution when editing this section.
//{{AFX_ODL_METHOD(CComMDADoc)
[id(1)] boolean InitInterface();
//}}AFX_ODL_METHOD
};
// Class information for CComMDADoc
[ uuid(E523187A-FFB7-46e9-AA64-A6CB1BEAF9BB) ]
coclass Document
{
[default] dispinterface IComMDA;
};
//{{AFX_APPEND_ODL}}
//}}AFX_APPEND_ODL}}
};
Class is registered as :
CString strServerName;
CString strLocalServerName;
CString strLocalShortName;
CString strLocalFilterName;
CString strLocalFilterExt;
if (!m_pDocTemplate->GetDocString(strServerName,
CDocTemplate::regFileTypeId) || strServerName.IsEmpty())
{
return;
}
if (!m_pDocTemplate->GetDocString(strLocalServerName,
CDocTemplate::regFileTypeName))
strLocalServerName = strServerName; // use non-localized name
if (!m_pDocTemplate->GetDocString(strLocalShortName,
CDocTemplate::fileNewName))
strLocalShortName = strLocalServerName; // use long name
if (!m_pDocTemplate->GetDocString(strLocalFilterName,
CDocTemplate::filterName))
ASSERT(nAppType != OAT_DOC_OBJECT_SERVER);
if (!m_pDocTemplate->GetDocString(strLocalFilterExt,
CDocTemplate::filterExt))
ASSERT(nAppType != OAT_DOC_OBJECT_SERVER);
ASSERT(strServerName.Find(' ') == -1); // no spaces allowed
int nIconIndex = 0;
POSITION pos = AfxGetApp()->GetFirstDocTemplatePosition();
for (int nIndex = 1; pos != NULL; nIndex++)
{
CDocTemplate* pTemplate = AfxGetApp()->GetNextDocTemplate(pos);
if (pTemplate == m_pDocTemplate)
{
nIconIndex = nIndex;
pos = NULL; // set exit condition
}
}
BOOL bResult = FALSE;
if (TRUE)
{
// call global helper to modify system registry
// progid, shortname, and long name are all equal in this case
if (!(bResult = AfxOleRegisterServerClass(m_clsid, strServerName,
strLocalShortName, strLocalServerName, nAppType,
rglpszRegister, rglpszOverwrite, nIconIndex,
strLocalFilterName, strLocalFilterExt)))
{
// not fatal (don't fail just warn)
AfxMessageBox(AFX_IDP_FAILED_TO_AUTO_REGISTER);
}
}
else
{
bResult = AfxOleUnregisterServerClass(m_clsid, m_lpszProgID, m_lpszProgID,
m_lpszProgID, OAT_DISPATCH_OBJECT);
}
return;
------------------------------------------------
type library is registered as AfxOleRegisterTypeLib(AfxGetInstanceHandle(),
clsid);
where >// {713B5595-EF1F-4961-A179-E374E0C82903}
static const GUID clsid =
{ 0x713b5595, 0xef1f, 0x4961, { 0xa1, 0x79, 0xe3, 0x74, 0xe0, 0xc8, 0x29,
0x3 } };
Thanks for your help.

Bluetooth Programming...

This is for the C/C++ developers out here...
i need to connect a PocketPC to a PC via Bluetooth. Looking at various samples from the Windows Platform SDK and the Windows Mobile SDKs, i came up with the following server (PC) and client (PDA) codes:
Server Code (WinXP):
Code:
WSAData wsaData;
SOCKADDR_BTH sa;
int namelen;
SOCKET sock;
SOCKADDR_BTH sockaddr;
int size = sizeof(sockaddr);
if (WSAStartup(MAKEWORD(2, 2), &wsaData) == SOCKET_ERROR)
return false;
BluetoothHost_Socket = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
if (BluetoothHost_Socket == INVALID_SOCKET)
return false;
memset (&sa, 0, sizeof(sa));
sa.addressFamily = AF_BTH;
sa.port = 0;
if (bind(BluetoothHost_Socket, (SOCKADDR *) &sa, sizeof(sa)))
{
closesocket(BluetoothHost_Socket);
return false;
namelen = sizeof(sa);
if (getsockname(BluetoothHost_Socket, (SOCKADDR *)&sa, &namelen))
{
closesocket (BluetoothHost_Socket);
return false;
}
BluetoothHost_ClientListCount = 0;
if (listen(BluetoothHost_Socket, 5))
return false;
sock = accept(BluetoothHost_Socket, (SOCKADDR *) &sockaddr, &size);
}
Client Code (WinCE):
Code:
WSAQUERYSET querySet;
HANDLE hLookup;
char buffer[1000];
DWORD bufferlength;
WSAQUERYSET *results;
SOCKADDR_BTH *btaddr;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) == SOCKET_ERROR)
return false;
memset(&querySet, 0, sizeof(querySet));
querySet.dwSize = sizeof(querySet);
querySet.dwNameSpace = NS_BTH;
BluetoothQuery_DeviceCount = 0;
if (WSALookupServiceBegin(&querySet, LUP_CONTAINERS, &hLookup) == SOCKET_ERROR)
return false;
while (BluetoothQuery_DeviceCount < BLUETOOTHQUERY_MAXDEVICES && !BluetoothQuery_Cancel)
{
bufferlength = sizeof(buffer);
memset(buffer, 0, sizeof(buffer));
results = (WSAQUERYSET *) &buffer;
if (WSALookupServiceNext(hLookup, LUP_RETURN_NAME|LUP_RETURN_ADDR, &bufferlength, results) == SOCKET_ERROR)
{
int result = WSAGetLastError();
break;
}
btaddr = (SOCKADDR_BTH*)results->lpcsaBuffer->RemoteAddr.lpSockaddr;
BluetoothQuery_DeviceAddrList[BluetoothQuery_DeviceCount]=btaddr->btAddr;
if (results->lpszServiceInstanceName != NULL)
wcscpy((TCHAR *)BluetoothQuery_DeviceNameList[BluetoothQuery_DeviceCount],results->lpszServiceInstanceName);
else
wcscpy((TCHAR *)BluetoothQuery_DeviceNameList[BluetoothQuery_DeviceCount],L"<unnamed>");
BluetoothQuery_DeviceCount++;
}
WSALookupServiceEnd(hLookup);
BluetoothClient_Socket = socket (AF_BT, SOCK_STREAM, BTHPROTO_RFCOMM);
if (BluetoothClient_Socket == INVALID_SOCKET)
return false;
SOCKADDR_BTH sa;
memset (&sa, 0, sizeof(sa));
sa.addressFamily = AF_BT;
sa.btAddr = *btaddr;
for (i = 0; i < 30; i++)
{
sa.port = i; //channel & 0xff;
if (connect(BluetoothClient_Socket, (SOCKADDR *) &sa, sizeof(sa)) == 0)
break;
}
if (i >= 30)
{
closesocket(BluetoothClient_Socket);
return false;
}
All calls seems to work out. Sockets are created, all return values look ok. Yet, the client does not connect to the server, so the server never goes beyong that accept() call.
Any comments would be greatly appreciated!
thanks,
Daniel

AT Command to gsm module in WM6

Hello everyone,
This topic is not new however i never see any thread that has the solution for WM6. In my case, i want to create an smartphone app send AT Command to the gsm modem of my HTC HD.
Apparently there's no port COM2 or COM9 open in the device (everytime i tried CreateFile there's error 55, i also checked in the active device registry, no COM2 or COM9), so i use RIL_Initialize and RIL_GetSerialPortHandle to get the port. The openning and writing steps works very well, however there's no data in return, seems that the modem doesn't respond.
Below is the code:
Code:
RIL_Initialize(1,
ResultCallback,
NotifyCallback,
dwNotifications,
dwParam,
&RilHandle);
HANDLE hCom = NULL;
char * xpos;
char rsltstr[5];
DWORD returnValue;
DWORD LAC;
DWORD CellId;
int bufpos;
DCB dcb;
COMMTIMEOUTS to;
DWORD nWritten;
DWORD event1;
DWORD nRead;
char outbuf[20], buf[256];
BYTE comdevcmd[2]= {0x84, 0x00};
GetSerialPortHandleResult = RIL_GetSerialPortHandle(RilHandle,&hCom);
if (FAILED(GetSerialPortHandleResult))
{
TCHAR szString[256];
wsprintf(szString, L"Error GetSerialPortHandle, result= %d",GetSerialPortHandleResult);
MessageBox(NULL, szString, L"Error", MB_OK | MB_ICONERROR);
return 0;
}
if (hCom==NULL || hCom==INVALID_HANDLE_VALUE)
{
TCHAR szBuf[80];
DWORD dw = GetLastError();
// get the most uptodate cells
_stprintf(szBuf, TEXT("CreateFile failed with error %d."), dw);
MessageBox(0, szBuf, TEXT("Error"), MB_OK);
hCom= NULL;
return -1;
}
if (!GetCommState(hCom, &dcb))
{
return -2;
}
dcb.BaudRate= CBR_115200;
dcb.ByteSize= 8;
dcb.fParity= false;
dcb.StopBits= ONESTOPBIT;
if (!SetCommState(hCom, &dcb))
{
return -3;
}
if (!EscapeCommFunction(hCom, SETDTR))
{
return -4;
}
if (!GetCommTimeouts(hCom, &to))
{
return -6;
}
to.ReadIntervalTimeout= 0;
to.ReadTotalTimeoutConstant= 200;
to.ReadTotalTimeoutMultiplier= 0;
to.WriteTotalTimeoutConstant= 20000;
to.WriteTotalTimeoutMultiplier= 0;
if (!SetCommTimeouts(hCom, &to))
{
return -7;
}
if (!SetCommMask(hCom, EV_RXCHAR))
{
return -8;
}
if (!DeviceIoControl (hCom,0xAAAA5679L, comdevcmd,sizeof(comdevcmd),0,0,0,0))
{
TCHAR szBuf[80];
DWORD dw = GetLastError();
// get the most uptodate cells
_stprintf(szBuf, TEXT("DeviceIoControl failed with error %d."), dw);
MessageBox(NULL,szBuf, TEXT("Error"), MB_OK);
return -9;
}
bufpos = 0;
strcpy(outbuf,"AT+creg=2\r");
if (!WriteFile(hCom, outbuf, strlen(outbuf), &nWritten, NULL))
{
return -10;
}
if (nWritten != strlen(outbuf))
{
return -11;
}
/*if (!WaitCommEvent(hCom, &event1, NULL)) // ALWAYS BLOCKED !!!
{
return -12;
}*/Sleep(500);
while(1)
{
if (!ReadFile(hCom, buf+bufpos, 256 - bufpos, &nRead, NULL))
{
return -13;
}
if (nRead == 0) // ALWAYS BREAKS !!!
break;
bufpos += nRead;
if (bufpos >= 256)
break;
}
strcpy(outbuf,"AT+creg?\r");
... // Continue to write and read
As i said above, there's no return error, just that the buffer read is empty...
Any ideas ?
Thanks!
I don't know why it always gets nRead = 0, all the other steps work very well, no error return ...
I saw several discussions about this, so i do believe that someone have tried once this dev in WM5 or 6...
Therefore could anyone please share some point ?
no one has an idea ?
There's something a little bit interesting that i found out directly in the memory.
There's a sequence of responses to AT Command writing in ASCII:
@HTCCSQ:3
@HTCCSQ:4
@HTCCSQ:2
+CREG: 1,"000C","9F60" (here we has current LAC + Cell ID)
+CREG: 1,"000C","9BC7" (another LAC + Cell ID, i think it's the previous one)
+COPS: 0,2,"20820",3 (inside the "" are MCC MNC)
@HTCCSQ:3 .... (there's plenty of @HTCCSQ: coming next )
Look like some kind of log of the querries of RIL driver to the modem (i'm not sure)
So i think the gsm modem is available for answering to the commands, just haven't figured out how to make a stream connection to it (in WM6).
Any ideas ?
Thanks.
TAPI
I heard somewhere that we can use TAPI to send some AT Command, my question is to know if we can send a custom command (for example AT+CCED) by using TAPI ?
hi,I met the same problem.Do you find the answer?
Thanks.

[Q] Why does this code not work in CE 6.0?

I want to add to HKLM\init an all purpose application launcher (CE 6.0 device has persistent registry):
Code:
[HKEY_LOCAL_MACHINE\Init]
"Depend199"=hex:00,14,00,1e,00,60
[HKEY_LOCAL_MACHINE\Init]
"Launch199"="\NandFlash\CeLaunchAppsAtBootTime.exe"
[HKEY_CURRENT_USER\Startup]
"Process1"="\NandFlash\SetBackLight.exe"
"Process1Delay"=dword:0
The launcher's code is
Code:
#include <Windows.h>
#if defined(OutputDebugString)
#undef OutputDebugString
void OutputDebugString(LPTSTR lpText)
{}
#endif
BOOL IsAPIReady(DWORD hAPI);
void WalkStartupKeys(void);
DWORD WINAPI ProcessThread(LPVOID lpParameter);
#define MAX_APPSTART_KEYNAME 256
typedef struct _ProcessStruct {
WCHAR szName[MAX_APPSTART_KEYNAME];
DWORD dwDelay;
} PROCESS_STRUCT,*LPPROCESS_STRUCT;
int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
int nLaunchCode = -1;
// Quick check to see whether we were called from within HKLM\init -> by default HKLM\init passes the lauch code
if(lpCmdLine && *lpCmdLine)
{
// MessageBox(NULL, lpCmdLine ,NULL,MB_OK);
nLaunchCode = _ttoi( (const TCHAR *) lpCmdLine);
}
else
{
// MessageBox(NULL, _T("No argumets passed"),NULL,MB_OK);
}
//Wait for system has completely initialized
BOOL success = FALSE;
int i = 0;
while((!IsAPIReady(SH_FILESYS_APIS)) && (i++ < 50))
{
Sleep(200);
}
success = (i < 50);
if(success)
{
i = 0;
while((!IsAPIReady(SH_DEVMGR_APIS))&& (i++ < 50))
{
Sleep(200);
}
success = (i < 50);
if(success)
{
i = 0;
while((!IsAPIReady(SH_SHELL))&& (i++ < 50))
{
Sleep(200);
}
success = (i < 50);
if(success)
{
i = 0;
while((!IsAPIReady(SH_WMGR))&& (i++ < 50))
{
Sleep(200);
}
success = (i < 50);
if(success)
{
i = 0;
while((!IsAPIReady(SH_GDI))&& (i++ < 50))
{
Sleep(200);
}
success = (i < 50);
}
}
}
}
if(nLaunchCode != -1)
{
// Since this is application is launched through the registry HKLM\Init we need to call SignalStarted passing in the command line parameter
SignalStarted((DWORD) nLaunchCode);
}
//If system has completely initialized
if( success)
{
WalkStartupKeys();
}
return (0);
}
void WalkStartupKeys(void)
{
HKEY hKey;
WCHAR szName[MAX_APPSTART_KEYNAME];
WCHAR szVal[MAX_APPSTART_KEYNAME];
WCHAR szDelay[MAX_APPSTART_KEYNAME];
DWORD dwType, dwNameSize, dwValSize, i,dwDelay;
DWORD dwMaxTimeout=0;
HANDLE hWaitThread=NULL;
HANDLE ThreadHandles[100];
int iThreadCount=0;
if (RegOpenKeyEx(HKEY_CURRENT_USER, TEXT("Startup"), 0, KEY_READ, &hKey) != ERROR_SUCCESS) {
return;
}
dwNameSize = MAX_APPSTART_KEYNAME;
dwValSize = MAX_APPSTART_KEYNAME * sizeof(WCHAR);
i = 0;
while (RegEnumValue(hKey, i, szName, &dwNameSize, 0, &dwType,(LPBYTE)szVal, &dwValSize) == ERROR_SUCCESS) {
if ((dwType == REG_SZ) && !wcsncmp(szName, TEXT("Process"), 7)) { // 7 for "Process"
// szval
wsprintf(szDelay,L"%sDelay",szName);
dwValSize=sizeof(dwDelay);
if (ERROR_SUCCESS == RegQueryValueEx(hKey,szDelay,0,&dwType,(LPBYTE)&dwDelay,&dwValSize)) {
// we now have the process name and the process delay - spawn a thread to "Sleep" and then create the process.
LPPROCESS_STRUCT ps=(LPPROCESS_STRUCT) LocalAlloc( LMEM_FIXED , sizeof( PROCESS_STRUCT));
ps->dwDelay=dwDelay;
wcscpy(ps->szName,szVal);
DWORD dwThreadID;
OutputDebugString(L"Creating Thread...\n");
HANDLE hThread=CreateThread(NULL,0,ProcessThread,(LPVOID)ps,0,&dwThreadID);
ThreadHandles[iThreadCount++]=hThread;
if (dwDelay > dwMaxTimeout) {
hWaitThread=hThread;
dwMaxTimeout=dwDelay;
}
LocalFree((HLOCAL) ps);
}
}
dwNameSize = MAX_APPSTART_KEYNAME;
dwValSize = MAX_APPSTART_KEYNAME * sizeof(WCHAR);
i++;
}
// wait on the thread with the longest delay.
DWORD dwWait=WaitForSingleObject(hWaitThread,INFINITE);
if (WAIT_FAILED == dwWait) {
OutputDebugString(L"Wait Failed!\n");
}
for(int x=0;x < iThreadCount;x++) {
CloseHandle(ThreadHandles[x]);
}
RegCloseKey(hKey);
}
DWORD WINAPI ProcessThread(LPVOID lpParameter)
{
TCHAR tcModuleName[MAX_APPSTART_KEYNAME];
OutputDebugString(L"Thread Created... Sleeping\n");
LPPROCESS_STRUCT ps=(LPPROCESS_STRUCT)lpParameter;
Sleep(ps->dwDelay); // Wait for delay period
OutputDebugString(L"Done Sleeping...\n");
PROCESS_INFORMATION pi;
STARTUPINFO si;
si.cb=sizeof(si);
OutputDebugString(L"Creating Process ");
OutputDebugString(ps->szName);
OutputDebugString(L"\n");
wcscpy(tcModuleName,ps->szName);
TCHAR *tcPtrSpace=wcsrchr(ps->szName,L' '); // Launch command has a space, assume command line.
if (NULL != tcPtrSpace) {
tcModuleName[lstrlen(ps->szName)-lstrlen(tcPtrSpace)]=0x00; // overwrite the space with null, break the app and cmd line.
tcPtrSpace++; // move past space character.
}
CreateProcess( tcModuleName, // Module Name
tcPtrSpace, // Command line -- NULL or PTR to command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi ); // Pointer to PROCESS_INFORMATION structure
OutputDebugString(L"Thread Exiting...\n");
return 0;
}
which compiled errorfree
Added the registry entries as shown above, copied the launcher's exe in default location, rebootet device. Nothing happened, means executable defined as
Code:
[HKEY_CURRENT_USER\Startup]
"Process1"="\NandFlash\SetBackLight.exe"
wasn't run at all.
Does anybody have an idea, where the error is? Any help appreciated. Thanks for reading.

How can I loop through my JSON object?

I am new to Java and I am getting kind of stuck by trying to loop through my JSON. I am retrieving a JSON object where I want to loop through.
My JSON looks as follow:
Code:
{"message":{"2":[{"uid":"2","title":"","message":"Test1","success":1,"created_at":null,"updated_at":null}],"3":[{"uid":"3","title":"","message":"Test2 !","success":1,"created_at":null,"updated_at":null}],"4":[{"uid":"4","title":"Bla","message":"Test3!","success":1,"created_at":null,"updated_at":null}]}}
I tried a loop like this:
Code:
for(int i = 0; i<json.names().length(); i++){
try {
Log.v("TEST", "key = " + json.names().getString(i) + " value = " + json.get(json.names().getString(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
But this will only target "message" which includes the whole JSON "string". I want to loop through each message and retrieving the value of uid 1, uid 2 etc. How can I achieve this?
Thanks in advance.
Here is how I'm doing it:
Code:
private static final String AllNewsItemsURL = "some_url_here.php";
private static final String TAG_SUCCESS = "success";
private static final String NEWS = "news";
private static final String TITLE = "title";
private static final String STORY = "story";
private final JSONParser jParser = new JSONParser();
private JSONArray newsItems = null;
..... / code snipped / ....
try {
JSONObject json = jParser.makeHttpRequest(AllNewsItemsURL, params);
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
newsItems = json.getJSONArray(NEWS);
for (int i = 0; i < newsItems.length(); i++) {
JSONObject obj = newsItems.getJSONObject(i);
Integer id = i + 1;
String title = obj.getString(TITLE);
String story = obj.getString(STORY);
}
} else {
Log.e("JSON Response", "success == 0");
}
} catch (Exception e) {
e.printStackTrace();
}
Thanks for your reply. I tried it but getting this exception:
Code:
org.json.JSONException: Value {"2":[{"uid":"2","title":"","message":"Test1","success":1,"created_at":null,"updated_at":null}],"3":[{"uid":"3","title":"","message":"Test2","success":1,"created_at":null,"updated_at":null}],"4":[{"uid":"4","title":"Bla","message":"Test3","success":1,"created_at":null,"updated_at":null}]} at messages of type org.json.JSONObject cannot be converted to JSONArray
CodeMonkeyy said:
Thanks for your reply. I tried it but getting this exception:
Code:
org.json.JSONException: Value {"2":[{"uid":"2","title":"","message":"Test1","success":1,"created_at":null,"updated_at":null}],"3":[{"uid":"3","title":"","message":"Test2","success":1,"created_at":null,"updated_at":null}],"4":[{"uid":"4","title":"Bla","message":"Test3","success":1,"created_at":null,"updated_at":null}]} at messages of type org.json.JSONObject cannot be converted to JSONArray
Click to expand...
Click to collapse
You might want to try the matching JSONParser I have for it, sorry forgot to include it:
https://github.com/JonnyXDA/WGSB/bl...om/jonny/wgsb/material/parser/JSONParser.java
Also noting that your entire JSON Array is called "message" but you also have a parameter called "message" - maybe rename the Array to "messages"?
As for the code you should have something like:
Code:
private static final String AllNewsItemsURL = "some_url_here.php";
private static final String TAG_SUCCESS = "success";
private static final String MESSAGES = "messages";
private static final String TITLE = "title";
private static final String MESSAGE = "message";
private final JSONParser jParser = new JSONParser();
private JSONArray messageItems = null;
..... / code snipped / ....
try {
JSONObject json = jParser.makeHttpRequest(AllNewsItemsURL, params);
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
messageItems = json.getJSONArray(MESSAGES);
for (int i = 0; i < messageItems.length(); i++) {
JSONObject obj = messageItems.getJSONObject(i);
String title = obj.getString(TITLE);
String message = obj.getString(MESSAGE);
}
} else {
Log.e("JSON Response", "success == 0");
}
} catch (Exception e) {
e.printStackTrace();
}
My code looks like the this:
Code:
//Message task
MessageTask task = new MessageTask(DashboardActivity.class);
task.execute();
try {
json = task.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
messageItems = json.getJSONArray(MESSAGES);
for (int i = 0; i < messageItems.length(); i++) {
JSONObject obj = messageItems.getJSONObject(i);
String title = obj.getString(TITLE);
String message = obj.getString(MESSAGE);
}
} else {
Log.e("JSON Response", "success == 0");
}
} catch (Exception e) {
e.printStackTrace();
}
I am using Async Task to retrieve my JSON.
And my JSON parser looks like this:
Code:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
But it doesn't get through the if statement, because it can't find the value success. ( org.json.JSONException: No value for success ). Don't really know what I am doing wrong here. Is it because I am using AsyncTask and retrieving my JSON the wrong way?
I also renamed my Array to "messages", stupid mistake thanks!
CodeMonkeyy said:
But it doesn't get through the if statement, because it can't find the value success. ( org.json.JSONException: No value for success ). Don't really know what I am doing wrong here. Is it because I am using AsyncTask and retrieving my JSON the wrong way?
I also renamed my Array to "messages", stupid mistake thanks!
Click to expand...
Click to collapse
We're getting closer! With regards to using AsyncTask - thats fine and the recommended way to do service side sync/download operations (doesn't block the UI thread) so no need to change that.
I just took a look at my reference JSON and I have the success tag outside of an item eg:
Code:
{"topical":[{"tid":"5","title":"Exam countdown... just 12 weeks left!","story":"some_story_text_here","staff":"0","red":"0","show":"1"}],[COLOR="red"]"success":1[/COLOR]}
Whereas your success tag is put in each item:
Code:
{"message":{"2":[{"uid":"2","title":"","message":"Test1","[COLOR="red"]success":1,[/COLOR]"created_at":null,"updated_at":null}],"3":[{"uid":"3","title":"","message":"Test2 !",[COLOR="red"]"success":1[/COLOR],"created_at":null,"updated_at":null}],"4":[{"uid":"4","title":"Bla","message":"Test3!","[COLOR="Red"]success":1[/COLOR],"created_at":null,"updated_at":null}]}}
I'm guessing that your php line for:
PHP:
$response["success"] = 1;
is inside of the while loop:
PHP:
while ($row = mysql_fetch_array($result)) {
Taking it out of the while loop should fix that
That makes sense, because I am trying to get a success code for my whole JSON response. I changed my PHP code to:
Code:
while($row = mysqli_fetch_array( $messages )) {
// create rowArr
$rowArr = array(
'uid' => $row['id'],
'title' => $row['title'],
'message' => $row["message"],
'created_at' => $row['created_at'],
'updated_at' => $row['updated_at'],
);
// store rowArr in $return_arr
$return_arr[$row['id']][] = $rowArr;
}
$return_arr['success'] = 1;
// Json encode
echo json_encode(array("messages" => $return_arr));
}
Retrieving the following JSON:
Code:
{"messages":{"2":[{"uid":"2","title":"","message":"Test1","created_at":null,"updated_at":null}],"3":[{"uid":"3","title":"","message":"Test2 !","created_at":null,"updated_at":null}],"4":[{"uid":"4","title":"Bla","message":"Test3!","created_at":null,"updated_at":null}],"success":1}}
But I am still getting the following exception:
Code:
org.json.JSONException: No value for success
The success tag is still being encoded as part of an inner array, not the first array - try this:
PHP:
if (mysql_num_rows($messages) > 0) {
$response["messages"] = array();
while ($row = mysql_fetch_array($messages)) {
$messagesArray= array(
'uid' => $row['id'],
'title' => $row['title'],
'message' => $row['message'],
'created_at' => $row['created_at'],
'updated_at' => $row['updated_at'],
);
array_push($response["messages"], $messagesArray);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No messages found";
echo json_encode($response);
}
And it's finally working!
Getting the following JSON result:
Code:
{"tag":"message","success":1,"error":0,"messages":[{"uid":"2","title":"","message":"Test1","created_at":null,"updated_at":null},{"uid":"3","title":"","message":"Test2!","created_at":null,"updated_at":null},{"uid":"4","title":"Bla","message":"Test3!","created_at":null,"updated_at":null}]}
And I can successfully loop through my JSON with the following code:
Code:
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
messageItems = json.getJSONArray(MESSAGES);
for (int i = 0; i < messageItems.length(); i++) {
JSONObject obj = messageItems.getJSONObject(i);
String title = obj.getString(TITLE);
String message = obj.getString(MESSAGE);
Log.e("TITLE :", title);
Log.e("MESSAGE :", message);
}
} else {
Log.e("JSON Response", "success == 0");
}
} catch (Exception e) {
e.printStackTrace();
}
Thank you very much! So the problem was that I placed the "success" tag outside my Array?

Categories

Resources