Example usage for android.widget Toast LENGTH_LONG

List of usage examples for android.widget Toast LENGTH_LONG

Introduction

In this page you can find the example usage for android.widget Toast LENGTH_LONG.

Prototype

int LENGTH_LONG

To view the source code for android.widget Toast LENGTH_LONG.

Click Source Link

Document

Show the view or text notification for a long period of time.

Usage

From source file:com.eyekabob.EventList.java

protected void loadEvents(JSONObject response) {
    try {//from w  ww  .  j a v a2s . c o m
        JSONObject jsonEvents = response.optJSONObject("events");
        if (jsonEvents == null) {
            Toast.makeText(getApplicationContext(), R.string.no_results, Toast.LENGTH_LONG).show();
            return;
        }

        Object eventsObj = jsonEvents.get("event");
        JSONArray events;
        if (eventsObj instanceof JSONArray) {
            events = (JSONArray) eventsObj;
        } else {
            // For some incredibly stupid reason, a one item list is not a list.
            // So create a list and stick the one item in it.
            events = new JSONArray();
            events.put(eventsObj);
        }

        for (int i = 0; i < events.length(); i++) {
            Event event = new Event();
            Venue venue = new Venue();
            event.setVenue(venue);
            JSONObject jsonEvent = events.getJSONObject(i);
            JSONObject jsonVenue = jsonEvent.getJSONObject("venue");
            JSONObject jsonLocation = jsonVenue.getJSONObject("location");
            JSONObject jsonGeo = jsonLocation.optJSONObject("geo:point");

            event.setId(jsonEvent.getString("id"));
            event.setName(jsonEvent.getString("title"));
            event.setDate(EyekabobHelper.LastFM.toReadableDate(jsonEvent.getString("startDate")));
            JSONObject jsonImage = EyekabobHelper.LastFM.getJSONImage("large", jsonEvent.getJSONArray("image"));
            event.addImageURL("large", jsonImage.getString("#text"));

            venue.setName(jsonVenue.getString("name"));
            venue.setCity(jsonLocation.getString("city"));

            if (jsonGeo != null) {
                venue.setLat(jsonGeo.optString("geo:lat"));
                venue.setLon(jsonGeo.getString("geo:long"));
            }

            adapter.add(event);
        }
    } catch (JSONException e) {
        Log.e(getClass().getName(), "", e);
    }
}

From source file:org.ale.scanner.zotero.web.zotero.ZoteroHandler.java

protected void onStatusLine(APIRequest req, StatusLine status) {
    int reqType = req.getExtra().getInt(ZoteroAPIClient.EXTRA_REQ_TYPE);
    int code = status.getStatusCode();
    switch (code) {
    case 400: // Bad Request
        if (reqType == ZoteroAPIClient.ITEMS) {
            APIHandler.MAIN.uploadFailure(ZoteroAPIClient.FAILURE_REASON_BAD_DATA);
        }//from   ww w.jav  a  2s  .c  o m
        break;
    case 403: // Forbidden
        if (reqType == ZoteroAPIClient.PERMISSIONS) {
            // This shouldn't happen, but to avoid a permission checking
            // loop in case it does, erase key permissions and log out
            APIHandler.MAIN.erasePermissions();
            APIHandler.MAIN.postAccountPermissions(null);
        } else {
            // Maybe the key permissions changed, do a refresh
            APIHandler.MAIN.refreshPermissions();
        }

        if (reqType == ZoteroAPIClient.ITEMS) {
            APIHandler.MAIN.uploadFailure(ZoteroAPIClient.FAILURE_REASON_PERMISSION);
        }
        break;
    case 404: // Not Found
        if (reqType == ZoteroAPIClient.PERMISSIONS) {
            // The key wasn't found, wipe it out.
            APIHandler.MAIN.erasePermissions();
            APIHandler.MAIN.postAccountPermissions(null);
        }
        break;
    case 405: // Method Not Allowed
    case 409: // Conflict (Target library locked)
    case 412: // Precondition failed (X-Zotero-Write-Token duplicate)
    case 417: // Expectation Failed
        break;
    case 413: // Request Entity Too Large
        if (reqType == ZoteroAPIClient.ITEMS) {
            APIHandler.MAIN.uploadFailure(ZoteroAPIClient.FAILURE_REASON_BAD_DATA);
        }
        break;
    case 500: // Internal Server Error
    case 503: // Service Unavailable
        if (reqType == ZoteroAPIClient.ITEMS) {
            APIHandler.MAIN.uploadFailure(ZoteroAPIClient.FAILURE_REASON_SERV_ERR);
        }
        Toast.makeText(APIHandler.MAIN, code + ": Zotero server error, try again later.", Toast.LENGTH_LONG)
                .show();
        break;

    // We don't actually have to handle any of these, but I'm leaving them
    // here in case of future API changes.
    case 200: // OK
    case 201: // Created
    case 204: // No Content
    case 304: // Not Modified
    default:
        break;
    }
}

From source file:com.example.karspoolingapp.RouteByHitchhikerCar.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.routebyhitchhiker);

    Intent intent = getIntent();/*from   ww  w .ja  va  2 s  . c  o m*/
    Bundle bundle = intent.getExtras();
    new_license_number = bundle.getString("pre_end_point");
    //session_username = session.getUsername();
    System.out.println("nayaaa licnse number" + new_license_number);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

    StrictMode.setThreadPolicy(policy);

    // code for dynamic radio button generation
    final RadioButton[] rb = new RadioButton[100];
    rl = (RelativeLayout) findViewById(R.id.rl);
    rg = new RadioGroup(this);

    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("car_number", new_license_number));
    System.out.println(params);
    json = jsonParser.makeHttpRequest(READ_COMMENTS_URL2, "POST", params);
    params.clear();
    System.out.println(json);

    try {
        jsonTripDetails = json.getJSONArray("route");
        System.out.println(jsonTripDetails);
        int k = jsonTripDetails.length();
        if (k > 0) {
            for (int i = 0; i < jsonTripDetails.length(); i++) {
                JSONObject c = jsonTripDetails.getJSONObject(i);

                String parent_username_str = c.getString("username");
                String route = c.getString("route");
                String timing = c.getString("timing");
                String seating = c.getString("seating_capacity");
                rb[i] = new RadioButton(this);
                rg.addView(rb[i]);
                rb[i].setText(parent_username_str + "," + route + "," + timing + "," + seating);
                params.clear();

            }
            rl.addView(rg);
            rl.setPadding(50, 50, 50, 50);
        } else {
            Toast.makeText(RouteByHitchhikerCar.this, "No Trip available on these routes", Toast.LENGTH_LONG)
                    .show();
        }

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

    }

    addListenerOnButton();

}

From source file:fib.lcfib.raco.Controladors.ControladorLoginRaco.java

private void showAddDialog() {

    loginDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
            WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
    loginDialog.setTitle(R.string.loginRaco);

    LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View dialogView = li.inflate(R.layout.contingut_login, null);
    loginDialog.setContentView(dialogView);

    username = (EditText) dialogView.findViewById(R.id.login);
    password = (EditText) dialogView.findViewById(R.id.password);

    Button okButton = (Button) dialogView.findViewById(R.id.acceptar_button);
    Button cancelButton = (Button) dialogView.findViewById(R.id.cancel_button);
    loginDialog.setCancelable(false);/*from  w w w  .j  a v  a 2 s  . c  om*/
    loginDialog.show();

    okButton.setOnClickListener(new OnClickListener() {
        // @Override
        public void onClick(View v) {
            try {
                String usernameAux = username.getText().toString().trim();
                String passwordAux = password.getText().toString().trim();

                usernameAux = URLEncoder.encode(usernameAux, "UTF-8");
                passwordAux = URLEncoder.encode(passwordAux, "UTF-8");

                boolean correcte = check_user(usernameAux, passwordAux);
                if (correcte) {
                    Toast.makeText(getApplicationContext(), R.string.login_correcte, Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), R.string.errorLogin, Toast.LENGTH_LONG).show();
                }

                if ("zonaRaco".equals(queEs)) {
                    Intent intent = new Intent(ControladorLoginRaco.this, ControladorTabIniApp.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intent.putExtra("esLogin", "zonaRaco");
                    startActivity(intent);

                } else {
                    Intent act = new Intent(ControladorLoginRaco.this, ControladorTabIniApp.class);
                    // Aquestes 2 lnies provoquen una excepci per no peta
                    // simplement informa s normal
                    act.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    act.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(act);
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        private boolean check_user(String username, String password) {

            GestorCertificats.allowAllSSL();
            AndroidUtils au = AndroidUtils.getInstance();
            /** open connection */

            //Aix tanquem les connexions segur
            System.setProperty("http.keepAlive", "false");

            try {
                InputStream is = null;
                HttpGet request = new HttpGet(au.URL_LOGIN + "username=" + username + "&password=" + password);
                HttpClient client = new DefaultHttpClient();
                HttpResponse response = client.execute(request);
                final int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != HttpStatus.SC_OK) {
                    Header[] headers = response.getHeaders("Location");
                    if (headers != null && headers.length != 0) {
                        String newUrl = headers[headers.length - 1].getValue();
                        request = new HttpGet(newUrl);
                        client.execute(request);
                    }
                }

                /** Get Keys */
                is = response.getEntity().getContent();
                ObjectMapper m = new ObjectMapper();
                JsonNode rootNode = m.readValue(is, JsonNode.class);

                is.close();
                client.getConnectionManager().closeExpiredConnections();

                if (rootNode.isNull()) {
                    return false;
                } else {

                    // GenerarUrl();
                    /** calendari ics */
                    String KEYportadaCal = rootNode.path("/ical/portada.ics").getTextValue().toString();

                    /** calendari rss */
                    String KEYportadaRss = rootNode.path("/ical/portada.rss").getTextValue().toString();

                    /** Avisos */
                    String KEYavisos = rootNode.path("/extern/rss_avisos.jsp").getTextValue().toString();

                    /** Assigraco */
                    String KEYAssigRaco = rootNode.path("/api/assigList").getTextValue().toString();

                    /** Horari */
                    String KEYIcalHorari = rootNode.path("/ical/horari.ics").getTextValue().toString();

                    /**Notificacions */
                    String KEYRegistrar = rootNode.path("/api/subscribeNotificationSystem").getTextValue()
                            .toString();

                    String KEYDesregistrar = rootNode.path("/api/unsubscribeNotificationSystem").getTextValue()
                            .toString();

                    SharedPreferences sp = getSharedPreferences(PreferenciesUsuari.getPreferenciesUsuari(),
                            MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();

                    /** Save Username and Password */
                    editor.putString(AndroidUtils.USERNAME, username);
                    editor.putString(AndroidUtils.PASSWORD, password);

                    /** Save Keys */
                    editor.putString(au.KEY_AGENDA_RACO_XML, KEYportadaRss);
                    editor.putString(au.KEY_AGENDA_RACO_CAL, KEYportadaCal);
                    editor.putString(au.KEY_AVISOS, KEYavisos);
                    editor.putString(au.KEY_ASSIG_FIB, "public");
                    editor.putString(au.KEY_ASSIGS_RACO, KEYAssigRaco);
                    editor.putString(au.KEY_HORARI_RACO, KEYIcalHorari);
                    editor.putString(au.KEY_NOTIFICACIONS_REGISTRAR, KEYRegistrar);
                    editor.putString(au.KEY_NOTIFICACIONS_DESREGISTRAR, KEYDesregistrar);

                    /** Save changes */
                    editor.commit();
                }
                return true;

            } catch (ProtocolException e) {
                Toast.makeText(getApplicationContext(), R.string.errorLogin, Toast.LENGTH_LONG).show();
                return false;
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(), R.string.errorLogin, Toast.LENGTH_LONG).show();
                return false;
            }

        }
    });

    cancelButton.setOnClickListener(new OnClickListener() {
        // @Override
        public void onClick(View v) {
            Intent act = new Intent(ControladorLoginRaco.this, ControladorTabIniApp.class);
            act.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            act.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(act);
        }
    });

}

From source file:com.filelocker.andy.MainActivity.java

public void lockButton_Click(View view) {

    TextView vPasswordText = (TextView) findViewById(R.id.passwordText);
    TextView vFileChooserText = (TextView) findViewById(R.id.fileChooserText);

    String myPassword = vPasswordText.getText().toString();

    vPasswordText.setText("");

    if (vFileChooserText.getText().toString().equals("") || myPassword.equals("")) {
        Toast toast;//from   w ww.  j  a v  a  2s  . c o  m
        if (vFileChooserText.getText().toString().equals("")) {
            toast = Toast.makeText(getApplicationContext(), "File Not Choosen", Toast.LENGTH_LONG);
            toast.show();
        } else if (myPassword.equals("")) {
            toast = Toast.makeText(getApplicationContext(), "Password Field Empty", Toast.LENGTH_LONG);
            toast.show();
        }

        return;
    } else if (!(vFileChooserText.getText().toString()
            .substring(vFileChooserText.getText().toString().lastIndexOf('.') + 1).equals("encrypt"))) {

        AES_Encryption en = new AES_Encryption(myPassword);
        /*
         * setup encryption cipher using password. print out iv and salt
         */
        try {
            File vInFile = new File(vFileChooserText.getText().toString());

            if (vInFile.exists() == false) {
                throw new FileNotFoundException("File Not Found");
            }

            en.setupEncrypt();
        } catch (InvalidKeyException ex) {
            ex.printStackTrace();
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        } catch (InvalidKeySpecException ex) {
            ex.printStackTrace();
        } catch (NoSuchPaddingException ex) {
            ex.printStackTrace();
        } catch (InvalidParameterSpecException ex) {
            ex.printStackTrace();
        } catch (IllegalBlockSizeException ex) {
            ex.printStackTrace();
        } catch (BadPaddingException ex) {
            ex.printStackTrace();
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }

        /*
         * write out encrypted file
         */
        try {

            File vInFile = new File(vFileChooserText.getText().toString());
            File vOutFile = new File(vFileChooserText.getText().toString() + ".encrypt");

            if (vInFile.exists() == false) {
                throw new FileNotFoundException("File Not Found");
            }

            en.WriteEncryptedFile(vInFile, vOutFile);

            Toast toast = Toast.makeText(getApplicationContext(), "Encryption Complete", Toast.LENGTH_LONG);
            toast.show();
            vInFile.delete();

        } catch (IllegalBlockSizeException ex) {
            ex.printStackTrace();
        } catch (BadPaddingException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    } else {

        /*
         * decrypt file
         */
        AES_Encryption dc = new AES_Encryption(myPassword);
        try {
            File vInFile = new File(vFileChooserText.getText().toString());

            if (vInFile.exists() == false) {
                throw new FileNotFoundException("File Not Found");
            }

            dc.setupDecrypt(vInFile);
        } catch (InvalidKeyException ex) {
            ex.printStackTrace();
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        } catch (InvalidKeySpecException ex) {
            ex.printStackTrace();
        } catch (NoSuchPaddingException ex) {
            ex.printStackTrace();
        } catch (InvalidAlgorithmParameterException ex) {
            ex.printStackTrace();
        } catch (DecoderException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {

            ex.printStackTrace();
        }

        /*
         * write out decrypted file
         */
        try {
            File vInFile = new File(vFileChooserText.getText().toString());
            File vOutFile = new File(vFileChooserText.getText().toString().substring(0,
                    vFileChooserText.getText().toString().length() - 8));

            if (vInFile.exists() == false) {
                throw new FileNotFoundException("File Not Found");
            }

            dc.ReadEncryptedFile(vInFile, vOutFile);
            vInFile.delete();

            Toast toast = Toast.makeText(getApplicationContext(), "Decryption Complete", Toast.LENGTH_LONG);
            toast.show();
        } catch (IllegalBlockSizeException ex) {
            ex.printStackTrace();
        } catch (BadPaddingException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}

From source file:com.chess.genesis.activity.GameListOnlineFrag.java

@Override
public boolean handleMessage(final Message msg) {
    switch (msg.what) {
    case DeleteArchiveDialog.MSG:
    case ReadAllMsgsDialog.MSG:
        updateGameList();//  w  w w. j a  v  a2 s . co  m
        break;
    case NewOnlineGameDialog.MSG:
        Bundle data = (Bundle) msg.obj;

        if (data.getInt("opponent") == Enums.INVITE) {
            new InviteOptionsDialog(act, handle, data).show();
            return true;
        }
        progress.setText("Sending Newgame Request");
        String gametype = Enums.GameType(data.getInt("gametype"));

        net.join_game(gametype);
        new Thread(net).start();
        break;
    case RematchConfirm.MSG:
        data = (Bundle) msg.obj;
        progress.setText("Sending Newgame Request");

        final String opponent = data.getString("opp_name");
        String color = Enums.ColorType(data.getInt("color"));
        gametype = Enums.GameType(data.getInt("gametype"));

        net.new_game(opponent, gametype, color);
        new Thread(net).start();
        break;
    case NudgeConfirm.MSG:
        progress.setText("Sending Nudge");

        final String gameid = (String) msg.obj;
        net.nudge_game(gameid);
        new Thread(net).start();
        break;
    case InviteOptionsDialog.MSG:
        data = (Bundle) msg.obj;
        progress.setText("Sending Newgame Request");

        gametype = Enums.GameType(data.getInt("gametype"));
        color = Enums.ColorType(data.getInt("color"));

        net.new_game(data.getString("opp_name"), gametype, color);
        new Thread(net).start();
        break;
    case SyncClient.MSG:
    case NetworkClient.JOIN_GAME:
        JSONObject json = (JSONObject) msg.obj;
        try {
            if (json.getString("result").equals("error")) {
                progress.remove();
                Toast.makeText(act, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
                return true;
            }
            if (msg.what == SyncClient.MSG || msg.what == NetworkClient.JOIN_GAME) {
                progress.setText("Checking Game Pool");
                updateGameList();
                GenesisNotifier.clearNotification(act,
                        GenesisNotifier.YOURTURN_NOTE | GenesisNotifier.NEWMGS_NOTE);
                net.pool_info();
                new Thread(net).start();
            } else {
                progress.remove();
            }
        } catch (final JSONException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        break;
    case NetworkClient.POOL_INFO:
        json = (JSONObject) msg.obj;
        try {
            if (json.getString("result").equals("error")) {
                progress.remove();
                Toast.makeText(act, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
                return true;
            }
            final JSONArray games = json.getJSONArray("games");
            final PrefEdit pref = new PrefEdit(act);
            pref.putString(R.array.pf_poolinfo, games.toString());
            pref.commit();

            act.findViewById(R.id.game_search).setVisibility((games.length() == 0) ? View.GONE : View.VISIBLE);

            progress.remove();
        } catch (final JSONException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        break;
    case NetworkClient.NEW_GAME:
    case NetworkClient.NUDGE_GAME:
        json = (JSONObject) msg.obj;
        try {
            if (json.getString("result").equals("error")) {
                progress.remove();
                Toast.makeText(act, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
                return true;
            }
            progress.setText("Updating Game List");
            final SyncClient sync = new SyncClient(act, handle);
            new Thread(sync).start();
        } catch (final JSONException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        break;
    }
    return true;
}

From source file:com.example.run_tracker.ProfileFragment.java

private void Make_get_profile_request() {

    JSONObject credentials = null;//from   w w w . j  av  a  2 s.c o  m
    try {
        credentials = new JSONObject();
        credentials.put("token", ((MainActivity) getActivity()).getToken());

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

    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, URLS.URL_PROFILE, credentials,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    try {
                        mUsername.setText(response.getString("username"));
                        mName.setText(response.getString("name"));
                        mSurname.setText(response.getString("surname"));

                    } catch (JSONException e) {

                        try {
                            Toast.makeText(getActivity(), response.getString("error"), Toast.LENGTH_LONG)
                                    .show();
                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                        e.printStackTrace();
                    }

                    Log.v(TAG, response.toString());
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                }
            }) {
        /**
         * Passing some request headers token and content type
         * */
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put("x-access-token", ((MainActivity) getActivity()).getToken());
            return headers;
        }
    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq, TAG);

    // Cancelling request
    // ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_obj);
}

From source file:com.aniruddhc.acemusic.player.AsyncTasks.AsyncCopyMoveTask.java

@Override
protected void onPostExecute(Boolean result) {
    super.onPostExecute(result);

    pd.dismiss();/*from w w w  .j a  v  a 2  s .c  o m*/
    if (result == true) {
        if (mShouldMove)
            Toast.makeText(mContext, R.string.done_move, Toast.LENGTH_SHORT).show();
        else
            Toast.makeText(mContext, R.string.done_copy, Toast.LENGTH_SHORT).show();
    } else {
        if (mShouldMove)
            Toast.makeText(mContext, R.string.file_could_not_be_written_new_location, Toast.LENGTH_LONG).show();
        else
            Toast.makeText(mContext, R.string.file_could_not_be_written_new_location, Toast.LENGTH_LONG).show();
    }

    try {
        mFragment.refreshListView();
    } catch (Exception e) {
        e.printStackTrace();
    } catch (Error er) {
        er.printStackTrace();
    }

}

From source file:com.chess.genesis.engine.GameState.java

@Override
public boolean handleMessage(final Message msg) {
    try {//ww w .j a  v a 2  s  .  c o m
        switch (msg.what) {
        case GenEngine.MSG:
        case RegEngine.MSG:
            final Bundle bundle = (Bundle) msg.obj;

            if (bundle.getLong("time") == 0) {
                cpu.setBoard(board);
                new Thread(cpu).start();
                return true;
            } else if (activity.isFinishing()) {
                // activity is gone, so give up!
                return true;
            }
            currentMove();

            final Move tmove = bundle.getParcelable("move");
            final Move move = board.newMove();
            if (board.validMove(tmove, move))
                applyMove(move, true, true);
            break;
        case CpuTimeDialog.MSG:
            final PrefEdit pref = new PrefEdit(activity);
            pref.putInt(R.array.pf_cputime, (Integer) msg.obj);
            pref.commit();
            cpu.setTime((Integer) msg.obj);
            break;
        case NetworkClient.GAME_DRAW:
        case NetworkClient.SUBMIT_MOVE:
            JSONObject json = (JSONObject) msg.obj;

            if (json.getString("result").equals("error")) {
                undoMove();
                progress.remove();
                Toast.makeText(activity, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
                return true;
            }
            progress.setText("Checking Game Status");

            net.game_status(settings.getString("gameid"));
            new Thread(net).start();
            break;
        case ResignConfirm.MSG:
            progress.setText("Sending Resignation");

            net.resign_game(settings.getString("gameid"));
            new Thread(net).start();
            break;
        case NudgeConfirm.MSG:
            progress.setText("Sending Nudge");

            net.nudge_game(settings.getString("gameid"));
            new Thread(net).start();
            break;
        case IdleResignConfirm.MSG:
            progress.setText("Sending Idle Resign");

            net.idle_resign(settings.getString("gameid"));
            new Thread(net).start();
            break;
        case DrawDialog.MSG:
        case AcceptDrawDialog.MSG:
            final String value = (String) msg.obj;
            progress.setText("Sending Draw");

            net.game_draw(settings.getString("gameid"), value);
            new Thread(net).start();
            break;
        case PawnPromoteDialog.MSG:
            applyMove((RegMove) msg.obj, true, true);
            break;
        case NetworkClient.RESIGN_GAME:
        case NetworkClient.IDLE_RESIGN:
            json = (JSONObject) msg.obj;

            if (json.getString("result").equals("error")) {
                progress.remove();
                Toast.makeText(activity, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
                return true;
            }
            progress.setText("Resignation Sent");

            net.game_status(settings.getString("gameid"));
            new Thread(net).start();
            break;
        case NetworkClient.NUDGE_GAME:
            json = (JSONObject) msg.obj;

            if (json.getString("result").equals("error"))
                Toast.makeText(activity, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
            progress.remove();
            break;
        case NetworkClient.GAME_STATUS:
            json = (JSONObject) msg.obj;

            if (json.getString("result").equals("error")) {
                progress.remove();
                Toast.makeText(activity, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
                return true;
            }
            final int status = Enums.GameStatus(json.getString("status"));

            settings.putString("status", String.valueOf(status));

            final GameDataDB db = new GameDataDB(activity);
            db.updateOnlineGame(json);
            db.close();
            GenesisNotifier.clearNotification(activity, GenesisNotifier.YOURTURN_NOTE);

            applyRemoteMove(json.getString("history"));
            if (status != Enums.ACTIVE) {
                if (Integer.parseInt(settings.getString("eventtype")) == Enums.INVITE) {
                    progress.remove();
                    ShowGameStats(json);
                    return true;
                }
                progress.setText("Retrieving Score");

                net.game_score(settings.getString("gameid"));
                new Thread(net).start();
            } else {
                progress.setText("Status Synced");
                progress.remove();
            }
            break;
        case NetworkClient.GAME_SCORE:
            json = (JSONObject) msg.obj;

            if (json.getString("result").equals("error")) {
                progress.remove();
                Toast.makeText(activity, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
                return true;
            }
            progress.setText("Score Loaded");
            progress.remove();

            ShowGameStats(json);
            break;
        case RematchConfirm.MSG:
            final Bundle data = (Bundle) msg.obj;
            progress.setText("Sending Newgame Request");

            final String opponent = data.getString("opp_name");
            final String color = Enums.ColorType(data.getInt("color"));
            final String gametype = Enums.GameType(data.getInt("gametype"));

            net.new_game(opponent, gametype, color);
            new Thread(net).start();
            break;
        case NetworkClient.NEW_GAME:
            json = (JSONObject) msg.obj;

            if (json.getString("result").equals("error")) {
                progress.remove();
                Toast.makeText(activity, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
                return true;
            }
            progress.setText(json.getString("reason"));
            progress.remove();
            break;
        }
        return true;
    } catch (final JSONException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:net.networksaremadeofstring.cyllell.ViewRoles_Fragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    list = (ListView) this.getActivity().findViewById(R.id.rolesListView);
    settings = this.getActivity().getSharedPreferences("Cyllell", 0);
    try {/*from ww  w . jav  a  2 s .  c  o m*/
        Cut = new Cuts(getActivity());
    } catch (Exception e) {
        e.printStackTrace();
    }

    dialog = new ProgressDialog(getActivity());
    dialog.setTitle("Contacting Chef");
    dialog.setMessage("Please wait: Prepping Authentication protocols");
    dialog.setIndeterminate(true);
    if (listOfRoles.size() < 1) {
        dialog.show();
    }

    updateListNotify = new Handler() {
        public void handleMessage(Message msg) {
            int tag = msg.getData().getInt("tag", 999999);

            if (msg.what == 0) {
                if (tag != 999999) {
                    listOfRoles.get(tag).SetSpinnerVisible();
                }
            } else if (msg.what == 1) {
                //Get rid of the lock
                CutInProgress = false;

                //the notifyDataSetChanged() will handle the rest
            } else if (msg.what == 99) {
                if (tag != 999999) {
                    Toast.makeText(ViewRoles_Fragment.this.getActivity(),
                            "An error occured during that operation.", Toast.LENGTH_LONG).show();
                    listOfRoles.get(tag).SetErrorState();
                }
            }
            RoleAdapter.notifyDataSetChanged();
        }
    };

    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            //Once we've checked the data is good to use start processing it
            if (msg.what == 0) {
                OnClickListener listener = new OnClickListener() {
                    public void onClick(View v) {
                        GetMoreDetails((Integer) v.getTag());
                    }
                };

                OnLongClickListener listenerLong = new OnLongClickListener() {
                    public boolean onLongClick(View v) {
                        selectForCAB((Integer) v.getTag());
                        return true;
                    }
                };

                RoleAdapter = new RoleListAdaptor(getActivity(), listOfRoles, listener, listenerLong);
                list = (ListView) getView().findViewById(R.id.rolesListView);
                if (list != null) {
                    if (RoleAdapter != null) {
                        list.setAdapter(RoleAdapter);
                    } else {
                        //Log.e("CookbookAdapter","CookbookAdapter is null");
                    }
                } else {
                    //Log.e("List","List is null");
                }

                dialog.dismiss();
            } else if (msg.what == 200) {
                dialog.setMessage("Sending request to Chef...");
            } else if (msg.what == 201) {
                dialog.setMessage("Parsing JSON.....");
            } else if (msg.what == 202) {
                dialog.setMessage("Populating UI!");
            } else {
                //Close the Progress dialog
                dialog.dismiss();

                //Alert the user that something went terribly wrong
                AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
                alertDialog.setTitle("API Error");
                alertDialog.setMessage("There was an error communicating with the API:\n"
                        + msg.getData().getString("exception"));
                alertDialog.setButton2("Back", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        //getActivity().finish();
                    }
                });
                alertDialog.setIcon(R.drawable.icon);
                alertDialog.show();
            }
        }
    };

    Thread dataPreload = new Thread() {
        public void run() {
            if (listOfRoles.size() > 0) {
                handler.sendEmptyMessage(0);
            } else {
                try {
                    handler.sendEmptyMessage(200);
                    Roles = Cut.GetRoles();
                    handler.sendEmptyMessage(201);

                    JSONArray Keys = Roles.names();

                    for (int i = 0; i < Keys.length(); i++) {
                        listOfRoles.add(new Role(Keys.getString(i), Roles.getString(Keys.getString(i))
                                .replaceFirst("^(https://|http://).*/roles/", "")));
                    }

                    handler.sendEmptyMessage(202);
                    handler.sendEmptyMessage(0);
                } catch (Exception e) {
                    Message msg = new Message();
                    Bundle data = new Bundle();
                    data.putString("exception", e.getMessage());
                    msg.setData(data);
                    msg.what = 1;
                    handler.sendMessage(msg);
                }
            }
            return;
        }
    };

    dataPreload.start();
    return inflater.inflate(R.layout.roles_landing, container, false);
}