Search Results

Search found 671 results on 27 pages for 'stub'.

Page 6/27 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • RemoteViewsService never gets called whenever we update app widget

    - by user3689160
    I am making one task widget application. This is a simple widget application which can be used to add new tasks by clicking on "+New Task". So ideally what I have done is, I've added a widget first, then when we click on "+New Task" a new activity opens up from where we can type in a new task and it should get updated in the ListView inside the home screen widget. Problem: Now whenever I add a new task, the ListView does not get updated. The data gets inside the database a new is created as well. My onUpdate(...) method gets called as well. There is a WidgetService.java which is a RemoteViewService that is being used to call the RemoteViewFactory but WidgetService.java gets called only when we create the widget, never after that. WidgetService.java never gets called again. I have the following setup MyWidgetProvider.java AppWidgetProvider class for updating the widget and filling its remote views. public class MyWidgetProvider extends AppWidgetProvider { public static int randomNumber=132; static RemoteViews remoteViews = null; @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { updateList(context,appWidgetManager,appWidgetIds); } public static void updateList(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){ final int N = appWidgetIds.length; Log.d("MyWidgetProvider", "length="+appWidgetIds.length+""); for (int i = 0; i<N; ++i) { Log.d("MyWidgetProvider", "value"+ i + "="+appWidgetIds[i]); // Calling updateWidgetListView(context, appWidgetIds[i]); to load the listview with data remoteViews = updateWidgetListView(context, appWidgetIds[i]); // Updating the Widget with the new data filled remoteviews appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews); appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds[i], R.id.lv_tasks); } } private static RemoteViews updateWidgetListView(Context context, int appWidgetId) { Intent svcIntent = null; remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget_demo); //RemoteViews Service needed to provide adapter for ListView svcIntent = new Intent(context, WidgetService.class); //passing app widget id to that RemoteViews Service svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); //setting a unique Uri to the intent //binding the data from the WidgetService to the svcIntent svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME))); //setting adapter to listview of the widget remoteViews.setRemoteAdapter(R.id.lv_tasks, svcIntent); //setting click listner on the "New Task" (TextView) of the widget remoteViews.setOnClickPendingIntent(R.id.tv_add_task, buildButtonPendingIntent(context)); return remoteViews; } // Just to create PendingIntent, this will be broadcasted everytime textview containing "New Task" is clicked and OnReceive method of MyWidgetIntentReceiver.java will run public static PendingIntent buildButtonPendingIntent(Context context) { Intent intent = new Intent(); intent.putExtra("TASK_DONE_VALUE_VALID", false); intent.setAction("com.ommzi.intent.action.CLEARTASK"); return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } // This method is defined here so that we can update the remoteviews from other classes as well, like we'll do it in MyWidgetIntentReceiver.java public static void pushWidgetUpdate(Context context, RemoteViews remoteViews) { ComponentName myWidget = new ComponentName(context, MyWidgetProvider.class); AppWidgetManager manager = AppWidgetManager.getInstance(context); manager.updateAppWidget(myWidget, remoteViews); } } WidgetService.java A RemoteViewsService class for creating a RemoteViewsFactory. public class WidgetService extends RemoteViewsService { @Override public RemoteViewsFactory onGetViewFactory(Intent intent) { int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,AppWidgetManager.INVALID_APPWIDGET_ID); return (new ListProvider(this.getApplicationContext(), intent)); } } ListProvider.java A RemoteViewsFactory class for filling the ListView inside the widget. public class ListProvider implements RemoteViewsFactory { private List<TemplateTaskData> tasks; private Context context = null; private int appWidgetId; int increment=0; public ListProvider(Context context, Intent intent) { this.context = context; appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,AppWidgetManager.INVALID_APPWIDGET_ID); //appWidgetId = Integer.valueOf(intent.getData().getSchemeSpecificPart())- MyWidgetProvider.randomNumber; populateListItem(); } private void populateListItem() { tasks = new ArrayList<TemplateTaskData>(); com.ommzi.database.sqliteDataBase letStartDB = new com.ommzi.database.sqliteDataBase(context); letStartDB.open(); tasks=letStartDB.getData(); letStartDB.close(); } public int getCount() { return tasks.size(); } public long getItemId(int position) { return position; } public RemoteViews getViewAt(int position) { // We are only showing the text view field here as there is limitation on using Checkbox within the widget // We prefer to on an activity for the user to make comprehensive changes as changes inside the widget is always limited. // To view the supported list of views for the widget you can visit http://developer.android.com/guide/topics/appwidgets/index.html final RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.screen_wcitem); TemplateTaskData taskDTO = tasks.get(position); Log.d("My ListProvider", "1"); remoteView.setTextViewText(R.id.wc_add_task, taskDTO.getTaskName()); if(taskDTO.getTaskDone()){ remoteView.setImageViewResource(R.id.imageView1, R.drawable.checked); }else{ remoteView.setImageViewResource(R.id.imageView1, R.drawable.unchecked); } Intent intent = new Intent(); intent.setAction("com.ommzi.intent.action.GETTASK"); intent.putExtra("TASK_DONE_VALUE_VALID", true); intent.putExtra("ROWID", taskDTO.getRowId()); intent.putExtra("TASK_NAME", taskDTO.getTaskName()); intent.putExtra("TASK_DONE_VALUE", taskDTO.getTaskDone()); remoteView.setOnClickPendingIntent(R.id.imageView1, PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)); Log.d("My ListProvider, Inside getView", "Value of Incrementor=" + increment + "\n ROWID=" + taskDTO.getRowId() + "\n TASK_NAME=" + taskDTO.getTaskName() + "\n TASK_DONE_VALUE=" +taskDTO.getTaskDone() + "\n Total Database Size=" + tasks.size()); return remoteView; } public RemoteViews getLoadingView() { // TODO Auto-generated method stub return null; } public int getViewTypeCount() { // TODO Auto-generated method stub return 1; } public boolean hasStableIds() { // TODO Auto-generated method stub return false; } public void onCreate() { // TODO Auto-generated method stub } public void onDataSetChanged() { // TODO Auto-generated method stub } public void onDestroy() { // TODO Auto-generated method stub } } GetTaskActivity.java This is another activity that is fired from a BroadcastReceiver(MyWidgetIntentReceiver.java). Purpose of this is to get a new task added to the list of task. MyWidgetIntentReceiver.java BroadcastReceiver fired using a pending intent that starts an activity GetTaskActivity.java. Please help me out with this problem. I am seen all the posts here and on other websites no body is having any solution. But I am sure a solution exist to this. Thanks for your help!

    Read the article

  • functional dependencies vs type families

    - by mhwombat
    I'm developing a framework for running experiments with artificial life, and I'm trying to use type families instead of functional dependencies. Type families seems to be the preferred approach among Haskellers, but I've run into a situation where functional dependencies seem like a better fit. Am I missing a trick? Here's the design using type families. (This code compiles OK.) {-# LANGUAGE TypeFamilies, FlexibleContexts #-} import Control.Monad.State (StateT) class Agent a where agentId :: a -> String liveALittle :: Universe u => a -> StateT u IO a -- plus other functions class Universe u where type MyAgent u :: * withAgent :: (MyAgent u -> StateT u IO (MyAgent u)) -> String -> StateT u IO () -- plus other functions data SimpleUniverse = SimpleUniverse { mainDir :: FilePath -- plus other fields } defaultWithAgent :: (MyAgent u -> StateT u IO (MyAgent u)) -> String -> StateT u IO () defaultWithAgent = undefined -- stub -- plus default implementations for other functions -- -- In order to use my framework, the user will need to create a typeclass -- that implements the Agent class... -- data Bug = Bug String deriving (Show, Eq) instance Agent Bug where agentId (Bug s) = s liveALittle bug = return bug -- stub -- -- .. and they'll also need to make SimpleUniverse an instance of Universe -- for their agent type. -- instance Universe SimpleUniverse where type MyAgent SimpleUniverse = Bug withAgent = defaultWithAgent -- boilerplate -- plus similar boilerplate for other functions Is there a way to avoid forcing my users to write those last two lines of boilerplate? Compare with the version using fundeps, below, which seems to make things simpler for my users. (The use of UndecideableInstances may be a red flag.) (This code also compiles OK.) {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, UndecidableInstances #-} import Control.Monad.State (StateT) class Agent a where agentId :: a -> String liveALittle :: Universe u a => a -> StateT u IO a -- plus other functions class Universe u a | u -> a where withAgent :: Agent a => (a -> StateT u IO a) -> String -> StateT u IO () -- plus other functions data SimpleUniverse = SimpleUniverse { mainDir :: FilePath -- plus other fields } instance Universe SimpleUniverse a where withAgent = undefined -- stub -- plus implementations for other functions -- -- In order to use my framework, the user will need to create a typeclass -- that implements the Agent class... -- data Bug = Bug String deriving (Show, Eq) instance Agent Bug where agentId (Bug s) = s liveALittle bug = return bug -- stub -- -- And now my users only have to write stuff like... -- u :: SimpleUniverse u = SimpleUniverse "mydir"

    Read the article

  • On screen orientation loads again data with Async Task

    - by Zookey
    I make Android application with master/detail pattern. So I have ListActivity class which is FragmentActivity and ListFragment class which is Fragment It all works perfect, but when I change screen orientation it calls again AsyncTask and reload all data. Here is the code for ListActivity class where I handle all logic: @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); getActionBar().setTitle("Dnevni horoskop"); if(findViewById(R.id.details_container) != null){ //Tablet mTwoPane = true; //Fragment stuff FragmentManager fm = getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); DetailsFragment df = new DetailsFragment(); ft.add(R.id.details_container, df); ft.commit(); } pb = (ProgressBar) findViewById(R.id.pb_list); tvNoConnection = (TextView) findViewById(R.id.tv_no_internet); ivNoConnection = (ImageView) findViewById(R.id.iv_no_connection); list = (GridView) findViewById(R.id.gv_list); if(mTwoPane == true){ list.setNumColumns(1); //list.setPadding(16,16,16,16); } adapter = new CustomListAdapter(); list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { pos = position; if(mTwoPane == false){ Bundle bundle = new Bundle(); bundle.putSerializable("zodiac", zodiacFeed); Intent i = new Intent(getApplicationContext(), DetailsActivity.class); i.putExtra("position", position); i.putExtras(bundle); startActivity(i); overridePendingTransition(R.anim.right_in, R.anim.right_out); } else if(mTwoPane == true){ DetailsFragment fragment = (DetailsFragment) getSupportFragmentManager().findFragmentById(R.id.details_container); fragment.setHoroscopeText(zodiacFeed.getItem(position).getText()); fragment.setLargeImage(zodiacFeed.getItem(position).getLargeImage()); fragment.setSign("Dnevni horoskop - "+zodiacFeed.getItem(position).getName()); fragment.setSignDuration(zodiacFeed.getItem(position).getDuration()); // inflate menu from xml /*if(menu != null){ MenuItem item = menu.findItem(R.id.share); Toast.makeText(getApplicationContext(), item.getTitle().toString(), Toast.LENGTH_SHORT).show(); }*/ } } }); if(!Utils.isConnected(getApplicationContext())){ pb.setVisibility(View.GONE); tvNoConnection.setVisibility(View.VISIBLE); ivNoConnection.setVisibility(View.VISIBLE); } //Calling AsyncTask to load data Log.d("TAG", "loading"); HoroscopeAsyncTask task = new HoroscopeAsyncTask(pb); task.execute(); } @Override public void onConfigurationChanged(Configuration newConfig) { // TODO Auto-generated method stub super.onConfigurationChanged(newConfig); } class CustomListAdapter extends BaseAdapter { private LayoutInflater layoutInflater; public CustomListAdapter() { layoutInflater = (LayoutInflater) getBaseContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { // TODO Auto-generated method stub // Set the total list item count return names.length; } public Object getItem(int arg0) { // TODO Auto-generated method stub return null; } public long getItemId(int arg0) { // TODO Auto-generated method stub return 0; } public View getView(int position, View convertView, ViewGroup parent) { // Inflate the item layout and set the views View listItem = convertView; int pos = position; zodiacItem = zodiacList.get(pos); if (listItem == null && mTwoPane == false) { listItem = layoutInflater.inflate(R.layout.list_item, null); } else if(mTwoPane == true){ listItem = layoutInflater.inflate(R.layout.tablet_list_item, null); } // Initialize the views in the layout ImageView iv = (ImageView) listItem.findViewById(R.id.iv_horoscope); iv.setScaleType(ScaleType.CENTER_CROP); TextView tvName = (TextView) listItem.findViewById(R.id.tv_zodiac_name); TextView tvDuration = (TextView) listItem.findViewById(R.id.tv_duration); iv.setImageResource(zodiacItem.getImage()); tvName.setText(zodiacItem.getName()); tvDuration.setText(zodiacItem.getDuration()); Animation animation = AnimationUtils.loadAnimation(getBaseContext(), R.anim.push_up); listItem.startAnimation(animation); animation = null; return listItem; } } private void getHoroscope() { String urlString = "http://balkanandroid.com/download/horoskop/examples/dnevnihoroskop.php"; try { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(urlString); HttpResponse response = client.execute(post); resEntity = response.getEntity(); response_str = EntityUtils.toString(resEntity); if (resEntity != null) { Log.i("RESPONSE", response_str); runOnUiThread(new Runnable() { public void run() { try { Log.d("TAG", "Response from server : n " + response_str); } catch (Exception e) { e.printStackTrace(); } } }); } } catch (Exception ex) { Log.e("TAG", "error: " + ex.getMessage(), ex); } } private class HoroscopeAsyncTask extends AsyncTask<String, Void, Void> { public HoroscopeAsyncTask(ProgressBar pb1){ pb = pb1; } @Override protected void onPreExecute() { pb.setVisibility(View.VISIBLE); super.onPreExecute(); } @Override protected Void doInBackground(String... params) { getHoroscope(); try { Log.d("TAG", "test u try"); JSONObject jsonObject = new JSONObject(response_str); JSONArray jsonArray = jsonObject.getJSONArray("horoscope"); for(int i=0;i<jsonArray.length();i++){ Log.d("TAG", "test u for"); JSONObject horoscopeObj = jsonArray.getJSONObject(i); String horoscopeSign = horoscopeObj.getString("name_sign"); String horoscopeText = horoscopeObj.getString("txt_hrs"); zodiacItem = new ZodiacItem(horoscopeSign, horoscopeText, duration[i], images[i], largeImages[i]); zodiacList.add(zodiacItem); zodiacFeed.addItem(zodiacItem); //Treba u POJO klasu ubaciti sve. Log.d("TAG", "ZNAK: "+zodiacItem.getName()+" HOROSKOP: "+zodiacItem.getText()); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.e("TAG", "error: " + e.getMessage(), e); } return null; } @Override protected void onPostExecute(Void result) { pb.setVisibility(View.GONE); list.setAdapter(adapter); adapter.notifyDataSetChanged(); super.onPostExecute(result); } } Here is the code for ListFragment class: public class ListFragment extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub // Retain this fragment across configuration changes. setRetainInstance(true); super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view = inflater.inflate(R.layout.fragment_list, container, false); return view; } }

    Read the article

  • Program crashes when item selected from listView

    - by philip
    The application just crash every time I try to click from the list. ListMovingNames.java public class ListMovingNames extends Activity { ListView MoveList; SQLHandler SQLHandlerview; Cursor cursor; Button addMove; EditText etAddMove; TextView temp; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.selectorcreatemove); addMove = (Button) findViewById(R.id.bAddMove); etAddMove = (EditText) findViewById(R.id.etMoveName); temp = (TextView) findViewById(R.id.tvTemp); MoveList = (ListView) findViewById(R.id.lvMoveItems); SQLHandlerview = new SQLHandler(this); SQLHandlerview = new SQLHandler(ListMovingNames.this); SQLHandlerview.open(); cursor = SQLHandlerview.getMove(); startManagingCursor(cursor); String[] from = new String[]{SQLHandler.KEY_MOVENAME}; int[] to = new int[]{R.id.text}; SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to); MoveList.setAdapter(cursorAdapter); SQLHandlerview.close(); addMove.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub try { String ssmoveName = etAddMove.getText().toString(); SQLHandler entry = new SQLHandler(ListMovingNames.this); entry.open(); entry.createMove(ssmoveName); entry.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); MoveList.setOnItemClickListener(new OnItemClickListener() { @SuppressLint("ShowToast") public void onItemClick(AdapterView<?> arg0, View view, int position, long id) { // TODO Auto-generated method stub // String moveset = cursor.getString(position); // temp.setText(moveset); Toast.makeText(ListMovingNames.this, position, Toast.LENGTH_SHORT); } }); } } and here's my database handler. But I'm sure that there's nothing wrong with it, its probably the cursor adapter. SQLHandler.java public class SQLHandler { public static final String KEY_ROOMMOVEHOLDER = "roommoveholder"; public static final String KEY_ROOM = "room"; public static final String KEY_ITEMMOVEHOLDER = "itemmoveholder"; public static final String KEY_ITEMNAME = "itemname"; public static final String KEY_ITEMVALUE = "itemvalue"; public static final String KEY_ROOMHOLDER = "roomholder"; public static final String KEY_MOVENAME = "movename"; public static final String KEY_ID1 = "_id"; public static final String KEY_ID2 = "_id"; public static final String KEY_ID3 = "_id"; public static final String KEY_ID4 = "_id"; public static final String KEY_MOVEDATE = "movedate"; private static final String DATABASE_NAME = "mymovingfriend"; private static final int DATABASE_VERSION = 1; public static final String KEY_SORTANDPURGE = "sortandpurge"; public static final String KEY_RESEARCH = "research"; public static final String KEY_CREATEMOVINGBINDER = "createmovingbinder"; public static final String KEY_ORDERSUPPLIES = "ordersupplies"; public static final String KEY_USEITORLOSEIT = "useitorloseit"; public static final String KEY_TAKEMEASUREMENTS = "takemeasurements"; public static final String KEY_CHOOSEMOVER = "choosemover"; public static final String KEY_BEGINPACKING = "beginpacking"; public static final String KEY_LABEL = "label"; public static final String KEY_SEPARATEVALUES = "separatevalues"; public static final String KEY_DOACHANGEOFADDRESS = "doachangeofaddress"; public static final String KEY_NOTIFYIMPORTANTPARTIES = "notifyimportantparties"; private static final String DATABASE_TABLE1 = "movingname"; private static final String DATABASE_TABLE2 = "movingrooms"; private static final String DATABASE_TABLE3 = "movingitems"; private static final String DATABASE_TABLE4 = "todolist"; public static final String CREATE_TABLE_1 = "CREATE TABLE " + DATABASE_TABLE1 + " (" + KEY_ID1 + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_MOVEDATE + " TEXT NOT NULL, " + KEY_MOVENAME + " TEXT NOT NULL);"; public static final String CREATE_TABLE_2 = "CREATE TABLE " + DATABASE_TABLE2 + " (" + KEY_ID2 + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_ROOMMOVEHOLDER + " TEXT NOT NULL, " + KEY_ROOM + " TEXT NOT NULL);"; public static final String CREATE_TABLE_3 = "CREATE TABLE " + DATABASE_TABLE3 + " (" + KEY_ID3 + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_ITEMNAME + " TEXT NOT NULL, " + KEY_ITEMVALUE + " TEXT NOT NULL, " + KEY_ROOMHOLDER + " TEXT NOT NULL, " + KEY_ITEMMOVEHOLDER + " TEXT NOT NULL);"; public static final String CREATE_TABLE_4 = "CREATE TABLE " + DATABASE_TABLE4 + " (" + KEY_ID4 + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_SORTANDPURGE + " TEXT NOT NULL, " + KEY_RESEARCH + " INTEGER NOT NULL, " + KEY_CREATEMOVINGBINDER + " TEXT NOT NULL, " + KEY_ORDERSUPPLIES + " TEXT NOT NULL, " + KEY_USEITORLOSEIT + " TEXT NOT NULL, " + KEY_TAKEMEASUREMENTS + " TEXT NOT NULL, " + KEY_CHOOSEMOVER + " TEXT NOT NULL, " + KEY_BEGINPACKING + " TEXT NOT NULL, " + KEY_LABEL + " TEXT NOT NULL, " + KEY_SEPARATEVALUES + " TEXT NOT NULL, " + KEY_DOACHANGEOFADDRESS + " TEXT NOT NULL, " + KEY_NOTIFYIMPORTANTPARTIES + " TEXT NOT NULL);"; private DbHelper ourHelper; private final Context ourContext; private SQLiteDatabase ourDatabase; private static class DbHelper extends SQLiteOpenHelper{ public DbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL(CREATE_TABLE_1); db.execSQL(CREATE_TABLE_2); db.execSQL(CREATE_TABLE_3); db.execSQL(CREATE_TABLE_4); } @Override public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) { // TODO Auto-generated method stub db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE1); db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE2); db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE3); db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE4); onCreate(db); } } public SQLHandler(Context c){ ourContext = c; } public SQLHandler open() throws SQLException{ ourHelper = new DbHelper(ourContext); ourDatabase = ourHelper.getWritableDatabase(); return this; } public void close(){ ourHelper.close(); } public long createMove(String smovename){ ContentValues cv = new ContentValues(); cv.put(KEY_MOVENAME, smovename); cv.put(KEY_MOVEDATE, "Not yet set"); return ourDatabase.insert(DATABASE_TABLE1, null, cv); } public long addRooms(String sroommoveholder, String sroom){ ContentValues cv = new ContentValues(); cv.put(KEY_ROOMMOVEHOLDER, sroommoveholder); cv.put(KEY_ROOM, sroom); return ourDatabase.insert(DATABASE_TABLE2, null, cv); } public long addItems(String sitemmoveholder, String sroomholder, String sitemname, String sitemvalue){ ContentValues cv = new ContentValues(); cv.put(KEY_ITEMMOVEHOLDER, sitemmoveholder); cv.put(KEY_ROOMHOLDER, sroomholder); cv.put(KEY_ITEMNAME, sitemname); cv.put(KEY_ITEMVALUE, sitemvalue); return ourDatabase.insert(DATABASE_TABLE3, null, cv); } public long todoList(String todoitem){ ContentValues cv = new ContentValues(); cv.put(todoitem, "Done"); return ourDatabase.insert(DATABASE_TABLE4, null, cv); } public Cursor getMove(){ String[] columns = new String[]{KEY_ID1, KEY_MOVENAME}; Cursor cursor = ourDatabase.query(DATABASE_TABLE1, columns, null, null, null, null, null); return cursor; } } can anyone point out what I'm doing wrong? here's the log 09-19 03:22:36.596: E/AndroidRuntime(679): FATAL EXCEPTION: main 09-19 03:22:36.596: E/AndroidRuntime(679): android.content.res.Resources$NotFoundException: String resource ID #0x0 09-19 03:22:36.596: E/AndroidRuntime(679): at android.content.res.Resources.getText(Resources.java:201) 09-19 03:22:36.596: E/AndroidRuntime(679): at android.widget.Toast.makeText(Toast.java:258) 09-19 03:22:36.596: E/AndroidRuntime(679): at standard.internet.marketing.mymovingfriend.ListMovingNames$2.onItemClick(ListMovingNames.java:78) 09-19 03:22:36.596: E/AndroidRuntime(679): at android.widget.AdapterView.performItemClick(AdapterView.java:284) 09-19 03:22:36.596: E/AndroidRuntime(679): at android.widget.ListView.performItemClick(ListView.java:3382) 09-19 03:22:36.596: E/AndroidRuntime(679): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1696) 09-19 03:22:36.596: E/AndroidRuntime(679): at android.os.Handler.handleCallback(Handler.java:587) 09-19 03:22:36.596: E/AndroidRuntime(679): at android.os.Handler.dispatchMessage(Handler.java:92) 09-19 03:22:36.596: E/AndroidRuntime(679): at android.os.Looper.loop(Looper.java:123) 09-19 03:22:36.596: E/AndroidRuntime(679): at android.app.ActivityThread.main(ActivityThread.java:4627) 09-19 03:22:36.596: E/AndroidRuntime(679): at java.lang.reflect.Method.invokeNative(Native Method) 09-19 03:22:36.596: E/AndroidRuntime(679): at java.lang.reflect.Method.invoke(Method.java:521) 09-19 03:22:36.596: E/AndroidRuntime(679): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 09-19 03:22:36.596: E/AndroidRuntime(679): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 09-19 03:22:36.596: E/AndroidRuntime(679): at dalvik.system.NativeStart.main(Native Method)

    Read the article

  • Is there any way to add a MouseListener to a Graphic object ?

    - by Fahad
    Hi, Is there any way to add a MouseListener to a Graphic object. I have this simple GUI that draw an oval. What I want is handling the event when the user clicks on the oval import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.*; public class Gui2 extends JFrame { JFrame frame = new JFrame(); MyDrawPanel drawpanel = new MyDrawPanel(); public static void main(String[] args) { Gui2 gui = new Gui2(); gui.go(); } public void go() { frame.getContentPane().add(drawpanel); // frame.addMouseListener(this); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 300); frame.setVisible(true); } } class MyDrawPanel extends JComponent implements MouseListener { public void paintComponent(Graphics g) { int red = (int) (Math.random() * 255); int green = (int) (Math.random() * 255); int blue = (int) (Math.random() * 255); Color startrandomColor = new Color(red, green, blue); red = (int) (Math.random() * 255); green = (int) (Math.random() * 255); blue = (int) (Math.random() * 255); Color endrandomColor = new Color(red, green, blue); Graphics2D g2d = (Graphics2D) g; this.addMouseListener(this); GradientPaint gradient = new GradientPaint(70, 70, startrandomColor, 150, 150, endrandomColor); g2d.setPaint(gradient); g2d.fillOval(70, 70, 100, 100); } @Override public void mouseClicked(MouseEvent e) { if ((e.getButton() == 1) && (e.getX() >= 70 && e.getX() <= 170 && e.getY() >= 70 && e .getY() <= 170)) { this.repaint(); // JOptionPane.showMessageDialog(null,e.getX()+ "\n" + e.getY()); } } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } } This Works Except it fires when the click is within a virtual box around the oval. Could anyone help me to have it fire when the click is EXACTLY on the oval. Thanks in advance.

    Read the article

  • Performance issues in android game

    - by user1446632
    I am making an android game, but however, the game is functioning like it should, but i am experiencing some performance issues. I think it has something to do with the sound. Cause each time i touch the screen, it makes a sound. I am using the standard MediaPlayer. The method is onTouchEvent() and onPlaySound1(). Could you please help me with an alternate solution for playing the sound? Thank you so much in advance! It would be nice if you also came up with some suggestions on how i can improve my code. Take a look at my code here: package com.mycompany.mygame; import java.util.ArrayList; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.media.MediaPlayer; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.webkit.WebView; import android.widget.TextView; import android.widget.Toast; public class ExampleView extends SurfaceView implements SurfaceHolder.Callback { class ExampleThread extends Thread { private ArrayList<Parachuter> parachuters; private Bitmap parachuter; private Bitmap background; private Paint black; private boolean running; private SurfaceHolder mSurfaceHolder; private Context mContext; private Context mContext1; private Handler mHandler; private Handler mHandler1; private GameScreenActivity mActivity; private long frameRate; private boolean loading; public float x; public float y; public float x1; public float y1; public MediaPlayer mp1; public MediaPlayer mp2; public int parachuterIndexToResetAndDelete; public int canvasGetWidth; public int canvasGetWidth1; public int canvasGetHeight; public int livesLeftValue; public int levelValue = 1; public int levelValue1; public int parachutersDown; public int difficultySet; public boolean isSpecialAttackAvailible; public ExampleThread(SurfaceHolder sHolder, Context context, Handler handler) { mSurfaceHolder = sHolder; mHandler = handler; mHandler1 = handler; mContext = context; mActivity = (GameScreenActivity) context; parachuters = new ArrayList<Parachuter>(); parachuter = BitmapFactory.decodeResource(getResources(), R.drawable.parachuteman); black = new Paint(); black.setStyle(Paint.Style.FILL); black.setColor(Color.GRAY); background = BitmapFactory.decodeResource(getResources(), R.drawable.gamescreenbackground); running = true; // This equates to 26 frames per second. frameRate = (long) (1000 / 26); loading = true; mp1 = MediaPlayer.create(getContext(), R.raw.bombsound); } @Override public void run() { while (running) { Canvas c = null; try { c = mSurfaceHolder.lockCanvas(); synchronized (mSurfaceHolder) { long start = System.currentTimeMillis(); doDraw(c); long diff = System.currentTimeMillis() - start; if (diff < frameRate) Thread.sleep(frameRate - diff); } } catch (InterruptedException e) { } finally { if (c != null) { mSurfaceHolder.unlockCanvasAndPost(c); } } } } protected void doDraw(Canvas canvas) { canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), black); //Draw for (int i = 0; i < parachuters.size(); i++) { canvas.drawBitmap(parachuter, parachuters.get(i).getX(), parachuters.get(i).getY(), null); parachuters.get(i).tick(); } //Remove for (int i = 0; i < parachuters.size(); i++) { if (parachuters.get(i).getY() > canvas.getHeight()) { parachuters.remove(i); onPlaySound(); checkLivesLeftValue(); checkAmountOfParachuters(); } else if(parachuters.get(i).isTouched()) { parachuters.remove(i); } else{ //Do nothing } } } public void loadBackground(Canvas canvas) { //Load background canvas.drawBitmap(background, 0, 0, black); } public void checkAmountOfParachuters() { mHandler.post(new Runnable() { @Override public void run() { if(parachuters.isEmpty()) { levelValue = levelValue + 1; Toast.makeText(getContext(), "New level! " + levelValue, 15).show(); if (levelValue == 3) { drawParachutersGroup1(); drawParachutersGroup2(); drawParachutersGroup3(); drawParachutersGroup4(); } else if (levelValue == 5) { drawParachutersGroup1(); drawParachutersGroup2(); drawParachutersGroup3(); drawParachutersGroup4(); drawParachutersGroup5(); } else if (levelValue == 7) { drawParachutersGroup1(); drawParachutersGroup2(); drawParachutersGroup3(); drawParachutersGroup4(); drawParachutersGroup5(); drawParachutersGroup6(); } else if (levelValue == 9) { //Draw 7 groups of parachuters drawParachutersGroup1(); drawParachutersGroup2(); drawParachutersGroup3(); drawParachutersGroup4(); drawParachutersGroup5(); drawParachutersGroup6(); drawParachutersGroup1(); } else if (levelValue > 9) { //Draw 7 groups of parachuters drawParachutersGroup1(); drawParachutersGroup2(); drawParachutersGroup3(); drawParachutersGroup4(); drawParachutersGroup5(); drawParachutersGroup6(); drawParachutersGroup1(); } else { //Draw normal 3 groups of parachuters drawParachutersGroup1(); drawParachutersGroup2(); drawParachutersGroup3(); } } else { //Do nothing } } }); } private void checkLivesLeftValue() { mHandler.post(new Runnable() { @Override public void run() { Log.d("checkLivesLeftValue", "lives = " + livesLeftValue); // TODO Auto-generated method stub if (livesLeftValue == 3) { //Message to display: "You lost! Log.d("checkLivesLeftValue", "calling onMethod now"); parachuters.removeAll(parachuters); onMethod(); } else if (livesLeftValue == 2) { Toast.makeText(getContext(), "Lives left=1", 15).show(); livesLeftValue = livesLeftValue + 1; Log.d("checkLivesLeftValue", "increased lives to " + livesLeftValue); } else if (livesLeftValue == 1) { Toast.makeText(getContext(), "Lives left=2", 15).show(); livesLeftValue = livesLeftValue + 1; Log.d("checkLivesLeftValue", "increased lives to " + livesLeftValue); } else { //Set livesLeftValueText 3 Toast.makeText(getContext(), "Lives left=3", 15).show(); livesLeftValue = livesLeftValue + 1; Log.d("checkLivesLeftValue", "increased lives to " + livesLeftValue); } } }); } public void onMethod() { mHandler.post(new Runnable() { @Override public void run() { try { Toast.makeText(getContext(), "You lost!", 15).show(); livesLeftValue = 0; //Tell the user that he lost: android.content.Context ctx = mContext; Intent i = new Intent(ctx, playerLostMessageActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra("KEY","You got to level " + levelValue + " And you shot down " + parachutersDown + " parachuters"); i.putExtra("levelValue", levelValue); ctx.startActivity(i); System.exit(0); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); //Exit activity and start playerLostMessageActivity Toast.makeText(getContext(), "You lost!", 15).show(); livesLeftValue = 0; //Tell the user that he lost: android.content.Context ctx = mContext; Intent i = new Intent(ctx, playerLostMessageActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra("KEY","You got to level " + levelValue + " And you shot down " + parachutersDown + " parachuters"); i.putExtra("levelValue", levelValue); System.exit(0); ctx.startActivity(i); System.exit(0); } } }); } public void onPlaySound() { try { mp1.start(); } catch (Exception e) { e.printStackTrace(); mp1.release(); } } public void onDestroy() { try { parachuters.removeAll(parachuters); mp1.stop(); mp1.release(); } catch (Exception e) { e.printStackTrace(); } } public void onPlaySound1() { try { mp2 = MediaPlayer.create(getContext(), R.raw.airriflesoundeffect); mp2.start(); } catch (Exception e) { e.printStackTrace(); mp2.release(); } } public boolean onTouchEvent(MotionEvent event) { if (event.getAction() != MotionEvent.ACTION_DOWN) releaseMediaPlayer(); x1 = event.getX(); y1 = event.getY(); checkAmountOfParachuters(); removeParachuter(); return false; } public void releaseMediaPlayer() { try { mp1.release(); } catch (Exception e) { e.printStackTrace(); } } public void removeParachuter() { try { for (Parachuter p: parachuters) { if (x1 > p.getX() && x1 < p.getX() + parachuter.getWidth() && y1 > p.getY() && y1 < p.getY() + parachuter.getHeight()) { p.setTouched(true); onPlaySound1(); parachutersDown = parachutersDown + 1; p.setTouched(false); } } } catch (Exception e) { e.printStackTrace(); } } public void initiateDrawParachuters() { drawParachutersGroup1(); } public void drawParachutersGroup1() { // TODO Auto-generated method stub //Parachuter group nr. 1 //Parachuter nr. 2 x = 75; y = 77; Parachuter p1 = new Parachuter(x, y); parachuters.add(p1); //Parachuter nr.1 x = 14; y = 28; Parachuter p = new Parachuter(x, y); parachuters.add(p); //Parachuter nr. 3 x = 250; y = 94; Parachuter p3 = new Parachuter(x, y); parachuters.add(p3); //Parachuter nr. 3 x = 275; y = 80; Parachuter p2 = new Parachuter(x, y); parachuters.add(p2); //Parachuter nr. 5 x = 280; y = 163; Parachuter p5 = new Parachuter(x, y); parachuters.add(p5); x = 125; y = 118; Parachuter p4 = new Parachuter(x, y); parachuters.add(p4); //Parachuter nr. 7 x = 126; y = 247; Parachuter p7 = new Parachuter(x, y); parachuters.add(p7); //Parachuter nr. 6 x = 123; y = 77; Parachuter p6 = new Parachuter(x, y); parachuters.add(p6); } public void drawParachutersGroup2() { // TODO Auto-generated method stub //Parachuter group nr. 2 //Parachuter nr. 5 x = 153; y = 166; Parachuter p5 = new Parachuter(x, y); parachuters.add(p5); x = 133; y = 123; Parachuter p4 = new Parachuter(x, y); parachuters.add(p4); //Parachuter nr. 7 x = 170; y = 213; Parachuter p7 = new Parachuter(x, y); parachuters.add(p7); //Parachuter nr. 6 x = 190; y = 121; Parachuter p6 = new Parachuter(x, y); parachuters.add(p6); } public void drawParachutersGroup3() { // TODO Auto-generated method stub //Parachuter group nr. 3 //Parachuter nr. 2 x = 267; y = 115; Parachuter p1 = new Parachuter(x, y); parachuters.add(p1); //Parachuter nr.1 x = 255; y = 183; Parachuter p = new Parachuter(x, y); parachuters.add(p); //Parachuter nr. 3 x = 170; y = 280; Parachuter p3 = new Parachuter(x, y); parachuters.add(p3); //Parachuter nr. 3 x = 116; y = 80; Parachuter p2 = new Parachuter(x, y); parachuters.add(p2); //Parachuter nr. 5 x = 67; y = 112; Parachuter p5 = new Parachuter(x, y); parachuters.add(p5); x = 260; y = 89; Parachuter p4 = new Parachuter(x, y); parachuters.add(p4); //Parachuter nr. 7 x = 260; y = 113; Parachuter p7 = new Parachuter(x, y); parachuters.add(p7); //Parachuter nr. 6 x = 178; y = 25; Parachuter p6 = new Parachuter(x, y); parachuters.add(p6); } public void drawParachutersGroup4() { // TODO Auto-generated method stub //Parachuter group nr. 1 //Parachuter nr. 2 x = 75; y = 166; Parachuter p1 = new Parachuter(x, y); parachuters.add(p1); //Parachuter nr.1 x = 118; y = 94; Parachuter p = new Parachuter(x, y); parachuters.add(p); //Parachuter nr. 3 x = 38; y = 55; Parachuter p3 = new Parachuter(x, y); parachuters.add(p3); //Parachuter nr. 3 x = 57; y = 18; Parachuter p2 = new Parachuter(x, y); parachuters.add(p2); //Parachuter nr. 5 x = 67; y = 119; Parachuter p5 = new Parachuter(x, y); parachuters.add(p5); x = 217; y = 113; Parachuter p4 = new Parachuter(x, y); parachuters.add(p4); //Parachuter nr. 7 x = 245; y = 234; Parachuter p7 = new Parachuter(x, y); parachuters.add(p7); //Parachuter nr. 6 x = 239; y = 44; Parachuter p6 = new Parachuter(x, y); parachuters.add(p6); } public void drawParachutersGroup5() { // TODO Auto-generated method stub //Parachuter group nr. 1 //Parachuter nr. 2 x = 59; y = 120; Parachuter p1 = new Parachuter(x, y); parachuters.add(p1); //Parachuter nr.1 x = 210; y = 169; Parachuter p = new Parachuter(x, y); parachuters.add(p); //Parachuter nr. 3 x = 199; y = 138; Parachuter p3 = new Parachuter(x, y); parachuters.add(p3); //Parachuter nr. 3 x = 22; y = 307; Parachuter p2 = new Parachuter(x, y); parachuters.add(p2); //Parachuter nr. 5 x = 195; y = 22; Parachuter p5 = new Parachuter(x, y); parachuters.add(p5); x = 157; y = 132; Parachuter p4 = new Parachuter(x, y); parachuters.add(p4); //Parachuter nr. 7 x = 150; y = 183; Parachuter p7 = new Parachuter(x, y); parachuters.add(p7); //Parachuter nr. 6 x = 130; y = 20; Parachuter p6 = new Parachuter(x, y); parachuters.add(p6); } public void drawParachutersGroup6() { // TODO Auto-generated method stub //Parachuter group nr. 1 //Parachuter nr. 2 x = 10; y = 10; Parachuter p1 = new Parachuter(x, y); parachuters.add(p1); //Parachuter nr.1 x = 20; y = 20; Parachuter p = new Parachuter(x, y); parachuters.add(p); //Parachuter nr. 3 x = 30; y = 30; Parachuter p3 = new Parachuter(x, y); parachuters.add(p3); //Parachuter nr. 3 x = 60; y = 60; Parachuter p2 = new Parachuter(x, y); parachuters.add(p2); //Parachuter nr. 5 x = 90; y = 90; Parachuter p5 = new Parachuter(x, y); parachuters.add(p5); x = 120; y = 120; Parachuter p4 = new Parachuter(x, y); parachuters.add(p4); //Parachuter nr. 7 x = 150; y = 150; Parachuter p7 = new Parachuter(x, y); parachuters.add(p7); //Parachuter nr. 6 x = 180; y = 180; Parachuter p6 = new Parachuter(x, y); parachuters.add(p6); } public void drawParachuters() { Parachuter p = new Parachuter(x, y); parachuters.add(p); Toast.makeText(getContext(), "x=" + x + " y=" + y, 15).show(); } public void setRunning(boolean bRun) { running = bRun; } public boolean getRunning() { return running; } } /** Handle to the application context, used to e.g. fetch Drawables. */ private Context mContext; /** Pointer to the text view to display "Paused.." etc. */ private TextView mStatusText; /** The thread that actually draws the animation */ private ExampleThread eThread; public ExampleView(Context context) { super(context); // register our interest in hearing about changes to our surface SurfaceHolder holder = getHolder(); holder.addCallback(this); // create thread only; it's started in surfaceCreated() eThread = new ExampleThread(holder, context, new Handler() { @Override public void handleMessage(Message m) { // mStatusText.setVisibility(m.getData().getInt("viz")); // mStatusText.setText(m.getData().getString("text")); } }); setFocusable(true); } @Override public boolean onTouchEvent(MotionEvent event) { return eThread.onTouchEvent(event); } public ExampleThread getThread() { return eThread; } @Override public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } public void surfaceCreated(SurfaceHolder holder) { if (eThread.getState() == Thread.State.TERMINATED) { eThread = new ExampleThread(getHolder(), getContext(), getHandler()); eThread.start(); } else { eThread.start(); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; eThread.setRunning(false); while (retry) { try { eThread.join(); retry = false; } catch (InterruptedException e) { } } } }

    Read the article

  • Visual Studio code generated when choosing to explicitly implement interface

    - by fearofawhackplanet
    Sorry for the vague title, but I'm not sure what this is called. Say I add IDisposable to my class, Visual Studio can create the method stub for me. But it creates the stub like: void IDisposable.Dispose() I don't follow what this syntax is doing. Why do it like this instead of public void Dispose()? And with the first syntax, I couldn't work out how to call Dispose() from within my class (in my destructor).

    Read the article

  • Deleting document attachments in CouchDb

    - by henrik_lundgren
    In CouchDb's documentation, the described method of deleting document attachments is to send a DELETE call to the attachment's url. However, I have noticed that if you edit the document and remove the attachment stub from the _attachment field, it will not be accessible anymore. If i remove foo.txt from the document below and save to CouchDb it will be gone the next time I access the document: { "_id":"attachment_doc", "_rev":1589456116, "_attachments": { "foo.txt": { "stub":true, "content_type":"text/plain", "length":29 } } } Is the attachment actually deleted on disk or is just the reference to it deleted?

    Read the article

  • Slick2d/Nifty-gui input

    - by eerongal
    I'm trying to get input from slick2d into nifty gui. Ive searched online, and I've seen a few examples, but I can't seem to get it working right. i've tried the example on here but I can't seem to get everything working. I'm not entirely sure what I'm doing wrong. I've also looked at examples using the JMonkeyEngine to help point me in the right direction, but still having issues with input. I can get everything else working like i need. Here's the code for my element controller: package gui; import java.util.Properties; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.controls.Controller; import de.lessvoid.nifty.elements.Element; import de.lessvoid.nifty.input.NiftyInputEvent; import de.lessvoid.nifty.screen.Screen; import de.lessvoid.xml.xpp3.Attributes; public class BaseElementController implements Controller { private Element element; public void bind(Nifty arg0, Screen arg1, Element arg2, Properties arg3, Attributes arg4) { this.element = element; } public void init(Properties arg0, Attributes arg1) { // TODO Auto-generated method stub } public boolean inputEvent(NiftyInputEvent arg0) { // TODO Auto-generated method stub return false; } public void onFocus(boolean arg0) { // TODO Auto-generated method stub } public void onStartScreen() { // TODO Auto-generated method stub } public void test() { System.out.println("test"); } public void bam() { System.out.println("bam"); } } Here's my XML file: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <nifty> <useStyles filename="nifty-default-styles.xml"/> <useControls filename="nifty-default-controls.xml"/> <screen id="screen2" controller="gui.BaseScreenController"> <layer backgroundColor="#fff0" childLayout="absolute" id="layer4" controller="gui.BaseElementController"> <panel childLayout="center" height="30%" id="panel1" style="nifty-panel-simple" width="50%" x="282" y="334" controller="gui.BaseElementController"> <control id="checkbox1" name="checkbox"/> <control childLayout="center" id="button2" label="button2" name="button" x="381" y="224" visibleToMouse="true" controller="gui.BaseElementController"> <interact onClick="bam()"/> </control> </panel> <text text="${CALL.getPlayerName()}" style="nifty-label" width="100%" height="100%" x="0" y="10" /> </layer> </screen> </nifty> Here's how I'm trying to bind the controller: public void init(GameContainer gc) throws SlickException { Input input = gc.getInput(); inputSystem = new PlainSlickInputSystem(); inputSystem.setInput(input); gui = new Gui(); gui.init(gc, inputSystem, "gui/tset.xml", "screen2"); input.removeListener(this); input.removeListener(inputSystem); input.addListener(inputSystem); } Essentially, all that happens right now is the screen loads up and displays, and it grabs the variable correctly in the label, but none of the input seems to be getting forwarded to Nifty from slick. I assume there's something I'm missing, but I can't seem to figure out what that is. In so far as what I have tried, I attempted to define a custom input listener to pick up events and assign that to my game in order to pick up input, which did not work, so i dropped that implementation, at current i'm trying to take the default inputs and bind then with a PlainSlickInputSystem and assigning that to the input (as shown in the first example link). On code execution, all the code is hit, and i've put several system.out.println's to get ouput of what is happening (the code above has been cleaned for presentation), and i even see the elements getting bound to the controller, yet it doesn't pick up controller events. As far as EXACTLY what's wrong, that I don't know, because I've followed all implementations i can find of this, and none of them seem to do anything it's like the input is just getting thrown out. None of the objects from niftyGui appear to be recognizing any input. Here is the binding from my objects at run time: ******INITIALIZED SCREEN: de.lessvoid.nifty.screen.Screen@4a1ab1c1 ******INITIALIZED ELEMENT: button2 (de.lessvoid.nifty.elements.Element@1e8c1be9) ******INITIALIZED ELEMENT: focusable => true, width => 100px {nifty-button#panel}, backgroundImage => button/button.png {nifty-button#panel}, label => button2, paddingLeft => 7px {nifty-button#panel}, imageMode => sprite-resize:100,23,0,2,96,2,2,2,96,2,19,2,96,2,2 {nifty-button#panel}, paddingRight => 7px {nifty-button#panel}, id => button2, visibleToMouse => true, height => 23px {nifty-button#panel}, style => nifty-button, name => button, inputMapping => de.lessvoid.nifty.input.mapping.MenuInputMapping, childLayout => center, controller => gui.BaseElementController, y => 224, x => 381 ******INITIALIZED SCREEN: de.lessvoid.nifty.screen.Screen@4a1ab1c1 ******INITIALIZED ELEMENT: panel1 (de.lessvoid.nifty.elements.Element@373ec894) ******INITIALIZED ELEMENT: id => panel1, height => 30%, style => nifty-panel-simple, width => 50%, backgroundImage => panel/nifty-panel-simple.png {nifty-panel-simple}, controller => gui.BaseElementController, childLayout => center, padding => 5px {nifty-panel-simple}, imageMode => resize:9,2,9,9,9,2,9,2,9,2,9,9 {nifty-panel-simple}, y => 334, x => 282 ******INITIALIZED SCREEN: de.lessvoid.nifty.screen.Screen@4a1ab1c1 ******INITIALIZED ELEMENT: layer4 (de.lessvoid.nifty.elements.Element@6427d489) ******INITIALIZED ELEMENT: id => layer4, backgroundColor => #fff0, controller => gui.BaseElementController, childLayout => absolute the button2 object is getting bound to my BaseElementController, but i can't seem to get it into the defined "onClick" call.

    Read the article

  • Unable to Create New Incidents in Dynamics CRM with Java and Axis2

    - by Lutz
    So I've been working on trying to figure this out, oddly when I ran it one machine I got a generic Axis Fault with no description, but now on another machine I'm getting a different error message, but I'm still stuck. Basically I'm just trying to do what I thought would be a fairly trivial task of creating a new incident in Microsoft Dynamics CRM 4.0 via a web services call. I started by downloading the XML from http://hostname/MSCrmServices/2007/CrmService.asmx and generating code from it using Axis2. Anyway, here's my program, any help would be greatly appreciated, as I've been stuck on this for way longer than I thought I'd be and I'm really out of ideas here. public class TestCRM { private static String endpointURL = "http://theHost/MSCrmServices/2007/CrmService.asmx"; private static String userName = "myUserNameHere"; private static String password = "myPasswordHere"; private static String host = "theHostname"; private static int port = 80; private static String domain = "theDomain"; private static String orgName = "theOrganization"; public static void main(String[] args) { CrmServiceStub stub; try { stub = new CrmServiceStub(endpointURL); setOptions(stub._getServiceClient().getOptions()); RetrieveMultipleDocument rmd = RetrieveMultipleDocument.Factory.newInstance(); com.microsoft.schemas.crm._2007.webservices.RetrieveMultipleDocument.RetrieveMultiple rm = com.microsoft.schemas.crm._2007.webservices.RetrieveMultipleDocument.RetrieveMultiple.Factory.newInstance(); QueryExpression query = QueryExpression.Factory.newInstance(); query.setColumnSet(AllColumns.Factory.newInstance()); query.setEntityName(EntityName.INCIDENT.toString()); rm.setQuery(query); rmd.setRetrieveMultiple(rm); TargetCreateIncident tinc = TargetCreateIncident.Factory.newInstance(); Incident inc = tinc.addNewIncident(); inc.setDescription("This is a test of ticket creation through a web services call."); CreateDocument cd = CreateDocument.Factory.newInstance(); Create create = Create.Factory.newInstance(); create.setEntity(inc); cd.setCreate(create); Incident test = (Incident)cd.getCreate().getEntity(); CrmAuthenticationTokenDocument catd = CrmAuthenticationTokenDocument.Factory.newInstance(); CrmAuthenticationToken token = CrmAuthenticationToken.Factory.newInstance(); token.setAuthenticationType(0); token.setOrganizationName(orgName); catd.setCrmAuthenticationToken(token); //The two printlns below spit back XML that looks okay to me? System.out.println(cd); System.out.println(catd); /* stuff that doesn't work */ CreateResponseDocument crd = stub.create(cd, catd, null, null); //this line throws the error CreateResponse cr = crd.getCreateResponse(); System.out.println("create result: " + cr.getCreateResult()); /* End stuff that doesn't work */ System.out.println(); System.out.println(); System.out.println(); boolean fetchNext = true; while(fetchNext){ RetrieveMultipleResponseDocument rmrd = stub.retrieveMultiple(rmd, catd, null, null); //This retrieve using the CRMAuthenticationToken catd works just fine RetrieveMultipleResponse rmr = rmrd.getRetrieveMultipleResponse(); BusinessEntityCollection bec = rmr.getRetrieveMultipleResult(); String pagingCookie = bec.getPagingCookie(); fetchNext = bec.getMoreRecords(); ArrayOfBusinessEntity aobe = bec.getBusinessEntities(); BusinessEntity[] myEntitiesAtLast = aobe.getBusinessEntityArray(); for(int i=0; i<myEntitiesAtLast.length; i++){ //cast to whatever you asked for... Incident myEntity = (Incident) myEntitiesAtLast[i]; System.out.println("["+(i+1)+"]: " + myEntity); } } } catch (Exception e) { e.printStackTrace(); } } private static void setOptions(Options options){ HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator(); List authSchemes = new ArrayList(); authSchemes.add(HttpTransportProperties.Authenticator.NTLM); auth.setAuthSchemes(authSchemes); auth.setUsername(userName); auth.setPassword(password); auth.setHost(host); auth.setPort(port); auth.setDomain(domain); auth.setPreemptiveAuthentication(false); options.setProperty(HTTPConstants.AUTHENTICATE, auth); options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, "true"); } } Also, here's the error message I receive: org.apache.axis2.AxisFault: com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character 'S' (code 83) in prolog; expected '<' at [row,col {unknown-source}]: [1,1] at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430) at org.apache.axis2.transport.TransportUtils.createSOAPMessage(TransportUtils.java:123) at org.apache.axis2.transport.TransportUtils.createSOAPMessage(TransportUtils.java:67) at org.apache.axis2.description.OutInAxisOperationClient.handleResponse(OutInAxisOperation.java:354) at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:417) at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229) at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165) at com.spanlink.crm.dynamics4.webservice.CrmServiceStub.create(CrmServiceStub.java:618) at com.spanlink.crm.dynamics4.runtime.TestCRM.main(TestCRM.java:82) Caused by: org.apache.axiom.om.OMException: com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character 'S' (code 83) in prolog; expected '<' at [row,col {unknown-source}]: [1,1] at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(StAXOMBuilder.java:260) at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.getSOAPEnvelope(StAXSOAPModelBuilder.java:161) at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.<init>(StAXSOAPModelBuilder.java:110) at org.apache.axis2.builder.BuilderUtil.getSOAPBuilder(BuilderUtil.java:682) at org.apache.axis2.transport.TransportUtils.createDocumentElement(TransportUtils.java:215) at org.apache.axis2.transport.TransportUtils.createSOAPMessage(TransportUtils.java:145) at org.apache.axis2.transport.TransportUtils.createSOAPMessage(TransportUtils.java:108) ... 7 more Caused by: com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character 'S' (code 83) in prolog; expected '<' at [row,col {unknown-source}]: [1,1] at com.ctc.wstx.sr.StreamScanner.throwUnexpectedChar(StreamScanner.java:623) at com.ctc.wstx.sr.BasicStreamReader.nextFromProlog(BasicStreamReader.java:2047) at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1069) at javax.xml.stream.util.StreamReaderDelegate.next(StreamReaderDelegate.java:60) at org.apache.axiom.om.impl.builder.SafeXMLStreamReader.next(SafeXMLStreamReader.java:183) at org.apache.axiom.om.impl.builder.StAXOMBuilder.parserNext(StAXOMBuilder.java:597) at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(StAXOMBuilder.java:172) ... 13 more

    Read the article

  • android camera preview blank screen

    - by user1104836
    I want to capture a photo manually not by using existing camera apps. So i made this Activity: public class CameraActivity extends Activity { private Camera mCamera; private Preview mPreview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera); // Create an instance of Camera // mCamera = Camera.open(0); // Create our Preview view and set it as the content of our activity. mPreview = new Preview(this); mPreview.safeCameraOpen(0); FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview); preview.addView(mPreview); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_camera, menu); return true; } } This is the CameraPreview which i want to use: public class Preview extends ViewGroup implements SurfaceHolder.Callback { SurfaceView mSurfaceView; SurfaceHolder mHolder; //CAM INSTANCE ================================ private Camera mCamera; List<Size> mSupportedPreviewSizes; //============================================= /** * @param context */ public Preview(Context context) { super(context); mSurfaceView = new SurfaceView(context); addView(mSurfaceView); // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = mSurfaceView.getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } /** * @param context * @param attrs */ public Preview(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } /** * @param context * @param attrs * @param defStyle */ public Preview(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub } /* (non-Javadoc) * @see android.view.ViewGroup#onLayout(boolean, int, int, int, int) */ @Override protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) { // TODO Auto-generated method stub } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // Now that the size is known, set up the camera parameters and begin // the preview. Camera.Parameters parameters = mCamera.getParameters(); parameters.setPreviewSize(width, height); requestLayout(); mCamera.setParameters(parameters); /* Important: Call startPreview() to start updating the preview surface. Preview must be started before you can take a picture. */ mCamera.startPreview(); } @Override public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub } @Override public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return, so stop the preview. if (mCamera != null) { /* Call stopPreview() to stop updating the preview surface. */ mCamera.stopPreview(); } } /** * When this function returns, mCamera will be null. */ private void stopPreviewAndFreeCamera() { if (mCamera != null) { /* Call stopPreview() to stop updating the preview surface. */ mCamera.stopPreview(); /* Important: Call release() to release the camera for use by other applications. Applications should release the camera immediately in onPause() (and re-open() it in onResume()). */ mCamera.release(); mCamera = null; } } public void setCamera(Camera camera) { if (mCamera == camera) { return; } stopPreviewAndFreeCamera(); mCamera = camera; if (mCamera != null) { List<Size> localSizes = mCamera.getParameters().getSupportedPreviewSizes(); mSupportedPreviewSizes = localSizes; requestLayout(); try { mCamera.setPreviewDisplay(mHolder); } catch (IOException e) { e.printStackTrace(); } /* Important: Call startPreview() to start updating the preview surface. Preview must be started before you can take a picture. */ mCamera.startPreview(); } } public boolean safeCameraOpen(int id) { boolean qOpened = false; try { releaseCameraAndPreview(); mCamera = Camera.open(id); mCamera.startPreview(); qOpened = (mCamera != null); } catch (Exception e) { // Log.e(R.string.app_name, "failed to open Camera"); e.printStackTrace(); } return qOpened; } Camera.PictureCallback mPicCallback = new Camera.PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { // TODO Auto-generated method stub Log.d("lala", "pic is taken"); } }; public void takePic() { mCamera.startPreview(); // mCamera.takePicture(null, mPicCallback, mPicCallback); } private void releaseCameraAndPreview() { this.setCamera(null); if (mCamera != null) { mCamera.release(); mCamera = null; } } } This is the Layout of CameraActivity: <LinearLayout 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" tools:context=".CameraActivity" > <FrameLayout android:id="@+id/camera_preview" android:layout_width="0dip" android:layout_height="fill_parent" android:layout_weight="1" /> <Button android:id="@+id/button_capture" android:text="Capture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" /> </LinearLayout> But when i start the CameraActivity, i just see a blank white background and the Capture-Button??? Why i dont see the Camera-Screen?

    Read the article

  • Error when call 'qb.query(db, projection, selection, selectionArgs, null, null, orderBy);'

    - by smalltalk1960s
    Hi all, I make a content provider named 'DictionaryProvider' (Based on NotepadProvider). When my program run to command 'qb.query(db, projection, selection, selectionArgs, null, null, orderBy);', error happen. I don't know how to fix. please help me. Below is my code // file main calling DictionnaryProvider @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dictionary); final String[] PROJECTION = new String[] { DicColumns._ID, // 0 DicColumns.KEY_WORD, // 1 DicColumns.KEY_DEFINITION // 2 }; Cursor c = managedQuery(DicColumns.CONTENT_URI, PROJECTION, null, null, DicColumns.DEFAULT_SORT_ORDER); String str = ""; if (c.moveToFirst()) { int wordColumn = c.getColumnIndex("KEY_WORD"); int defColumn = c.getColumnIndex("KEY_DEFINITION"); do { // Get the field values str = ""; str += c.getString(wordColumn); str +="\n"; str +=c.getString(defColumn); } while (c.moveToNext()); } Toast.makeText(this, str, Toast.LENGTH_SHORT).show(); } // file DictionaryProvider.java package com.example.helloandroid; import java.util.HashMap; import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import com.example.helloandroid.Dictionary.DicColumns; public class DictionaryProvider extends ContentProvider { //private static final String TAG = "DictionaryProvider"; private DictionaryOpenHelper dbdic; static final int DATABASE_VERSION = 1; static final String DICTIONARY_DATABASE_NAME = "dictionarydb"; static final String DICTIONARY_TABLE_NAME = "dictionary"; private static final UriMatcher sUriMatcher; private static HashMap<String, String> sDicProjectionMap; @Override public int delete(Uri arg0, String arg1, String[] arg2) { // TODO Auto-generated method stub return 0; } @Override public String getType(Uri arg0) { // TODO Auto-generated method stub return null; } @Override public Uri insert(Uri arg0, ContentValues arg1) { // TODO Auto-generated method stub return null; } @Override public boolean onCreate() { // TODO Auto-generated method stub dbdic = new DictionaryOpenHelper(getContext(), DICTIONARY_DATABASE_NAME, null, DATABASE_VERSION); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(DICTIONARY_TABLE_NAME); switch (sUriMatcher.match(uri)) { case 1: qb.setProjectionMap(sDicProjectionMap); break; case 2: qb.setProjectionMap(sDicProjectionMap); qb.appendWhere(DicColumns._ID + "=" + uri.getPathSegments().get(1)); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } // If no sort order is specified use the default String orderBy; if (TextUtils.isEmpty(sortOrder)) { orderBy = DicColumns.DEFAULT_SORT_ORDER; } else { orderBy = sortOrder; } // Get the database and run the query SQLiteDatabase db = dbdic.getReadableDatabase(); Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy); // Tell the cursor what uri to watch, so it knows when its source data changes c.setNotificationUri(getContext().getContentResolver(), uri); return c; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // TODO Auto-generated method stub return 0; } static { sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); sUriMatcher.addURI(Dictionary.AUTHORITY, "dictionary", 1); sUriMatcher.addURI(Dictionary.AUTHORITY, "dictionary/#", 2); sDicProjectionMap = new HashMap<String, String>(); sDicProjectionMap.put(DicColumns._ID, DicColumns._ID); sDicProjectionMap.put(DicColumns.KEY_WORD, DicColumns.KEY_WORD); sDicProjectionMap.put(DicColumns.KEY_DEFINITION, DicColumns.KEY_DEFINITION); // Support for Live Folders. /*sLiveFolderProjectionMap = new HashMap<String, String>(); sLiveFolderProjectionMap.put(LiveFolders._ID, NoteColumns._ID + " AS " + LiveFolders._ID); sLiveFolderProjectionMap.put(LiveFolders.NAME, NoteColumns.TITLE + " AS " + LiveFolders.NAME);*/ // Add more columns here for more robust Live Folders. } } // file Dictionary.java package com.example.helloandroid; import android.net.Uri; import android.provider.BaseColumns; /** * Convenience definitions for DictionaryProvider */ public final class Dictionary { public static final String AUTHORITY = "com.example.helloandroid.provider.Dictionary"; // This class cannot be instantiated private Dictionary() {} /** * Dictionary table */ public static final class DicColumns implements BaseColumns { // This class cannot be instantiated private DicColumns() {} /** * The content:// style URL for this table */ public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/dictionary"); /** * The MIME type of {@link #CONTENT_URI} providing a directory of notes. */ //public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.note"; /** * The MIME type of a {@link #CONTENT_URI} sub-directory of a single note. */ //public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.google.note"; /** * The default sort order for this table */ public static final String DEFAULT_SORT_ORDER = "modified DESC"; /** * The key_word of the dictionary * <P>Type: TEXT</P> */ public static final String KEY_WORD = "KEY_WORD"; /** * The key_definition of word * <P>Type: TEXT</P> */ public static final String KEY_DEFINITION = "KEY_DEFINITION"; } } thanks so much

    Read the article

  • Wine 1.6.2-Trying to switch to 32-bit Wineprefix from 64-bit Wine (Trusty 14.04). Can anyone help me out?

    - by AlternateSteve90
    Hello fellow Ubuntu users, I'm having a little trouble with Wine 1.6.1 and I was wondering if someone could help me out. I recently downloaded some 32-bit games that I'd wanted to try(BeamNG Drive and Bugbear's Next Car Game demo) and I had run into some trouble trying to get either of these games to run. So I came across a couple pieces of advice on the 'Net, one here on the Ubuntu community site and the other at BeamNG's forums, on how to create a 32-bit wineprefix on a 64-bit setup. I managed to be able to create the wine32 folder, but now I'm having trouble making it my default Wine setup. Anybody have any idea how I can do that? I'll post the URLs for said advice, btw: http://www.beamng.com/threads/1788-Installing-DRIVE-under-Linux-via-Wine How do I create a 32-bit WINE prefix? Here's what I've tried so far in the Terminal: steven@steven-HP-Pavilion-17-Notebook-PC:~$ WINEPREFIX='/home/user/wine32' WINEARCH='win32' wine 'wineboot' wine: chdir to /home/user/wine32 : No such file or directory steven@steven-HP-Pavilion-17-Notebook-PC:~$ WINEPREFIX='/home/steven/wine32' WINEARCH='win32' wine 'wineboot' wine: created the configuration directory '/home/steven/wine32' fixme:storage:create_storagefile Storage share mode not implemented. err:mscoree:LoadLibraryShim error reading registry key for installroot err:mscoree:LoadLibraryShim error reading registry key for installroot err:mscoree:LoadLibraryShim error reading registry key for installroot err:mscoree:LoadLibraryShim error reading registry key for installroot fixme:storage:create_storagefile Storage share mode not implemented. fixme:iphlpapi:NotifyAddrChange (Handle 0x10ee890, overlapped 0x10ee89c): stub wine: configuration in '/home/steven/wine32' has been updated. steven@steven-HP-Pavilion-17-Notebook-PC:~$ WINEPREFIX=$HOME/.wine32 wine dxsetup.exe wine: created the configuration directory '/home/steven/.wine32' fixme:storage:create_storagefile Storage share mode not implemented. err:mscoree:LoadLibraryShim error reading registry key for installroot err:mscoree:LoadLibraryShim error reading registry key for installroot err:mscoree:LoadLibraryShim error reading registry key for installroot err:mscoree:LoadLibraryShim error reading registry key for installroot fixme:storage:create_storagefile Storage share mode not implemented. fixme:iphlpapi:NotifyAddrChange (Handle 0x103e2b8, overlapped 0x103e2d0): stub fixme:storage:create_storagefile Storage share mode not implemented. fixme:iphlpapi:NotifyAddrChange (Handle 0x10fe890, overlapped 0x10fe89c): stub wine: configuration in '/home/steven/.wine32' has been updated. wine: cannot find L"C:\windows\system32\dxsetup.exe" steven@steven-HP-Pavilion-17-Notebook-PC:~$ WINEARCH=win64 winecfgsteven@steven-HP-Pavilion-17-Notebook-PC:~$ WINEPREFIX='/home/steven/wine32' WINEARCH='win32' wine 'wineboot' steven@steven-HP-Pavilion-17-Notebook-PC:~$ WINEARCH=win32 winecfg wine: WINEARCH set to win32 but '/home/steven/.wine' is a 64-bit installation. steven@steven-HP-Pavilion-17-Notebook-PC:~$ WINEPREFIX='/home/steven/wine32' WINEARCH='win32' wine 'wineboot' steven@steven-HP-Pavilion-17-Notebook-PC:~$ WINEPREFIX='/home/user/wine32' WINEARCH='win32' wine 'wineboot' wine: chdir to /home/user/wine32 : No such file or directory steven@steven-HP-Pavilion-17-Notebook-PC:~$ WINEPREFIX='/home/steven/wine32' WINEARCH='win32' wine 'wineboot' steven@steven-HP-Pavilion-17-Notebook-PC:~$ WINEPREFIX=/home/steven/wine32 WINEARCH='win32' wine 'wineboot' steven@steven-HP-Pavilion-17-Notebook-PC:~$ WINEPREFIX=/home/steven/wine32 WINEARCH=win32 wine wineboot steven@steven-HP-Pavilion-17-Notebook-PC:~$ So, yeah. TBH, though, I'm far from an expert and perhaps I've been going about it all the wrong way. In the meantime, I'll try to keep looking for solutions on my own, but if anybody can help me solve this dilemma, especially if anyone happens to own any of these two games in particular, I'd appreciate it. :)

    Read the article

  • Animation Trouble with Java Swing Timer - Also, JFrame Will Not Exit_On_Close

    - by forgotton_semicolon
    So, I am using a Java Swing Timer because putting the animation code in a run() method of a Thread subclass caused an insane amount of flickering that is really a terrible experience for any video game player. Can anyone give me any tips on: Why there is no animation... Why the JFrame will not close when it is coded to Exit_On_Close 2 times My code is here: import java.awt.; import java.awt.event.; import javax.swing.*; import java.net.URL; //////////////////////////////////////////////////////////////// TFQ public class TFQ extends JFrame { DrawingsInSpace dis; //========================================================== constructor public TFQ() { dis = new DrawingsInSpace(); JPanel content = new JPanel(); content.setLayout(new FlowLayout()); this.setContentPane(dis); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setTitle("Plasma_Orbs_Off_Orion"); this.setSize(500,500); this.pack(); //... Create timer which calls action listener every second.. // Use full package qualification for javax.swing.Timer // to avoid potential conflicts with java.util.Timer. javax.swing.Timer t = new javax.swing.Timer(500, new TimePhaseListener()); t.start(); } /////////////////////////////////////////////// inner class Listener thing class TimePhaseListener implements ActionListener, KeyListener { // counter int total; // loop control boolean Its_a_go = true; //position of our matrix int tf = -400; //sprite directions int Sprite_Direction; final int RIGHT = 1; final int LEFT = 2; //for obstacle Rectangle mega_obstacle = new Rectangle(200, 0, 20, HEIGHT); public void actionPerformed(ActionEvent e) { //... Whenever this is called, repaint the screen dis.repaint(); addKeyListener(this); while (Its_a_go) { try { dis.repaint(); if(Sprite_Direction == RIGHT) { dis.matrix.x += 2; } // end if i think if(Sprite_Direction == LEFT) { dis.matrix.x -= 2; } } catch(Exception ex) { System.out.println(ex); } } // end while i think } // end actionPerformed @Override public void keyPressed(KeyEvent arg0) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent arg0) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent event) { // TODO Auto-generated method stub if (event.getKeyChar()=='f'){ Sprite_Direction = RIGHT; System.out.println("matrix should be animating now "); System.out.println("current matrix position = " + dis.matrix.x); } if (event.getKeyChar()=='d') { Sprite_Direction = LEFT; System.out.println("matrix should be going in reverse"); System.out.println("current matrix position = " + dis.matrix.x); } } } //================================================================= main public static void main(String[] args) { JFrame SafetyPins = new TFQ(); SafetyPins.setVisible(true); SafetyPins.setSize(500,500); SafetyPins.setResizable(true); SafetyPins.setLocationRelativeTo(null); SafetyPins.setDefaultCloseOperation(EXIT_ON_CLOSE); } } class DrawingsInSpace extends JPanel { URL url1_plasma_orbs; URL url2_matrix; Image img1_plasma_orbs; Image img2_matrix; // for the plasma_orbs Rectangle bbb = new Rectangle(0,0, 0, 0); // for the matrix Rectangle matrix = new Rectangle(-400, 60, 430, 200); public DrawingsInSpace() { //load URLs try { url1_plasma_orbs = this.getClass().getResource("plasma_orbs.png"); url2_matrix = this.getClass().getResource("matrix.png"); } catch(Exception e) { System.out.println(e); } // attach the URLs to the images img1_plasma_orbs = Toolkit.getDefaultToolkit().getImage(url1_plasma_orbs); img2_matrix = Toolkit.getDefaultToolkit().getImage(url2_matrix); } public void paintComponent(Graphics g) { super.paintComponent(g); // draw the plasma_orbs g.drawImage(img1_plasma_orbs, bbb.x, bbb.y,this); //draw the matrix g.drawImage(img2_matrix, matrix.x, matrix.y, this); } } // end class enter code here

    Read the article

  • java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.HashMap

    - by kongkea
    I've got this Error When I click listview to show full image size. how can i solve it? Error 11-20 10:27:47.039: D/AndroidRuntime(5078): Shutting down VM 11-20 10:27:47.039: W/dalvikvm(5078): threadid=1: thread exiting with uncaught exception (group=0x40c061f8) 11-20 10:27:47.047: E/AndroidRuntime(5078): FATAL EXCEPTION: main 11-20 10:27:47.047: E/AndroidRuntime(5078): java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.HashMap 11-20 10:27:47.047: E/AndroidRuntime(5078): at com.example.mylistview.MainActivity$1.onItemClick(MainActivity.java:103) 11-20 10:27:47.047: E/AndroidRuntime(5078): at android.widget.AdapterView.performItemClick(AdapterView.java:292) 11-20 10:27:47.047: E/AndroidRuntime(5078): at android.widget.AbsListView.performItemClick(AbsListView.java:1173) 11-20 10:27:47.047: E/AndroidRuntime(5078): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2701) 11-20 10:27:47.047: E/AndroidRuntime(5078): at android.widget.AbsListView$1.run(AbsListView.java:3453) 11-20 10:27:47.047: E/AndroidRuntime(5078): at android.os.Handler.handleCallback(Handler.java:605) 11-20 10:27:47.047: E/AndroidRuntime(5078): at android.os.Handler.dispatchMessage(Handler.java:92) 11-20 10:27:47.047: E/AndroidRuntime(5078): at android.os.Looper.loop(Looper.java:137) 11-20 10:27:47.047: E/AndroidRuntime(5078): at android.app.ActivityThread.main(ActivityThread.java:4514) 11-20 10:27:47.047: E/AndroidRuntime(5078): at java.lang.reflect.Method.invokeNative(Native Method) 11-20 10:27:47.047: E/AndroidRuntime(5078): at java.lang.reflect.Method.invoke(Method.java:511) 11-20 10:27:47.047: E/AndroidRuntime(5078): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790) 11-20 10:27:47.047: E/AndroidRuntime(5078): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557) 11-20 10:27:47.047: E/AndroidRuntime(5078): at dalvik.system.NativeStart.main(Native Method) MainActivity public class MainActivity extends Activity { public static final int DIALOG_DOWNLOAD_JSON_PROGRESS = 0; private ProgressDialog mProgressDialog; ArrayList<HashMap<String, Object>> MyArrList; @SuppressLint("NewApi") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Permission StrictMode if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } // Download JSON File new DownloadJSONFileAsync().execute(); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_DOWNLOAD_JSON_PROGRESS: mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage("Downloading....."); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mProgressDialog.setCancelable(true); mProgressDialog.show(); return mProgressDialog; default: return null; } } // Show All Content public void ShowAllContent() { // listView1 final ListView lstView1 = (ListView)findViewById(R.id.listView1); lstView1.setAdapter(new ImageAdapter(MainActivity.this,MyArrList)); lstView1.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { HashMap<String, Object> hm = (HashMap<String, Object>) lstView1.getAdapter().getItem(position); String imagePath = (String) hm.get("photo"); Intent i = new Intent(MainActivity.this,FullImageActivity.class); i.putExtra("fullImage", imagePath); startActivity(i); } }); } public class ImageAdapter extends BaseAdapter { private Context context; private ArrayList<HashMap<String, Object>> MyArr = new ArrayList<HashMap<String, Object>>(); public ImageAdapter(Context c, ArrayList<HashMap<String, Object>> myArrList) { // TODO Auto-generated method stub context = c; MyArr = myArrList; } public int getCount() { // TODO Auto-generated method stub return MyArr.size(); } public Object getItem(int position) { // TODO Auto-generated method stub return position; } public long getItemId(int position) { // TODO Auto-generated method stub return position; } public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (convertView == null) { convertView = inflater.inflate(R.layout.activity_column, null); } // ColImage ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImgPath); imageView.getLayoutParams().height = 80; imageView.getLayoutParams().width = 80; imageView.setPadding(5, 5, 5, 5); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); try { imageView.setImageBitmap((Bitmap)MyArr.get(position).get("ImageThumBitmap")); } catch (Exception e) { // When Error imageView.setImageResource(android.R.drawable.ic_menu_report_image); } // ColImgID TextView txtImgID = (TextView) convertView.findViewById(R.id.ColImgID); txtImgID.setPadding(10, 0, 0, 0); txtImgID.setText("ID : " + MyArr.get(position).get("id").toString()); // ColImgName TextView txtPicName = (TextView) convertView.findViewById(R.id.ColImgName); txtPicName.setPadding(50, 0, 0, 0); txtPicName.setText("Name : " + MyArr.get(position).get("first_name").toString()); return convertView; } } // Download JSON in Background public class DownloadJSONFileAsync extends AsyncTask<String, Void, Void> { protected void onPreExecute() { super.onPreExecute(); showDialog(DIALOG_DOWNLOAD_JSON_PROGRESS); } @Override protected Void doInBackground(String... params) { // TODO Auto-generated method stub String url = "http://192.168.10.104/adchara1/"; JSONArray data; try { data = new JSONArray(getJSONUrl(url)); MyArrList = new ArrayList<HashMap<String, Object>>(); HashMap<String, Object> map; for(int i = 0; i < data.length(); i++){ JSONObject c = data.getJSONObject(i); map = new HashMap<String, Object>(); map.put("id", (String)c.getString("id")); map.put("first_name", (String)c.getString("first_name")); // Thumbnail Get ImageBitmap To Object map.put("photo", (String)c.getString("photo")); map.put("ImageThumBitmap", (Bitmap)loadBitmap(c.getString("photo"))); // Full (for View Popup) map.put("frame", (String)c.getString("frame")); MyArrList.add(map); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } protected void onPostExecute(Void unused) { ShowAllContent(); // When Finish Show Content dismissDialog(DIALOG_DOWNLOAD_JSON_PROGRESS); removeDialog(DIALOG_DOWNLOAD_JSON_PROGRESS); } } /*** Get JSON Code from URL ***/ public String getJSONUrl(String url) { StringBuilder str = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { // Download OK HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { str.append(line); } } else { Log.e("Log", "Failed to download file.."); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return str.toString(); } /***** Get Image Resource from URL (Start) *****/ private static final String TAG = "Image"; private static final int IO_BUFFER_SIZE = 4 * 1024; public static Bitmap loadBitmap(String url) { Bitmap bitmap = null; InputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE); final ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE); copy(in, out); out.flush(); final byte[] data = dataStream.toByteArray(); BitmapFactory.Options options = new BitmapFactory.Options(); //options.inSampleSize = 1; bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options); } catch (IOException e) { Log.e(TAG, "Could not load Bitmap from: " + url); } finally { closeStream(in); closeStream(out); } return bitmap; } private static void closeStream(Closeable stream) { if (stream != null) { try { stream.close(); } catch (IOException e) { android.util.Log.e(TAG, "Could not close stream", e); } } } private static void copy(InputStream in, OutputStream out) throws IOException { byte[] b = new byte[IO_BUFFER_SIZE]; int read; while ((read = in.read(b)) != -1) { out.write(b, 0, read); } } /***** Get Image Resource from URL (End) *****/ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } } FullImageActivity String imagePath = getIntent().getStringExtra("fullImage"); if(imagePath != null && !imagePath.isEmpty()){ File imageFile = new File(imagePath); if(imageFile.exists()){ Bitmap myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath()); ImageView iv = (ImageView) findViewById(R.id.fullimage); iv.setImageBitmap(myBitmap); } }

    Read the article

  • From VB6 to .net via COM and Remoting...What a mess!

    - by Robert
    I have some legacy vb6 applications that need to talk to my .Net engine application. The engine provides an interface that can be connected to via .net Remoting. Now I have a stub class library that wraps all of the types that the interface exposes. The purpose of this stub is to translate my .net types into COM-friendly types. When I run this class library as a console application, it is able to connect to the engine, call various methods, and successfully return the wrapped types. The next step in the chain is to allow my VB6 application to call this COM enabled stub. This works fine for my main engine-entry type (IModelFetcher which is wrapped as COM_ModelFetcher). However, when I try and get any of the model fetcher's model types (IClientModel, wrapped as COM_IClientModel, IUserModel, wrapped as COM_IUserModel, e.t.c.), I get the following exception: [Exception - type: System.InvalidCastException 'Return argument has an invalid type.'] in mscorlib at System.Runtime.Remoting.Proxies.RealProxy.ValidateReturnArg(Object arg, Type paramType) at System.Runtime.Remoting.Proxies.RealProxy.PropagateOutParameters(IMessage msg, Object[] outArgs, Object returnValue) at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at AWT.Common.AWTEngineInterface.IModelFetcher.get_ClientModel() at AWT.Common.AWTEngineCOMInterface.COM_ModelFetcher.GetClientModel() The first thing I did when I saw this was to handle the 'AppDomain.CurrentDomain.AssemblyResolve' event, and this allowed me to load the required assemblies. However, I'm still getting this exception now. My AssemblyResolve event handler is loading three assemblies correctly, and I can confirm that it does not get called prior to this exception. Can someone help me untie myself from this mess of interprocess communication?!

    Read the article

  • Rspec stubing view for anonymous controller

    - by Colin G
    I'm trying to test a method on the application controller that will be used as a before filter. To do this I have setup an anonymous controller in my test with the before filter applied to ensure that it functions correctly. The test currently looks like this: describe ApplicationController do controller do before_filter :authenticated def index end end describe "user authenticated" do let(:session_id){"session_id"} let(:user){OpenStruct.new(:email => "[email protected]", :name => "Colin Gemmell")} before do request.cookies[:session_id] = session_id UserSession.stub!(:find).with(session_id).and_return(user) get :index end it { should assign_to(:user){user} } end end And the application controller is like this: class ApplicationController < ActionController::Base protect_from_forgery def authenticated @user = nil end end My problem is when ever I run the test I'm getting the following error 1) ApplicationController user authenticated Failure/Error: get :index ActionView::MissingTemplate: Missing template stub_resources/index with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml, :haml], :formats=>[:html], :locale=>[:en, :en]} in view paths "#<RSpec::Rails::ViewRendering::PathSetDelegatorResolver:0x984f310>" According to the docs the view is not rendered when running controller tests however this points to no stub existing for this action (which is understandable as the view doesn't exist) Anyone have a clue how to solve this problem or stub the view out. Cheers Colin G

    Read the article

  • PHPUnit - multiple stubs of same class

    - by keithjgrant
    I'm building unit tests for class Foo, and I'm fairly new to unit testing. A key component of my class is an instance of BarCollection which contains a number of Bar objects. One method in Foo iterates through the collection and calls a couple methods on each Bar object in the collection. I want to use stub objects to generate a series of responses for my test class. How do I make the Bar stub class return different values as I iterate? I'm trying to do something along these lines: $stubs = array(); foreach ($array as $value) { $barStub->expects($this->any()) ->method('GetValue')) ->will($this->returnValue($value)); $stubs[] = $barStub; } // populate stubs into `Foo` // assert results from `Foo->someMethod()` So Foo->someMethod() will produce data based on the results it receives from the Bar objects. But this gives me the following error whenever the array is longer than one: There was 1 failure: 1) testMyTest(FooTest) with data set #2 (array(0.5, 0.5)) Expectation failed for method name is equal to <string:GetValue> when invoked zero or more times. Mocked method does not exist. /usr/share/php/PHPUnit/Framework/MockObject/Mock.php(193) : eval()'d code:25 One thought I had was to use ->will($this->returnCallback()) to invoke a callback method, but I don't know how to indicate to the callback which Bar object is making the call (and consequently what response to give). Another idea is to use the onConsecutiveCalls() method, or something like it, to tell my stub to return 1 the first time, 2 the second time, etc, but I'm not sure exactly how to do this. I'm also concerned that if my class ever does anything other than ordered iteration on the collection, I won't have a way to test it.

    Read the article

  • How can we call an activity through service in android???

    - by Shalini Singh
    Hi! friends, i am a android developer,,, want to know is it possible to call an activity through background service in android like : import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; import android.media.MediaPlayer; import android.os.Handler; import android.os.IBinder; import android.os.Message; public class background extends Service{ private int timer1; @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); SharedPreferences preferences = getSharedPreferences("SaveTime", MODE_PRIVATE); timer1 = preferences.getInt("time", 0); startservice(); } @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } private void startservice() { Handler handler = new Handler(); handler.postDelayed(new Runnable(){ public void run() { mediaPlayerPlay.sendEmptyMessage(0); } }, timer1*60*1000); } private Handler mediaPlayerPlay = new Handler(){ @Override public void handleMessage(Message msg) { try { getApplication(); MediaPlayer mp = new MediaPlayer(); mp = MediaPlayer.create(background.this, R.raw.alarm); mp.start(); } catch(Exception e) { e.printStackTrace(); } super.handleMessage(msg); } }; /* * (non-Javadoc) * * @see android.app.Service#onDestroy() */ @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } } i want to call my activity......

    Read the article

  • No GPS Update retrieved? Problem in Code?

    - by poeschlorn
    Hello mates, I've got a serious problem with my GPS on my Nexus One: I wrote a kind of hello world with GPS, but the Toast that should be displayed isn't :( I don't know what I'm doing wrong...maybe you could help me getting this work. Here's my code: package gps.test; import android.app.Activity; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.widget.Toast; public class GPS extends Activity { private LocationManager lm; private LocationListener locationListener; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // ---use the LocationManager class to obtain GPS locations--- lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationListener = new MyLocationListener(); lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 1, locationListener); } private class MyLocationListener implements LocationListener { @Override public void onLocationChanged(Location loc) { if (loc != null) { Toast.makeText( getBaseContext(), "Location changed : Lat: " + loc.getLatitude() + " Lng: " + loc.getLongitude(), Toast.LENGTH_SHORT).show(); } } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } } } Theoretically there should be a new toast every 100 milliseconds, shouldn't it? Or at least, when I change my position by one meter!? I've no idea why it doesn't. I must admit I'm new to the topic, maybe I've missed something? It would be great if you could give me a hint :) nice greetings, poeschlorn

    Read the article

  • Updating an application OTA

    - by Bostjan
    I'm developing an application that will be available from a website (market probably as well). The problem I'm having at the moment is how to handle the updates to the app. I know how to check the version against the current one and I know if I need to update it. Question is...how? Is there a way I can download an APK from the website and start the install process? The user will have to confirm of course, but I just want to be able to start it for him. At the moment I'm doing this: private void doUpgrade() { // TODO Auto-generated method stub Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.upgrade)); builder.setIcon(R.drawable.help); builder.setMessage(getString(R.string.needUpgrade)); builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Map<String, String> data = new HashMap<String, String>(); try { HttpResponse re = Registration.doPost("http://www.android-town.com/appRelease/AndroidTown.apk",data); int statusCode = re.getStatusLine().getStatusCode(); closeApp(); } catch (ClientProtocolException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), getString(R.string.noURLAccess), Toast.LENGTH_SHORT).show(); closeApp(); } catch (IOException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), getString(R.string.noURLAccess), Toast.LENGTH_SHORT).show(); closeApp(); } } }); builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.cancel(); closeApp(); } }); builder.show(); } But it doesn't really do anything...should I open a webView with the URL? A new runnable thread? Any other way? Please help :) Cheers

    Read the article

  • What is the purpose of unit testing an interface repository

    - by ahsteele
    I am unit testing an ICustomerRepository interface used for retrieving objects of type Customer. As a unit test what value am I gaining by testing the ICustomerRepository in this manner? Under what conditions would the below test fail? For tests of this nature is it advisable to do tests that I know should fail? i.e. look for id 4 when I know I've only placed 5 in the repository I am probably missing something obvious but it seems the integration tests of the class that implements ICustomerRepository will be of more value. [TestClass] public class CustomerTests : TestClassBase { private Customer SetUpCustomerForRepository() { return new Customer() { CustId = 5, DifId = "55", CustLookupName = "The Dude", LoginList = new[] { new Login { LoginCustId = 5, LoginName = "tdude" }, new Login { LoginCustId = 5, LoginName = "tdude2" } } }; } [TestMethod] public void CanGetCustomerById() { // arrange var customer = SetUpCustomerForRepository(); var repository = Stub<ICustomerRepository>(); // act repository.Stub(rep => rep.GetById(5)).Return(customer); // assert Assert.AreEqual(customer, repository.GetById(5)); } } Test Base Class public class TestClassBase { protected T Stub<T>() where T : class { return MockRepository.GenerateStub<T>(); } } ICustomerRepository and IRepository public interface ICustomerRepository : IRepository<Customer> { IList<Customer> FindCustomers(string q); Customer GetCustomerByDifID(string difId); Customer GetCustomerByLogin(string loginName); } public interface IRepository<T> { void Save(T entity); void Save(List<T> entity); bool Save(T entity, out string message); void Delete(T entity); T GetById(int id); ICollection<T> FindAll(); }

    Read the article

  • GPS not update location after close and reopen app on android

    - by mrmamon
    After I closed my app for a while then reopen it again,my app will not update location or sometime it will take long time( about 5min) before update. How can I fix it? This is my code private LocationManager lm; private LocationListener locationListener; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationListener = new mLocationListener(); lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, locationListener); } private class myLocationListener implements LocationListener { @Override public void onLocationChanged(Location loc) { if (loc != null) { TextView gpsloc = (TextView) findViewById(R.id.widget28); gpsloc.setText("Lat:"+loc.getLatitude()+" Lng:"+ loc.getLongitude()); } } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub TextView gpsloc = (TextView) findViewById(R.id.widget28); gpsloc.setText("GPS OFFLINE."); } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } }

    Read the article

  • Axis2 SOAP Envelope Header Information

    - by BigZig
    I'm consuming a web service that places an authentication token in the SOAP envelope header. It appears (through looking at the samples that came with the WS WSDL) that if the stub is generated in .NET, this header information is exposed through a member variable in the stub class. However, when I generate my Axis2 java stub using WSDL2Java it doesn't appear to be exposed anywhere. What is the correct way to extract this information from the SOAP envelope header? WSDL: http://www.vbar.com/zangelo/SecurityService.wsdl C# Sample: using System; using SignInSample.Security; // web service using SignInSample.Document; // web service namespace SignInSample { class SignInSampleClass { [STAThread] static void Main(string[] args) { // login to the Vault and set up the document service SecurityService secSvc = new SecurityService(); secSvc.Url = "http://localhost/AutodeskDM/Services/SecurityService.asmx"; secSvc.SecurityHeaderValue = new SignInSample.Security.SecurityHeader(); secSvc.SignIn("Administrator", "", "Vault"); DocumentServiceWse docSvc = new DocumentServiceWse(); docSvc.Url = "http://localhost/AutodeskDM/Services/DocumentService.asmx"; docSvc.SecurityHeaderValue = new SignInSample.Document.SecurityHeader(); docSvc.SecurityHeaderValue.Ticket = secSvc.SecurityHeaderValue.Ticket; docSvc.SecurityHeaderValue.UserId = secSvc.SecurityHeaderValue.UserId; } } } The sample illustrates what I'd like to do. Notice how the secSvc instance has a SecurityHeaderValue member variable that is populated after a successful secSvc.SignIn() invocation. Here's some relevant API documentation regarding the SignIn method: Although there is no return value, a successful sign in will populate the SecurityHeaderValue of the security service. The SecurityHeaderValue information is then used for other web service calls.

    Read the article

  • camera picturecallback intent not work

    - by Simon
    After I take the photo, the program automatically goes back like onBackPressed(). When I remove the putExtra, the intent runs. When I put startActivity() after takePicture(), it transfers null data.... I just want to put the image data to another activity to have other use. How can it be achieved? private PictureCallback picture = new PictureCallback(){ @Override public void onPictureTaken(byte[] data, Camera camera) { // TODO Auto-generated method stub Intent intent = new Intent(CameraFilming.this, PhotoPreview.class); intent.putExtra("imageByte", data); //Picture data transfer to next activity startActivity(intent); } }; //take photo by pressing button private class captureBtnListener implements View.OnClickListener{ @Override public void onClick(View v){ capture.setOnClickListener(null); CountDownTimer timer = new CountDownTimer(10000, 1000){ @Override public void onTick(long millisUntilFinished) { // TODO Auto-generated method stub countdown.setText(millisUntilFinished/1000+""); } @Override public void onFinish() { // TODO Auto-generated method stub countdown.setText("0"); camera.takePicture(null, null, picture); } }; timer.start(); } } public class PhotoPreview extends Activity{ private RelativeLayout layout; private ImageView overlay, texture, face1, face2; @Override public void onCreate (Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.photo_preview); layout = (RelativeLayout)findViewById(R.id.preview_layout); byte[] data = getIntent().getByteArrayExtra("imageByte"); if (data == null){ Log.d("PhotoPreview", "no image data"); finish(); } Bitmap rawPhotoBitmap = BitmapFactory.decodeByteArray(data, 0, data.length); ImageProcess imgProcess = new ImageProcess(this); Bitmap resizedFace = imgProcess.scaleAccordingWidth(imgProcess.cropImage(rawPhotoBitmap, 840, 125, 440, 560), 77); face1 = new ImageView(this); face1.setImageBitmap(resizedFace); Log.d("testing", "testing"); } }

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >