With this code:
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace TEST1
{
public partial class Form1 : Form
{
public delegate void RILRESULTCALLBACK(int dwCode, IntPtr hrCmdID, IntPtr lpData, int cbData, int dwParam);
public delegate void RILNOTIFYCALLBACK(int dwCode, IntPtr lpData, int cbData, int dwParam);
public static IntPtr hRil;
[StructLayout(LayoutKind.Explicit)]
class RILADDRESS
{
[FieldOffset(0)]
public uint dwSize;
[FieldOffset(4)]
public uint dwParams;
[FieldOffset(8)]
public uint dwType;
[FieldOffset(12)]
public uint dwNumPlan;
[FieldOffset(16)]
public byte[] sAddress = new byte[256 * 2];
//[FieldOffset(528)]
}
[StructLayout(LayoutKind.Explicit)]
class RILSUBADDRESS
{
[FieldOffset(0)]
public uint dwSize;
[FieldOffset(4)]
public uint dwParams;
[FieldOffset(8)]
public uint dwType;
[FieldOffset(12)]
public byte[] sSubAddress = new byte[256 * 2];
//[FieldOffset(524)]
}
[StructLayout(LayoutKind.Explicit)]
class RILREMOTEPARTYINFO
{
[FieldOffset(0)]
public uint dwSize;
[FieldOffset(4)]
public uint dwParams;
/*[FieldOffset(8)]
public RILADDRESS rilAddress = new RILADDRESS();
[FieldOffset(536)]
public RILSUBADDRESS rilSubAddress = new RILSUBADDRESS();
[FieldOffset(1060)]
public char[] sDescription = new char[256 * 2];
[FieldOffset(1572)]
public uint dwValidity;*/
}
[StructLayout(LayoutKind.Explicit)]
class RILCELLTOWERINFO
{
[FieldOffset(0)]
uint dwSize;
[FieldOffset(4)]
uint dwParams;
[FieldOffset(8)]
public uint dwMobileCountryCode;
[FieldOffset(12)]
public uint dwMobileNetworkCode;
[FieldOffset(16)]
public uint dwLocationAreaCode;
[FieldOffset(20)]
public uint dwCellID;
[FieldOffset(24)]
uint dwBaseStationID;
[FieldOffset(28)]
uint dwBroadcastControlChannel;
[FieldOffset(32)]
uint dwRxLevel;
[FieldOffset(36)]
uint dwRxLevelFull;
[FieldOffset(40)]
uint dwRxLevelSub;
[FieldOffset(44)]
uint dwRxQuality;
[FieldOffset(48)]
uint dwRxQualityFull;
[FieldOffset(52)]
uint dwRxQualitySub;
/* More minor interesting fields below */
}
[StructLayout(LayoutKind.Explicit)]
class RILRINGINFO
{
[FieldOffset(0)]
public uint dwSize;
[FieldOffset(4)]
public uint dwParams;
[FieldOffset(8)]
public uint dwCallType;
[FieldOffset(12)]
public uint dwAddressID;
}
//private static bool done = false;
private static string result = "";
[DllImport("ril.dll")]
private static extern IntPtr RIL_Initialize(int dwIndex, RILRESULTCALLBACK pfnResult, RILNOTIFYCALLBACK pfnNotify, int dwNotificationClasses, int dwParam, out IntPtr lphRil);
[DllImport("ril.dll", EntryPoint = "RIL_GetCellTowerInfo")]
private static extern IntPtr RIL_GetCellTowerInfo(IntPtr hRil);
[DllImport("ril.dll", EntryPoint = "RIL_Hangup")]
private static extern IntPtr RIL_Hangup(IntPtr hRil);
[DllImport("ril.dll")]
private static extern IntPtr RIL_Deinitialize(IntPtr hRil);
public static void f_notify(int dwCode, IntPtr lpData, int cbData, int dwParam)
{
string strMsg = "";
switch (dwCode & 0x00ff0000) //RIL_NCLASS_ALL
{
case 0x00080000: //RIL_NCLASS_SUPSERVICE
switch (dwCode & 0xff)
{
case 0x00000001: // RIL_NOTIFY_CALLERID
RILREMOTEPARTYINFO rilRemotePartyInfo = new RILREMOTEPARTYINFO();
Marshal.PtrToStructure(lpData, rilRemotePartyInfo);
break;
case 0x00000002: // RIL_NOTIFY_DIALEDRID
break;
case 0x00000003: // RIL_NOTIFY_CALLWAITING
break;
case 0x00000004: // RIL_NOTIFY_SUPSERVICEDATA
break;
}
strMsg += "SUPSERVICE";
break;
case 0x00010000: //RIL_NCLASS_CALLCTRL
switch (dwCode & 0xff)
{
case 0x00000001: // RIL_NOTIFY_RING
RILRINGINFO rilRingInfo = new RILRINGINFO();
Marshal.PtrToStructure(lpData, rilRingInfo);
switch (rilRingInfo.dwCallType)
{
case 0x00000000:
strMsg += "UNKNOWN ";
break;
case 0x00000001:
strMsg += "VOICE ";
//RIL_Hangup(hRil);
break;
case 0x00000002:
strMsg += "DATA ";
break;
case 0x00000003:
strMsg += "FAX ";
break;
default:
strMsg += "UNHANDLED ";
break;
}
break;
case 0x00000002: // RIL_NOTIFY_CONNECT
strMsg += "CONNECT ";
break;
case 0x00000003: // RIL_NOTIFY_DISCONNECT
strMsg += "DISCONNECT ";
break;
case 0x0000000B: // RIL_NOTIFY_CALLPROGRESSINFO
strMsg += "CPI ";
break;
default:
strMsg += "SOME ";
break;
}
strMsg += "CALL";
break;
case 0x00020000: // RIL_NCLASS_MESSAGE
switch (dwCode & 0xff)
{
case 0x00000001: // RIL_NOTIFY_MESSAGE
strMsg += "NEW ";
break;
default:
strMsg += "SOME ";
break;
}
strMsg += "SMS";
break;
}
//MessageBox.Show(strMsg);
}
public static void f_result(int dwCode, IntPtr hrCmdID, IntPtr lpData, int cbData, int dwParam)
{
/*RILCELLTOWERINFO rci = new RILCELLTOWERINFO();
Marshal.PtrToStructure(lpData, rci);
result = String.Format("MCC: {0}, MNC: {1}, LAC: {2}, CID: {3}",
rci.dwMobileCountryCode,
rci.dwMobileNetworkCode,
rci.dwLocationAreaCode,
rci.dwCellID);
done = true;*/
}
public static string GetCellTowerInfo()
{
IntPtr res;
RILRESULTCALLBACK result = new RILRESULTCALLBACK(f_result);
RILNOTIFYCALLBACK notify = new RILNOTIFYCALLBACK(f_notify);
res = RIL_Initialize(1, result, notify, (0x00010000 | 0x00020000 | 0x00080000), 0, out Form1.hRil);
if (res != IntPtr.Zero)
return ("Could not initialize Ril");
/*Form1.done = false;
Form1.result = "";
res = RIL_GetCellTowerInfo(hRil);
int i = 10;
while (i-- > 0 && !Form1.done)
{
System.Threading.Thread.Sleep(1000);
}
RIL_Deinitialize(hRil);*/
return Form1.result;
}
public Form1()
{
InitializeComponent();
string s = Form1.GetCellTowerInfo();
//MessageBox.Show(s);
}
private void button1_Click(object sender, EventArgs e)
{
RIL_Deinitialize(hRil);
Application.Exit();
}
}
}
at line 136 (Marshal.PtrToStructure(lpData, rilRemotePartyInfo) there is an exception (NotSupportedException) and i don't understand why!!!
Need some help please...........
Related
Hello together,
does anyone know why a Notify Icon is shown on Windows Mobile 5.0 Pocket PC's but not shown on Windows Mobile 2003 Pocket PC's?
Here is the code of my Notify Icon class:
Code:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace NotifyClient
{
public class NotifyIcon
{
//Declare click event
public event System.EventHandler Click;
private WindowSink windowSink;
private int uID = 5000;
//Constructor
public NotifyIcon()
{
//Create instance of the MessageWindow subclass
windowSink = new WindowSink(this);
windowSink.uID = uID;
}
//Destructor
~NotifyIcon()
{
Remove();
}
public void Add(IntPtr hIcon)
{
TrayMessage(windowSink.Hwnd, NIM_ADD, (uint)uID, hIcon);
}
public void Remove()
{
TrayMessage(windowSink.Hwnd, NIM_DELETE, (uint)uID, IntPtr.Zero);
}
public void Modify(IntPtr hIcon)
{
TrayMessage(windowSink.Hwnd, NIM_MODIFY, (uint)uID, hIcon);
}
private void TrayMessage(IntPtr hwnd, int dwMessage, uint uID, IntPtr hIcon)
{
NOTIFYICONDATA notdata = new NOTIFYICONDATA();
notdata.cbSize = 152;
notdata.hIcon = hIcon;
notdata.hWnd = hwnd;
notdata.uCallbackMessage = WM_NOTIFY_TRAY;
notdata.uFlags = NIF_MESSAGE | NIF_ICON;
notdata.uID = uID;
int ret = Shell_NotifyIcon(dwMessage, ref notdata);
}
#region API Declarations
internal const int WM_LBUTTONDOWN = 0x0201;
//User defined message
internal const int WM_NOTIFY_TRAY = 0x0400 + 2001;
internal const int NIM_ADD = 0x00000000;
internal const int NIM_MODIFY = 0x00000001;
internal const int NIM_DELETE = 0x00000002;
const int NIF_MESSAGE = 0x00000001;
const int NIF_ICON = 0x00000002;
internal struct NOTIFYICONDATA
{
internal int cbSize;
internal IntPtr hWnd;
internal uint uID;
internal uint uFlags;
internal uint uCallbackMessage;
internal IntPtr hIcon;
//internal char[] szTip = new char[64];
//internal IntPtr szTip;
}
[DllImport("coredll.dll")]
internal static extern int Shell_NotifyIcon(
int dwMessage,ref NOTIFYICONDATA pnid);
[DllImport("coredll.dll")]
internal static extern int SetForegroundWindow(IntPtr hWnd);
[DllImport("coredll.dll")]
internal static extern int ShowWindow(
IntPtr hWnd,
int nCmdShow);
[DllImport("coredll.dll")]
internal static extern IntPtr GetFocus();
#endregion
#region WindowSink
internal class WindowSink : Microsoft.WindowsCE.Forms.MessageWindow
{
//Private members
private int m_uID = 0;
private NotifyIcon notifyIcon;
//Constructor
public WindowSink(NotifyIcon notIcon)
{
notifyIcon = notIcon;
}
public int uID
{
set
{
m_uID = value;
}
}
protected override void WndProc(ref Microsoft.WindowsCE.Forms.Message msg)
{
if (msg.Msg == WM_NOTIFY_TRAY)
{
if((int)msg.LParam == WM_LBUTTONDOWN)
{
if ((int)msg.WParam == m_uID)
{
//If somebody hooked, raise the event
if (notifyIcon.Click != null)
notifyIcon.Click(notifyIcon, null);
}
}
}
}
}
#endregion
}
}
The usage of this class is in my WM 5.0 project identical with my WM 2003 project. But the icon is not shown...
It seems like the space in the "Task Bar" is reserved and my application reacts correct when I click on the place the icon should appear...
Does anyone have an idea?
Greetings
Alex
I've just spent a lot of time looking for ways to tie Windows and process exe files together and I saw a lot of people asking after similar topics.
It was somewhat frustrating because of numerous little difficulties - using CreateToolhelp32Snapshot unpredictably fails, GetProcessById is no good if the process wasn't started with StartInfo, because you can have multiple windows to a process it's hard to identify which is a processes mainwindow.
But I solved my problem, a solution that I haven't seen elsewhere, so I thought I'd share it here. This is my solution to the specific problem of finding a window to match an executable file path....
This is on WM6, using CF2 in C#.
Used as follows (with S2U2 as the example):
Ionwerks.Window w = new Ionwerks.Window(@"\Program Files\S2U2\S2U2.exe");
IntPtr WindowsHandle = w.handle;
Code:
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace Ionwerks
{
delegate int EnumWindowsProc(IntPtr hwnd, IntPtr lParam);
class Window
{
private EnumWindowsProc callbackDelegate;
private IntPtr callbackDelegatePointer;
private IntPtr m_handle = IntPtr.Zero;
private string moduleFileName = "";
//Construct from path
public Window(string path)
{
moduleFileName = path;
Enumerate();
}
public IntPtr handle
{
get
{
return m_handle;
}
}
private void Enumerate() {
callbackDelegate = new EnumWindowsProc(EnumWindowsCallbackProc);
callbackDelegatePointer = Marshal.GetFunctionPointerForDelegate(callbackDelegate);
EnumWindows(callbackDelegatePointer, 0);
}
[DllImport("coredll.dll", SetLastError = true)]
private static extern bool EnumWindows(IntPtr lpEnumFunc, uint lParam);
[DllImport("coredll.dll", EntryPoint = "GetModuleFileNameW", SetLastError = true)]
private static extern uint GetModuleFileName(IntPtr hModule, [MarshalAs(UnmanagedType.LPWStr)] string lpFileName, uint nSize);
[DllImport("coredll")]
private static extern uint GetWindowThreadProcessId(IntPtr hwnd, out int lpdwProcessId);
[DllImport("coredll.dll")]
private static extern IntPtr OpenProcess(int flags, bool fInherit, int PID);
[DllImport("coredll.dll")]
private static extern bool CloseHandle(IntPtr handle);
[DllImport("coredll.dll")]
private static extern bool IsWindowVisible(IntPtr handle);
private string ModuleFileName = new string((char)0x20, 255);
private int EnumWindowsCallbackProc(IntPtr hwnd, IntPtr lParam)
{
//get windows process
int pid = 0;
GetWindowThreadProcessId(hwnd, out pid);
IntPtr pHnd = OpenProcess(0, false, pid);
//get processes image
GetModuleFileName(pHnd, ModuleFileName, (uint)ModuleFileName.Length);
//if paths match up
if (String.Compare(ModuleFileName.Substring(0, ModuleFileName.IndexOf('\0')), moduleFileName, true) == 0) {
//only interested in processes mainwindow
if (hwnd == Process.GetProcessById(pid).MainWindowHandle)
{
m_handle = hwnd;
}
}
CloseHandle(pHnd);
return 1;
}
}
}
thanks man! your code helped!
simple explanation ... ?.... what that codes for and how to use
I want my form to fade to black until the app. exits, when I click my self-made exit-button. I've got my inspiration from the apps. "S2U2" and "PocketCM" ... they fade to black really smooth and fast.
I already got my app working... but it is extrem slowly.
for those who are interested in my application
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace TransparentSample
{
public partial class Form1 : Form
{
public struct BlendFunction
{
public byte BlendOp;
public byte BlendFlags;
public byte SourceConstantAlpha;
public byte AlphaFormat;
}
public enum BlendOperation : byte
{
AC_SRC_OVER = 0x00
}
public enum BlendFlags : byte
{
Zero = 0x00
}
public enum SourceConstantAlpha : byte
{
Transparent = 0x00,
Opaque = 0xFF
}
public enum AlphaFormat : byte
{
AC_SRC_ALPHA = 0x01
}
[DllImport("coredll.dll")]
extern public static Int32 AlphaBlend(IntPtr hdcDest,
Int32 xDest,
Int32 yDest,
Int32 cxDest,
Int32 cyDest,
IntPtr hdcSrc,
Int32 xSrc,
Int32 ySrc,
Int32 cxSrc,
Int32 cySrc,
BlendFunction blendFunction);
Bitmap backBuffer = null;
Byte alpha;
public Form1()
{
InitializeComponent();
backBuffer = new Bitmap( pictureBox1.Image);
alpha = 0x00;
}
protected override void OnPaintBackground(PaintEventArgs e)
{
// Prevent flicker, we will take care of the background in Form1_Paint
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
if (backBuffer != null)
{
Graphics gxBuffer = Graphics.FromImage(backBuffer);
gxBuffer.Clear(Color.White);
gxBuffer.DrawImage(pictureBox1.Image, 0, 0);
Graphics gxSrc = Graphics.FromImage( new Bitmap( backBuffer.Width, backBuffer.Height));
gxSrc.Clear(Color.Black);
IntPtr hdcDst = gxBuffer.GetHdc();
IntPtr hdcSrc = gxSrc.GetHdc();
BlendFunction blendFunction = new BlendFunction();
blendFunction.BlendOp = (byte)BlendOperation.AC_SRC_OVER; // Only supported blend operation
blendFunction.BlendFlags = (byte)BlendFlags.Zero; // Documentation says put 0 here
blendFunction.SourceConstantAlpha = (byte)alpha;// Constant alpha factor
blendFunction.AlphaFormat = (byte)0; // Don't look for per pixel alpha
Form1.AlphaBlend(
hdcDst,
0,
0,
backBuffer.Width,
backBuffer.Height,
hdcSrc,
0,
0,
pictureBox1.Width,
pictureBox1.Height,
blendFunction);
gxBuffer.ReleaseHdc(hdcDst); // Required cleanup to GetHdc()
gxSrc.ReleaseHdc(hdcSrc); // Required cleanup to GetHdc()
// Put the final composed image on screen.
e.Graphics.DrawImage(backBuffer, 0, 0);
}
}
private void btnExit_Click(object sender, EventArgs e)
{
tmrFade.Enabled = true;
}
private void tmrFade_Tick(object sender, EventArgs e)
{
// timers interval: 100ms ... so this should take 1Sek.
alpha = (byte)(alpha + (byte)25);
if (alpha == 250)
{
alpha = 0xff;
Application.Exit();
}
this.Refresh();
}
}
}
Have you got a better idea to solve this?
thanks
Look for DIBSection, but in .NET that's not gonna be easy.
You might be right about .NET
I already thought about coding in c++ ...I think that's what I am going to do.
Thank you
I have an async task that loads a list view of items. I am currently trying to set the onClick to load a new fragment with an "id" that is being retrieved from the list item that is clicked. I have no errors in my code that the Android Studio shows me.
When I run the app and click on the item in the list view I get this FC:
02-13 19:49:56.813 20334-20334/com.beerportfolio.beerportfoliopro E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.beerportfolio.beerportfoliopro.ReadJSONResult$1.onItemClick(ReadJSONResult.java:140)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1237)
at android.widget.ListView.performItemClick(ListView.java:4555)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3037)
at android.widget.AbsListView$1.run(AbsListView.java:3724)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5789)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:843)
at dalvik.system.NativeStart.main(Native Method)
02-13 19:50:42.112 20864-20870/? E/jdwp﹕ Failed sending reply to debugger: Broken pipe
line 140 in ReadJSONResult is:
listenerBeer.onArticleSelected(idToSend);
That line is part of this whole onClick:
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
BeerData beerInfo = beerList.get(arg2);
String idToSend = beerInfo.beerId;
//todo: launch beer fragment
listenerBeer.onArticleSelected(idToSend);
}
});
All the code for ReadJSONResult is:
public class ReadJSONResult extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public ReadJSONResult(Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
//code for on click
OnArticleSelectedListener listenerBeer;
public interface OnArticleSelectedListener{
public void onArticleSelected(String myString);
}
public void setOnArticleSelectedListener(OnArticleSelectedListener listener){
this.listenerBeer = listener;
}
//end code for onClick
@override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Searching Beer Cellar");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONObject json = new JSONObject(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(android.R.id.list);
//make array list for beer
final List<BeerData> beerList = new ArrayList<BeerData>();
//get json items
for(int i = 0; i < json.getJSONArray("data").length(); i++) {
String beerId = GetBeerDataFromJSON(i,"id", json);
String beerName = GetBeerDataFromJSON(i,"name", json);
String beerDescription = GetBeerDataFromJSON(i,"description" , json);
String beerAbv = GetBeerDataFromJSON(i,"abv" , json);
String beerIbu = GetBeerDataFromJSON(i,"ibu" , json);
String beerIcon = GetBeerIconsFromJSON(i, "icon",json );
String beerMediumIcon = GetBeerIconsFromJSON(i, "medium",json );
String beerLargeIcon = GetBeerIconsFromJSON(i, "large",json );
String beerGlass = GetBeerGlassFromJSON(i, json );
String beerStyle = GetBeerStyleFromJSON(i,"name", json );
String beerStyleDescription = GetBeerStyleFromJSON(i,"description", json );
String beerBreweryId = GetBeerBreweryInfoFromJSON(i, "id", json );
String beerBreweryName = GetBeerBreweryInfoFromJSON(i, "name", json );
String beerBreweryDescription = GetBeerBreweryInfoFromJSON(i, "description", json );
String beerBreweryWebsite = GetBeerBreweryInfoFromJSON(i, "website", json );
//get long and latt
String beerBreweryLat = GetBeerBreweryLocationJSON(i, "longitude", json );
String beerBreweryLong = GetBeerBreweryLocationJSON(i, "latitude", json );
String beerBreweryYear = GetBeerBreweryInfoFromJSON(i, "established", json );
String beerBreweryIcon = GetBeerBreweryIconsFromJSON(i,"large",json);
//create beer object
BeerData thisBeer = new BeerData(beerName, beerId, beerDescription, beerAbv, beerIbu, beerIcon,
beerMediumIcon,beerLargeIcon, beerGlass, beerStyle, beerStyleDescription, beerBreweryId, beerBreweryName,
beerBreweryDescription, beerBreweryYear, beerBreweryWebsite,beerBreweryIcon, beerBreweryLat, beerBreweryLong);
//add beer to list
beerList.add(thisBeer);
}
//update listview
BeerSearchAdapter adapter1 = new BeerSearchAdapter(c ,R.layout.listview_item_row, beerList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
BeerData beerInfo = beerList.get(arg2);
String idToSend = beerInfo.beerId;
//todo: launch beer fragment
listenerBeer.onArticleSelected(idToSend);
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
//todo: all the get functions go here
private String GetBeerDataFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get icons
private String GetBeerBreweryIconsFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getJSONObject("images").getString(whatIsTheKeyYouAreLookFor);;
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get icons
private String GetBeerIconsFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("labels").getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get style information
private String GetBeerStyleFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("style").getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get location data
private String GetBeerBreweryLocationJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getJSONArray("locations").getJSONObject(0).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get brewery information
//get style information
private String GetBeerBreweryInfoFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get glass
private String GetBeerGlassFromJSON(int position, JSONObject json ) {
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("glass").getString("name");
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
BeerSearchAdapter is:
public class BeerSearchAdapter extends ArrayAdapter<BeerData> {
Context context;
int layoutResourceId;
List<BeerData> data = null;
public BeerSearchAdapter(Context context, int layoutResourceId, List<BeerData> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
beerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new beerHolder();
holder.txtBrewery = (TextView)row.findViewById(R.id.beerBreweryNameList);
holder.txtTitle = (TextView)row.findViewById(R.id.beerNameList);
row.setTag(holder);
}
else
{
holder = (beerHolder)row.getTag();
}
BeerData beer = data.get(position);
holder.txtTitle.setText(beer.beerName);
holder.txtBrewery.setText(beer.beerBreweryName);
return row;
}
static class beerHolder
{
TextView txtBrewery;
TextView txtTitle;
}
}
My Search.java where the interface comes form is here:
public class Search extends Fragment implements SearchView.OnQueryTextListener, ReadJSONResult.OnArticleSelectedListener {
private ListView lv;
View v;
@override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//set layout here
v = inflater.inflate(R.layout.activity_search, container, false);
setHasOptionsMenu(true);
getActivity().setTitle("Search");
//get user information
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
//todo: code body goes here
// Inflate the layout for this fragment
return v;
}
@override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu, inflater);
Log.d("click", "inside the on create");
//inflater.inflate(R.menu.main, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search2).getActionView();
searchView.setIconified(false);
searchView.setOnQueryTextListener(this);
}
public boolean onQueryTextSubmit (String query) {
//toast query
//make json variables to fill
// url to make request
String url = "myURL";
try {
query = URLEncoder.encode(query, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String jsonUrl = url + query;
//todo: get json
new ReadJSONResult(getActivity()).execute(jsonUrl);
return false;
}
@override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
}
@override
public void onArticleSelected(String b){
//code to execute on click
Fragment Fragment_one;
FragmentManager man= getFragmentManager();
FragmentTransaction tran = man.beginTransaction();
//todo: set to beer fragment
Fragment_one = new StylePage2();
final Bundle bundle = new Bundle();
bundle.putString("beerIDSent", b);
Fragment_one.setArguments(bundle);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
Let me know if you need any other code, I am stomped on this and could use a second pair of eyes. Thanks.
I have created a questionnaire in the beginning of the app in order to base a user model off the answers chosen. The values of the chosen options are stored as Shared Preferences as shown below. With the data retrieved I am then trying to tag a Google map with certain tags based on the answers chosen. The issue I am encountering is that of reading the stored Shared Preference values across the different activities, from the Question2 Activity, to that of the Map Activity (code below). Any pointers on how to solve the *context* conflict would be greatly appreciated.
Question2 Activity:
Code:
public class Question2 extends Activity{
RadioButton q2a1,q2a2,q2a3;
Button btn2;
public static final String MY_PREF = "MyPreferences";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.activity_question2, null);
return v;
}
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question2);
q2a1 = (RadioButton) findViewById(R.id.q2a1);
q2a2 = (RadioButton) findViewById(R.id.q2a2);
q2a3 = (RadioButton) findViewById(R.id.q2a3);
btn2 = (Button) findViewById(R.id.q2_button);
btn2.setOnClickListener(new OnClickListener(){
public void onClick(View v){
SharedPreferences prefernces = getSharedPreferences(MY_PREF, 0);
SharedPreferences.Editor editor = prefernces.edit();
if (q2a1.isChecked()){
editor.putInt("answer_value2", 1);
editor.commit();
}
if (q2a2.isChecked()){
editor.putInt("answer_value2", 2);
editor.commit();
}
if (q2a3.isChecked()){
editor.putInt("answer_value2", 3);
editor.commit();
}else {
editor.putInt("answer_value2", 0);
editor.commit();
}
editor.commit();
Intent intent = new Intent(getApplicationContext(), Question3.class);
startActivity(intent);
}
});
}
}
Map Activity:
Code:
public class MapActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.mapLayout)).getMap();
map.setMyLocationEnabled(true);
SharedPreferences preferences = getSharedPreferences(Question2.MY_PREF,MODE_PRIVATE);
int q1answer = preferences.getInt("answer_value", 0);
int q2answer = preferences.getInt("answer_value2", 0);
int q3answer = preferences.getInt("answer_value3", 0);
if(q1answer == 1){
//method
}
if(q1answer == 2){
//method
}
if(q1answer == 3){
//method
}
if(q2answer == 1){
map.addMarker(new MarkerOptions().position(FOOD_FOOD).title("Food & Food").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(HEALTHSHOP).title("Health Shop").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(GRASSYHOPPER).title("Grasy Hopper").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(M_S).title("M&S").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(MINT).title("Mint").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}if(q2answer == 2){
Toast.makeText(getApplicationContext(), "Your result is " + q2answer, Toast.LENGTH_SHORT).show();
map.addMarker(new MarkerOptions().position(FOOD_FOOD).title("Food & Food").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(SUBWAY).title("Subway").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(NEWYORKSBEST).title("New York's Best").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(MCD).title("Mc Donald's").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(M_S).title("M&S").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(JUBILEE).title("Jubilee").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(GRASSYHOPPER).title("Grassy Hopper").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}if(q2answer == 3){
map.addMarker(new MarkerOptions().position(NEWYORKSBEST).title("New York's Best").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(SUBWAY).title("Subway").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(PASTIZZERIA).title("Pastizerria").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(MCD).title("Mc Donald's").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(BURGERKING).title("Burger King").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
if(q3answer == 1){
//implementation
}if(q3answer == 2){
//implementation
}if(q3answer == 3){
//implementation
}if(q3answer == 4){
//implementation
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
Use this
create this class in your package
Code:
public class SharedPrefence{
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "MyPreferences";
// Answers (make variable public to access from outside)
public static final String KEY_ANSWER_TWO = "answer_value2";
//similarly other answers tag can be added(this is the key of preference)
// Constructor
public SharedPrefence(Context context) {
_context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create Answer.
* */
public void createAnswer(int ans) {
// Storing name in pref
editor.putInt(KEY_ANSWER_TWO, ans);
// commit changes
editor.commit();
}
public int getAnswer(String tag,int default) {
return pref.getString(tag, default);
}
}
now create an activity and initialise this class in the starting with the activity context.
next call the create answer method of this class and you are done.
also no need to create sharedprefence in each activity.
and it's even better if you create only one activity and use ViewPager for all questions.you can google for it.
And if this was useful click on thanks below.
:victory::victory::victory::victory: