Ir para conteúdo

Pesquisar na Comunidade

Mostrando resultados para as tags ''android''.

  • Pesquisar por Tags

    Digite tags separadas por vírgulas
  • Pesquisar por Autor

Tipo de Conteúdo


Todas as áreas do Fórum

  • Q&A Desenvolvimento
    • Perguntas e respostas rápidas
  • Desenvolvimento Web
    • Desenvolvimento frontend
    • Javascript
    • PHP
    • Ruby
    • Python
    • Java
    • .NET
    • Docker, Kubernets e outros ambientes
    • Desenvolvimento com Wordpress
    • Desenvolvimento de apps
    • Desenvolvimento ágil
    • Desenvolvimento de Games
    • Banco de Dados
    • Design e UX
    • Algoritmos & Outras Tecnologias
  • Entretenimento e uso pessoal
    • Segurança & Malwares
    • Geral
    • Boteco iMasters

Encontrar resultados em...

Encontrar resultados que...


Data de Criação

  • Início

    FIM


Data de Atualização

  • Início

    FIM


Filtrar pelo número de...

Data de Registro

  • Início

    FIM


Grupo


Google+


Hangouts


Skype


Twitter


deviantART


Github


Flickr


LinkedIn


Pinterest


Facebook


Site Pessoal


Localização


Interesses

Encontrado 47 registros

  1. Marcosjrpb

    ...

    ...
  2. Eu tenho minha tela de busca. Ao digitar, ele traz o resultado da busca. O resultado é mostrado em uma recyclerview. Meu Recyclerview foi modelado com algumas textviews e uma imagem. Queria que ao tocar no item da Recyclerview, que o texto da textview fosse passado para outra fragment (tela) que tenho. Consigo fazer até a parte da chamada da tela. Só não consigo resgatar o texto da textview na outra tela. Cheguei até a instanciar as textviews da outra tela que esta modelada o recycler. Minha classe do adaptador: public class CursosAdapterImg extends RecyclerView.Adapter<CursosAdapterImg.CursosHolder> { List<Curso>listaCursos; private OnNoteListener mOnNoteListener; public CursosAdapterImg(List<Curso> listaCursos, Context context,OnNoteListener onNoteListener) { this.listaCursos = listaCursos; this.mOnNoteListener = onNoteListener; } @NonNull @Override public CursosHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View vista = LayoutInflater.from(parent.getContext()).inflate(R.layout.lista_cursos_img, parent, false); RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ); vista.setLayoutParams(layoutParams); return new CursosHolder(vista, mOnNoteListener); } @Override public void onBindViewHolder(@NonNull CursosHolder holder, int position) { // holder.txtCodigo.setText(listaCursos.get(position).getCodigo().toString()); holder.txtNome.setText(listaCursos.get(position).getNome().toString()); holder.txtProfessor.setText(listaCursos.get(position).getProfessor().toString()); holder.txtCategoria.setText(listaCursos.get(position).getCategoria().toString()); if(listaCursos.get(position).getImagem()!=null){ holder.idImagem.setImageBitmap(listaCursos.get(position).getImagem()); }else{ holder.idImagem.setImageResource(R.drawable.sem_foto); } } @Override public int getItemCount() { return listaCursos.size(); } public class CursosHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView txtNome,txtCodigo,txtProfessor, txtCategoria; ImageView idImagem; OnNoteListener onNoteListener; public CursosHolder(View itemView,OnNoteListener onNoteListener) { super(itemView); txtNome= (TextView) itemView.findViewById(R.id.nomeCurso); //txtCodigo= (TextView) itemView.findViewById(R.id.txtCodigo); txtProfessor= (TextView) itemView.findViewById(R.id.Professor); txtCategoria= (TextView) itemView.findViewById(R.id.Categoria); idImagem= itemView.findViewById(R.id.idImagem); this.onNoteListener = onNoteListener; itemView.setOnClickListener(this); } @Override public void onClick(View view) { onNoteListener.onNoteClick(getAdapterPosition()); } } public interface OnNoteListener{ void onNoteClick(int position); } } Abaixo a minha tela da busca que retorna uma Recyclerview: return vista; } private void carregarWEBService() { progresso = new ProgressDialog(getContext()); progresso.setMessage("Buscando..."); progresso.show(); String url = "http://192.168.0.5/webservices/consultarListaImagemUrlNome.php?nome="+ campoNome.getText().toString(); jsonObjectReq = new JsonObjectRequest(Request.Method.GET, url, null, this, this); request.add(jsonObjectReq); } @Override public void onErrorResponse(VolleyError error) { progresso.hide(); Toast.makeText(getContext(), "Não foi possível listar os cursos " +error.toString() , Toast.LENGTH_SHORT).show(); Log.i("ERROR", error.toString()); } @Override public void onResponse(JSONObject response) { progresso.hide(); Curso curso = null; JSONArray json = response.optJSONArray("curso"); // nome da tabela curso try { for(int i=0; i<json.length();i++){ curso = new Curso(); JSONObject jsonObject = null; jsonObject = json.getJSONObject(i); curso.setNome(jsonObject.optString("nome")); curso.setProfessor(jsonObject.optString("professor")); curso.setCategoria(jsonObject.optString("categoria")); curso.setDado(jsonObject.optString("imagem")); listaCursos.add(curso); } progresso.hide(); CursosAdapterImg adapter = new CursosAdapterImg(listaCursos,getContext(),this); recyclerCursos.setAdapter(adapter); }catch (JSONException e){ e.printStackTrace(); progresso.hide(); Toast.makeText(getContext(), "Não foi possível listar os cursos " +response , Toast.LENGTH_SHORT).show(); } } @Override public void onNoteClick(int position) { listaCursos.get(position); //Falta passar os parâmetros consultarCursoUrl fragmentConsulta = new consultarCursoUrl(); /* Estava testando nesse bloco passagem de parâmetros para outra fragment Bundle arguments = new Bundle(); arguments.putString( "professor" , "Testando a passagem"); fragmentConsulta.setArguments(arguments); */ FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.content_main,fragmentConsulta).commit(); } E esse código abaixo, é minha tela que é chamada após tocar no item do recyclerview: @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View vista = inflater.inflate(R.layout.fragment_consultar_curso_url, container, false); campoCodigo = vista.findViewById(R.id.codigo); campoNome = vista.findViewById(R.id.txt_nome); campoCategoria = vista.findViewById(R.id.txt_categoria); campoProfessor = vista.findViewById(R.id.txt_professor); btnAtualizar = vista.findViewById(R.id.btnAtualizar); btnDeletar = vista.findViewById(R.id.btnDeletar); btnConsultar = vista.findViewById(R.id.btnConsultar); imgFoto = vista.findViewById(R.id.imagemId); /* Estava fazendo teste de parametros nesse bloco Bundle arguments = getArguments(); String nomeProfessor = arguments.getString("professor"); campoNome.setText(nomeProfessor); */ request = Volley.newRequestQueue(getContext()); btnConsultar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { carregarWEBService(); } }); if(solicitarPermissoesVersoesSuperiores()){ imgFoto.setEnabled(true); }else{ imgFoto.setEnabled(false); } imgFoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { carregarDialog(); } }); btnAtualizar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { carregarWEBServiceAtualizar(); } }); btnDeletar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { carregarWEBServiceDeletar(); } }); return vista; }
  3. vinihhylian0103

    DATABASE IS LOCKED DELPHI MOBILE

    Estou fazendo um projeto de Delphi escola e nele tenho que gravar dados no SQLITE. Estou usando o seguinte código: unit UClube; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListView.Types, FMX.ListView.Appearances, FMX.ListView.Adapters.Base, FMX.StdCtrls, FMX.ListView, FMX.DateTimeCtrls, FMX.Edit, FMX.Controls.Presentation, FMX.TabControl, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.FMXUI.Wait, System.Rtti, System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.EngExt, Fmx.Bind.DBEngExt, Data.DB, FireDAC.Comp.DataSet, Data.Bind.Components, Data.Bind.DBScope, FireDAC.Comp.UI, FireDAC.Comp.Client, System.IOUtils; type TForm1 = class(TForm) TabControl1: TTabControl; TabItem2: TTabItem; tb1: TTabItem; lvSocio: TListView; btnSalvar: TButton; btnCancelar: TButton; btnEditar: TButton; btnExcluirr: TButton; Panel1: TPanel; edtDataNasc: TDateEdit; edtCod: TEdit; edtNome: TEdit; edtRg: TEdit; edtCPF: TEdit; edtEndereco: TEdit; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; labwl: TLabel; NOME: TLabel; Button5: TButton; Panel2: TPanel; edtDataA: TDateEdit; edtCodSocio: TEdit; Label6: TLabel; Label10: TLabel; Label11: TLabel; Label12: TLabel; rdbSocio: TRadioButton; edtNomeA: TEdit; btnNovoA: TButton; edtHoraIA: TEdit; Label7: TLabel; Edit7: TEdit; edtHoraFA: TLabel; edtDescricaoA: TEdit; Label9: TLabel; edtValorA: TEdit; btnCancelarA: TButton; btnEditarA: TButton; btnExcluirA: TButton; btnSalvarA: TButton; lvAgendamento: TListView; FDConnPrincipal: TFDConnection; qrSocio: TFDQuery; qrAgendamento: TFDQuery; FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink; FDGUIxWaitCursor1: TFDGUIxWaitCursor; BindSourceDB1: TBindSourceDB; BindingsList1: TBindingsList; LinkListControlToField1: TLinkListControlToField; LinkControlToField1: TLinkControlToField; LinkControlToField2: TLinkControlToField; LinkControlToField3: TLinkControlToField; LinkControlToField4: TLinkControlToField; LinkControlToField5: TLinkControlToField; LinkControlToField6: TLinkControlToField; qrSocioID: TFDAutoIncField; qrSocioNOME: TStringField; qrSocioRG: TStringField; qrSocioCPF: TStringField; qrSocioENDERECO: TStringField; qrSocioDATA_NASC: TDateField; qrSocioCODIGO: TIntegerField; qrAgendamentoID: TFDAutoIncField; qrAgendamentoNOME: TStringField; qrAgendamentoCODIGO: TIntegerField; qrAgendamentoDESCRICAO: TWideMemoField; qrAgendamentoDATA: TDateField; qrAgendamentoHORA_INICIO: TStringField; qrAgendamentoHORARIO_FIM: TStringField; qrAgendamentoVALOR: TLargeintField; qrAgendamentoSOCIO: TStringField; procedure rdbSocioChange(Sender: TObject); procedure btnSalvarClick(Sender: TObject); procedure Button5Click(Sender: TObject); procedure btnCancelarClick(Sender: TObject); procedure btnEditarClick(Sender: TObject); procedure btnExcluirrClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} procedure TForm1.btnCancelarClick(Sender: TObject); begin qrSocio.Cancel; Panel1.Enabled := False; end; procedure TForm1.btnEditarClick(Sender: TObject); begin if qrSocio.RecordCount > 0 then begin qrSocio.Edit; Panel1.Enabled := True; edtNome.SetFocus; end; end; procedure TForm1.btnExcluirrClick(Sender: TObject); begin if qrSocio.RecordCount = 0 then abort; qrSocio.Delete; ShowMessage('Dados excluídos!'); end; procedure TForm1.btnSalvarClick(Sender: TObject); begin if edtNome.Text = '' then begin ShowMessage('O nome não pode estar vázio!'); edtNome.SetFocus; abort; end; qrSocio.Post; qrSocio.Refresh; Panel1.Enabled := False; end; procedure TForm1.Button5Click(Sender: TObject); begin Panel1.Enabled := True; edtNome.SetFocus; qrSocio.Append; end; procedure TForm1.FormShow(Sender: TObject); begin FDConnPrincipal.Connected := True; try {$IF DEFINED (IOS) or DEFINED (ANDROID)} FDConnPrincipal.Params.Values['DATABASE'] := TPath.Combine(TPath.GetDocumentsPath, 'BD_CLUBE.s3db'); {$ENDIF} except on E: Exception do ShowMessage(e.Message); end; qrSocio.Open(); end; procedure TForm1.rdbSocioChange(Sender: TObject); begin if rdbSocio.IsChecked = true then begin edtCodSocio.Enabled := true; edtCodSocio.SetFocus; end; end; end. E recebo o seguinte erro:
  4. Pessoal criei um app Webview, com leitor de código de barra, porém tiver que utilizar a Bíblioteca zxing barcode, tá funcionando só que é queria que ao ler o código de barra, no lugar do alert fizesse um redirecionamento com código via get para tá salvando com php no banco de dados. creio que seja uma função simples um redirecionamento, como tenho conhecimento somente com php, tenho dificuldades com Java do Android.
  5. cristianomg

    Resgatar um dado especifico de um nó filho Firebase

    Preciso de uma orientação estou iniciando com programação para android, e tenho o seguinte caso. Possuo dois models Usuario e Anuncio, Quando eu crio um novo usuario e cadastro ele eu adiciono os seguintes dados: Quando eu salvo um anuncio do usuario acima por exemplo, eu quero implementar um contador e adicionar +1 no campo qtdAnuncio, ai vem minha pergunta Como eu posso fazer ao exemplo clicar no botão de cadastrar anuncio e colocar dentro de uma variavel o valor do campo qtdAnuncio que esta salvo o dado no nó de usuario? Ex: int valorAnuncios = qtdAnuncio que seria 1 Eu preciso primeiramente resgatar este campo qtdAnuncio do usuario logado Eu tentei nomear private Usuario usuarioLogado; e xecutar a chamada de um metodo usuarioLogado = UsuarioFirebase.getDadosUsuarioLogado() Método chamado public static Usuario getDadosUsuarioLogado(){ FirebaseUser firebaseUser = getUsuarioAtual(); Usuario usuario = new Usuario(); usuario.setEmail( firebaseUser.getEmail() ); usuario.setNome( firebaseUser.getDisplayName().toUpperCase() ); usuario.setId( firebaseUser.getUid() ); return usuario; } E depois em uma dado momento dentro do meu código no @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_editar_perfil); //validar permissoes Permissao.validarPermissoes(permissoesNecessarias, this, 1); //configuracoes iniciais usuarioLogado = UsuarioFirebase.getDadosUsuarioLogado(); //Tentei aqui buscar o valor do qtdAnuncio desta forma int valor = String.valueof(usuariologado.getQtdAnuncio()); Só que ao depurar o valor é sempre zero , sendo que tenho qtdAnuncio = 1 no banco do firebase, cfe imagem no inicio Alguém pode me orientar como pegar este valor ??
  6. gamesmax2

    Abir links no navegador

    Pessoal sou novo com crianção de app android, este app e bastante simples utilizar webview. Estou com um problema, queria abrir link externo que não seja do meu site no navegador do celular, meu código abrir todos os links externo no meu app. exemplo quero que links externo sejam aberto no navegador e link como Youtube ou que utilizar algum app do celular seja aberto nesse app, segue meu codigo: public class MainActivity extends AppCompatActivity { private WebView cash; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cash = findViewById(R.id.site); cash.getSettings().setJavaScriptEnabled(true); cash.setFocusable(true); cash.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); cash.getSettings().setAppCacheEnabled(true); cash.getSettings().setDomStorageEnabled(true); cash.setWebViewClient(new WebViewClient()); cash.setWebChromeClient(new Meusite()); cash.loadUrl("https://www.meusite.com.br/meu_site/"); } private class Meusite extends WebChromeClient { private View mCustomView; private WebChromeClient.CustomViewCallback mCustomViewCallback; protected FrameLayout mFullscreenContainer; private int mOriginalOrientation; private int mOriginalSystemUiVisibility; Meusite() {} public Bitmap getDefaultVideoPoster() { if (mCustomView == null) { return null; } return BitmapFactory.decodeResource(getApplicationContext().getResources(), 2130837573); } public void onHideCustomView() { ((FrameLayout)getWindow().getDecorView()).removeView(this.mCustomView); this.mCustomView = null; getWindow().getDecorView().setSystemUiVisibility(this.mOriginalSystemUiVisibility); setRequestedOrientation(this.mOriginalOrientation); this.mCustomViewCallback.onCustomViewHidden(); this.mCustomViewCallback = null; } public void onShowCustomView(View paramView, WebChromeClient.CustomViewCallback paramCustomViewCallback) { if (this.mCustomView != null) { onHideCustomView(); return; } this.mCustomView = paramView; this.mOriginalSystemUiVisibility = getWindow().getDecorView().getSystemUiVisibility(); this.mOriginalOrientation = getRequestedOrientation(); this.mCustomViewCallback = paramCustomViewCallback; ((FrameLayout)getWindow().getDecorView()).addView(this.mCustomView, new FrameLayout.LayoutParams(-1, -1)); getWindow().getDecorView().setSystemUiVisibility(3846); } } @Override public void onBackPressed() { if (cash.canGoBack()) { cash.goBack(); } else { super.onBackPressed(); } } }
  7. Elias Camilo Mendes

    react-native run android

    Olá galera estou iniciando um projeto com react-native mas estou tendo sérios problemas até o momento em tentar rodar o código no emulador do android studio, até o momento ainda não fiz mudanças nos arquivos do projeto, estão do jeito que foram instalado. Se alguém puder me ajudar estarei grato, segue o erro : Starting a Gradle Daemon, 1 incompatible and 1 stopped Daemons could not be reused, use --status for details FAILURE: Build failed with an exception. What went wrong: A problem occurred configuring project ':app'. SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at '/home/eliascmendhes/my_pet/android/local.properties'. Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. Get more help at https://help.gradle.org BUILD FAILED in 28s error Failed to install the app. Make sure you have the Android development environment set up: https://facebook.github.io/react-native/docs/getting-started.html#android-development-environment. Run CLI with --verbose flag for more details. Error: Command failed: ./gradlew app:installDebug -PreactNativeDevServerPort=8081 FAILURE: Build failed with an exception. What went wrong: A problem occurred configuring project ':app'. SDK location not found. Define location with an ANDROID_SDK_ROOT environment variable or by setting the sdk.dir path in your project's local properties file at '/home/eliascmendhes/my_pet/android/local.properties'. Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. Get more help at https://help.gradle.org BUILD FAILED in 28s at checkExecSyncError (child_process.js:601:13) at execFileSync (child_process.js:621:13) at runOnAllDevices (/home/eliascmendhes/my_pet/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/runOnAllDevices.js:74:39) at buildAndRun (/home/eliascmendhes/my_pet/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/index.js:158:41) at then.result (/home/eliascmendhes/my_pet/node_modules/@react-native-community/cli-platform-android/build/commands/runAndroid/index.js:125:12) at <anonymous> at process._tickCallback (internal/process/next_tick.js:188:7)
  8. godrugal

    Android Studio,Problemas com RecyclerView

    Criei uma tela de busca com Recycleview, e ao efetuar a busca ele traz o resultado armazenado no banco. Até ai tudo bem. Porém se existir no banco 2 nomes iguais como por exemplo: se existir vinte pessoas com o nome "Carlos", ele só me traz uma pessoa. Aqui abaixo segue a classe adapter e o recycle. Estou usando a tela de fragment. Outro detalhe, se eu repetir a mesma busca, ele inseri na lista abaixo o mesmo item da busca anterior, ou seja, fica 2 itens duplicados com os mesmos valores no recycleview. Eu não sei se o erro ta dentro do método onResponse ou se ta no PHP. Deve ser uma besteira. Quem puder ajudar, agradeço. Classe Adapter: public class CursosAdapterImgUrl extends RecyclerView.Adapter<CursosAdapterImgUrl.CursosHolder> { List<Curso>listaCursos; RequestQueue request; Context context; public CursosAdapterImgUrl(List<Curso> listaCursos, Context context) { this.listaCursos = listaCursos; this.context = context; request = Volley.newRequestQueue(context); } @NonNull @Override public CursosHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View vista = LayoutInflater.from(parent.getContext()).inflate(R.layout.lista_cursos_img, parent, false); RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ); vista.setLayoutParams(layoutParams); return new CursosHolder(vista); } @Override public void onBindViewHolder(@NonNull CursosHolder holder, int position) { // holder.txtCodigo.setText(listaCursos.get(position).getCodigo().toString()); holder.txtNome.setText(listaCursos.get(position).getNome().toString()); holder.txtProfessor.setText(listaCursos.get(position).getProfessor().toString()); holder.txtCategoria.setText(listaCursos.get(position).getCategoria().toString()); if(listaCursos.get(position).getUrlImagem()!=null){ carregarImagemWEBService(listaCursos.get(position).getUrlImagem(),holder); }else{ holder.idImagem.setImageResource(R.drawable.sem_foto); } } private void carregarImagemWEBService(String urlImagem, final CursosHolder holder) { String caminhoImage = "http://192.168.0.12/webservices/" +urlImagem; caminhoImage = caminhoImage.replace(" ", "%20"); ImageRequest imageReq = new ImageRequest(caminhoImage, new Response.Listener<Bitmap>() { @Override public void onResponse(Bitmap response) { holder.idImagem.setImageBitmap(response); } }, 0, 0, ImageView.ScaleType.CENTER, null, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(context, "Erro ao carregar a imagem",Toast.LENGTH_SHORT).show(); } }); request.add(imageReq); } @Override public int getItemCount() { return listaCursos.size(); } public class CursosHolder extends RecyclerView.ViewHolder { TextView txtNome,txtCodigo,txtProfessor, txtCategoria; ImageView idImagem; public CursosHolder(View itemView) { super(itemView); txtNome= (TextView) itemView.findViewById(R.id.nomeCurso); //txtCodigo= (TextView) itemView.findViewById(R.id.txtCodigo); txtProfessor= (TextView) itemView.findViewById(R.id.Professor); txtCategoria= (TextView) itemView.findViewById(R.id.Categoria); idImagem= itemView.findViewById(R.id.idImagem); } } } Classe do Recicleview: public class consultarListaNome extends Fragment implements Response.Listener<JSONObject>, Response.ErrorListener { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; EditText campoNome; Button botaoConsultar; RecyclerView recyclerCursos; ArrayList<Curso> listaCursos; ProgressDialog progresso; RequestQueue request; JsonObjectRequest jsonObjectReq; ImageView imgFoto; private OnFragmentInteractionListener mListener; public consultarListaNome() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment consultarListaNome. */ // TODO: Rename and change types and number of parameters public static consultarListaNome newInstance(String param1, String param2) { consultarListaNome fragment = new consultarListaNome(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View vista = inflater.inflate(R.layout.fragment_consultar_lista_nome, container, false); listaCursos=new ArrayList<>(); recyclerCursos= (RecyclerView) vista.findViewById(R.id.idRecyclerNome); // se der problema, mude aqui recyclerCursos.setLayoutManager(new LinearLayoutManager(this.getContext())); recyclerCursos.setHasFixedSize(true); campoNome = (EditText) vista.findViewById(R.id.campoNome); botaoConsultar = (Button) vista.findViewById(R.id.btnConsultar); request= Volley.newRequestQueue(getContext()); botaoConsultar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { carregarWEBService(); } }); return vista; } private void carregarWEBService() { progresso = new ProgressDialog(getContext()); progresso.setMessage("Buscando..."); progresso.show(); String url = "http://192.168.0.12/webservices/consultarCursoNome.php?nome="+ campoNome.getText().toString(); jsonObjectReq = new JsonObjectRequest(Request.Method.GET, url, null, this, this); request.add(jsonObjectReq); } @Override public void onErrorResponse(VolleyError error) { progresso.hide(); Toast.makeText(getContext(), "Não foi possível listar os cursos " +error.toString() , Toast.LENGTH_SHORT).show(); Log.i("ERROR", error.toString()); } @Override public void onResponse(JSONObject response) { progresso.hide(); Curso curso = null; JSONArray json = response.optJSONArray("curso"); // nome da tabela curso try { for(int i=0; i<json.length();i++){ curso = new Curso(); JSONObject jsonObject = null; jsonObject = json.getJSONObject(i); curso.setNome(jsonObject.optString("nome")); curso.setProfessor(jsonObject.optString("professor")); curso.setCategoria(jsonObject.optString("categoria")); curso.setUrlImagem(jsonObject.optString("url_imagem")); listaCursos.add(curso); } progresso.hide(); CursosAdapterImgUrl adapter = new CursosAdapterImgUrl(listaCursos,getContext()); recyclerCursos.setAdapter(adapter); }catch (JSONException e){ e.printStackTrace(); progresso.hide(); Toast.makeText(getContext(), "Não foi possível listar os cursos " +response , Toast.LENGTH_SHORT).show(); } } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } } Código do PHP: <?PHP include "conexao.php"; $json=array(); if(isset($_GET["nome"])){ $nome=$_GET["nome"]; $consulta="select * from curso where nome= '{$nome}'"; // busca pelo nome $resultado=mysqli_query($conexao,$consulta); if($registro=mysqli_fetch_array($resultado)){ $result["codigo"]=$registro['codigo']; $result["nome"]=$registro['nome']; $result["categoria"]=$registro['categoria']; $result["professor"]=$registro['professor']; $result["url_imagem"]=$registro['url_imagem']; $json['curso'][]=$result; }else{ $resultar["codigo"]=0; $resultar["nome"]='nao registrado'; $resultar["categoria"]='nao registrado'; $resultar["professor"]='nao registrado'; $result["url_imagem"]=$registro['url_imagem']; $json['curso'][]=$resultar; } mysqli_close($conexao); echo json_encode($json); } else{ $resultar["codigo"]=0; $resultar["nome"]='nao registrado'; $resultar["categoria"]='nao registrado'; $resultar["professor"]='nao registrado'; $result["url_imagem"]=$registro['url_imagem']; $json['curso'][]=$resultar; echo json_encode($json); } ?>
  9. paulocosta1980

    Bug em execução de cálculo em dispositivos móveis

    Bom dia pessoal. Eu estava desenvolvendo um pequeno script que compara dois números e seleciona o maior deles, sendo eles uma variável pré-definida e o outro é um valor informado pelo usuário. A variável pré definida é atualizada com o valor máximo. Em um outro ponto do script esta variável é multiplicada por uma constante para se chegar a um resultado. Vejam as etapas de forma resumida (desconsiderando validação do número informado pelo usuário, entre outros pontos, para deixar o código mais simples): valorPreDefinido=0; function valorUsuario(valor){ valorPreDefinido=Math.max(valorPreDefinido,valor); } Em outra etapa do código tem a seguinte instrução (considerando a constante como seja 1000, por exemplo): valorReal=valorPreDefinido*1000; O script roda perfeitamente no computador, mas a execução interrompe quando está sendo executado no Chrome para Android (não testei em outros dispositivos móveis). Curiosamente, a interrupção não ocorre quando, em vez de se utilizar uma variável, se utiliza um array. Alguém já ouviu falar deste bug?
  10. Motta

    Huawei lança seu próprio sistema operacional

    Ameaçada pela dependência do Android, Huawei lança seu próprio sistema operacional
  11. Olá, Estou querendo desenvolver um aplicativo multi-plataforma (Android e IOS). Projeto para longo prazo (mais de 12 meses), pois como é complexo, investirei em conhecimento antes. Já tenho conhecimento básico em lógica de programação, já pratiquei o básico em SQL, Delphi, Oracle (tenho noção de if, else, then, boolean, true, false, string, etc)...trabalho com TI a mais de 10 anos... então acredito no meu potencial...Porém terei que fazer cursos voltados para aplicação mobile, para conseguir implementar meu projeto sem precisar contratar terceiros. Vai ser um aplicativo bem complexo no meu ponto de vista. Em resumo o cliente tem que se cadastrar, vai visualizar produtos de empresas separados por categorias (mais de uma empresa) e poder fazer seus pedidos. As empresas que anunciam seus produtos, vão ter que ter gerenciamento dos pedidos realizados e dos produtos. E eu, terei que ter acesso as vendas dessas empresas, pois serei remunerado sobre esses pedidos feitos no app. Por ser 3 tipos de credenciais diferentes, com acessos à recursos diferentes, telas diferentes, pensei em separar em 3 aplicativos, pois poderia ser muito pesado tudo em um único. Um app então será para clientes fazerem o seu cadastro, efetuarem seus pedidos, obter históricos, etc. Outro será para gestão de pedidos e cadastros de produtos pelas empresas credenciadas. E o outro, seria gerencial para mim (dono do app), pois haverá comissão para mim pelos pedidos efetuados, terei que gerenciar isso. Recursos complexos que gostaria de implementar: App de compra dos clientes: - Cadastro com possibilidade de conectar com Facebook (Acredito que existe API para isso) - Confirmação de cadastro através de código gerado automaticamente (enviado por SMS ou email) - Utilização de mapa com posição atual (coordenadas) e se possível cálculo de distância. Ser possível mostrar empresas perto da pessoa por exemplo (Acredito que existe API para isso também) - Pagamento online (deve haver varias API (opções) nesse sentido) App para gestão (empresas vendedoras): Possibilidade de enviar fotos (cadastro de produtos) Possibilidade de salvar/enviar email com planilha ou relatório Agora meus questionamentos: 1) Com esses recursos mais complexos, qual linguagem melhor me atenderia(Xamarin, FireMonkey, Ionic, Unity, entre outros)? Se possível mencionar a questão de disponibilidade de materiais e cursos, pontos fortes e fracos referente a recursos e API’s (compatibilidade). 2) Será necessário um banco de dados externo para armazenar tudo isso (será na nuvem e deverá ser sincronizado). Qual banco poderia ser utilizado? Ouvi falar muito bem do Firebase. 3) Bem futuramente (caso aplicativo der certo), poderá ser necessário implantar o gerenciamento da empresa também em sistema Web. As decisões anteriores terá interferência? Digo, já devo observar a escolha da linguagem do app e o banco de dados, visando essa futura implantação? Se sim, qual recomendação? Como pode ver, preciso de um ponta pé inicial para começar os estudos (pois estudar meses ou anos uma linguagem para depois não conseguir aplicar tais recursos devido a não ter eles, seria perda de tempo e dinheiro). Para isso conto com a ajuda dos mais experientes, vocês. Obrigado desde já!
  12. brunoogm

    Realizar insert com espaço entre textos

    Pessoal estou desenvolvendo em Android Studio mas estou com o seguinte problema: Todos os inserts onde eu coloco alguma palavra composta ele da erro no app, porem todos os inserts com campos sem o espaço eles funcionam Ex: se eu for inserir "NOME SOBRENOME" ele me devolve erro (com espaço) mas se eu inserir "NOMESOBRENOME" ele funciona normalmente (sem espaço) Ja configurei o android pra ISO 8859-1 e também pra UTF-8 mas nenhum dos dois me resolveu os problemas. Alguém tem alguma sugestão do que pode ser ?
  13. Motta

    Google afasta Huawei do Android.

    Google afasta Huawei do Android. Chegou a hora do plano B?
  14. isaque_cb2

    Google maps api android

    Bom, eu estou trabalhando em um app que depende de um mapa, gps e coisas do tipo, não é nada grande, e é mais pra estudos mesmo, quero conhecer melhor essa api, mais eu não encontro nenhum tutorial do tipo, todos que encontro são antigos e têm algum erro, alguém pode me ajudar? com tutoriais, dicas, video-aulas (que ainda funcionem...) eu já reproduzi vários, mais sempre tem um erro... grato por qualquer ajuda!
  15. Tenho ao meu ponto de vista uma "boa" ideia de app para ganhar dinheiro e prêmios, mas não entendo nada sobre desenvolvimento do mesmo. Gostaria de conhecer pessoas que saibam desenvolver e trocar idéias, nada mais que isso. Quem sabe possa surgir um Aplicativo reconhecido mundialmente.
  16. Omar~

    Android 9 Estragou meu telefone

    Bom ainda não vi um tópico similar a esse aqui no iMasters, e também não condiz com seu conteúdo bruto. Mas vim aqui porque acredito que alguém possa me dar uma luz. Bem possuo um Sansung j4+, que ao realizar a gigantesca atualização para do sistema para versão 9 o telefone passou a apresentar inúmeras anomalias, como não atender ligação, não fechar aplicativos, falha em carregamentos, lentidão extrema, descarregamento da bateria em poucos minutos, além de super aquecimento entre outras sem mencionar que a interface ficou extremamente ridícula (horrível mesmo). Tentei localizar um lugar para reportar ou reclamar de tais problemas, mas não encontrei. Penso que se eu restaurar as configurações originais de fábrica ou formatar possa voltar o sistema a versão anterior (QUE FUNCIONAVA LINDAMENTE), porém me rebate nos termos de atualização que se não fazer como algumas pessoas me disseram o android pode deixar de funcionar. Quem está mais por dentro desse ramo poderiam me dar dicas de qual a melhor forma de proceder? Poque com essa versão 9 do android estou a ponto de atirar o telefone na parede de tão ruim que ele ficou.
  17. Omar~

    Android 9 Estragou meu telefone

    Bom ainda não vi um tópico similar a esse aqui no iMasters, e também não condiz com seu conteúdo bruto. Mas vim aqui porque acredito que alguém possa me dar uma luz. Bem possuo um Sansung j4+, que ao realizar a gigantesca atualização para do sistema para versão 9 o telefone passou a apresentar inúmeras anomalias, como não atender ligação, não fechar aplicativos, falha em carregamentos, lentidão extrema, descarregamento da bateria em poucos minutos, além de super aquecimento entre outras sem mencionar que a interface ficou extremamente ridícula (horrível mesmo). Tentei localizar um lugar para reportar ou reclamar de tais problemas, mas não encontrei. Penso que se eu restaurar as configurações originais de fábrica ou formatar possa voltar o sistema a versão anterior (QUE FUNCIONAVA LINDAMENTE), porém me rebate nos termos de atualização que se não fazer como algumas pessoas me disseram o android pode deixar de funcionar. Quem está mais por dentro desse ramo poderiam me dar dicas de qual a melhor forma de proceder? Poque com essa versão 9 do android estou a ponto de atirar o telefone na parede de tão ruim que ele ficou.
  18. juniormelo26

    Service Android

    Boa noite, pessoal estou desenvolvendo um App Android que pega ( Latitude, longitude e Imei ) a cada 5 minutos e envia ao banco. até ai tudo certo, o service executa bem certinho quando o app está com a tela habilitada ou no caso está sendo utilizado, queria que o App mesmo com a tela bloqueada realize o serviço. foi criado um service, broadcastReceive. Segue service package com.example.junior.buskrastreamentogps; import android.Manifest; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.support.annotation.RequiresApi; import android.support.v4.app.ActivityCompat; import android.support.v4.app.NotificationCompat; import android.telephony.TelephonyManager; import android.util.Log; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import java.util.HashMap; import java.util.Map; public class service extends Service { int mStartMode; // indicates how to behave if the service is killed IBinder mBinder; // interface for clients that bind boolean mAllowRebind; // indicates whether onRebind should be used private Handler mHandler = new Handler(); // Creating Volley RequestQueue. RequestQueue requestQueue; // Create string variable to hold the EditText Value. String ImeiHolder, LatitudeHolder,LongitudeHolder, tmpLat, tmpLon,tmpImei; // ENDEREÇO DO SERVIDOR E PAGINA RESPONSAVEL POR RECEBER DADOS DO APP E INSERIR NO BANCO String HttpUrl = "http://xxxxxxxx/inserir.php"; /** Called when the activity is first created. */ @TargetApi(Build.VERSION_CODES.O) @Override public void onCreate() { super.onCreate(); Context context = getApplicationContext(); //NOTIFICAÇÃO PARA O USUARIO String CHANNEL_ID = "my_channel_01"; // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = getString(R.string.app_name); // String description = getString(R.string.channel_description); int importance = NotificationManager.IMPORTANCE_HIGH; NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance); //channel.setDescription(description); // Register the channel with the system; you can't change the importance // or other notification behaviors after this NotificationManager notificationManager = getSystemService(NotificationManager.class); PendingIntent p = PendingIntent.getActivity(this, 1, new Intent(this, service.class), 0); notificationManager.createNotificationChannel(channel); }else { NotificationCompat.Builder builder = new NotificationCompat.Builder(service.this, CHANNEL_ID) .setSmallIcon(R.drawable.logo_busk) .setContentTitle("Notificação") .setContentText("Bem vindo") .setPriority(NotificationCompat.PRIORITY_HIGH); } Log.d("TAG", "Serviço Criado, Notificação enviada"); Toast.makeText(service.this, "Proteção Criada", Toast.LENGTH_SHORT).show(); // Creating Volley newRequestQueue . requestQueue = Volley.newRequestQueue(service.this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d("TAG", "Comando Service inciado no OnStartComannd."); Toast.makeText(service.this, "Proteção Incializada", Toast.LENGTH_SHORT).show(); Imei(); EnviarLocalizacao.run(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { String CHANNEL_ID = "my_channel_01"; Notification.Builder builder = new Notification.Builder(service.this,CHANNEL_ID) .setContentTitle(getString(R.string.app_name)) .setContentText("Notificação") .setAutoCancel(true); Notification notification = builder.build(); startForeground(1, notification); } else { NotificationCompat.Builder builder = new NotificationCompat.Builder(service.this) .setContentTitle(getString(R.string.app_name)) .setContentText("Notificação") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setAutoCancel(true); Notification notification = builder.build(); startForeground(1, notification); } return mStartMode; } private Runnable EnviarLocalizacao = new Runnable() { @RequiresApi(api = Build.VERSION_CODES.O) @Override public void run() { configurarServico(); //Toast.makeText(MainActivity.this, "This is a delayed toast", Toast.LENGTH_SHORT).show(); mHandler.postDelayed(this, 180000); } }; private void Imei() { final TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { return; } @SuppressLint("HardwareIds") final String imei = telephonyManager.getDeviceId(); tmpImei = imei.toString(); ImeiHolder = tmpImei.trim(); } public void configurarServico() { try { final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { double latPoint = location.getLatitude(); double lngPoint = location.getLongitude(); tmpLat = Double.toString(latPoint); tmpLon = Double.toString(lngPoint); LatitudeHolder = tmpLat.trim(); LongitudeHolder = tmpLon.trim(); insert_banco(); Imei(); Toast.makeText(service.this, "Proteção Sincronizada!", Toast.LENGTH_SHORT).show(); locationManager.removeUpdates(this); } public void onStatusChanged(String provider, int status, Bundle extras) { } public void onProviderEnabled(String provider) { } public void onProviderDisabled(String provider) { } }; locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0, locationListener); }catch(SecurityException ex){ //Toast.makeText(service.this, "Você precisa ativar a permissão do GPS", Toast.LENGTH_LONG).show(); } } public void insert_banco() { // Creating string request with post method. StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl, new Response.Listener<String>() { @Override public void onResponse(String ServerResponse) { // Showing response message coming from server. //Toast.makeText(service.this, ServerResponse, Toast.LENGTH_LONG).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { // Showing error message if something goes wrong. //Toast.makeText(service.this, volleyError.toString(), Toast.LENGTH_LONG).show(); } }) { @Override protected Map<String, String> getParams() { // Creating Map String Params. Map<String, String> params = new HashMap<String, String>(); // Adding All values to Params. params.put("imei", ImeiHolder); params.put("lat", LatitudeHolder); params.put("lng", LongitudeHolder); return params; } }; // Creating RequestQueue. RequestQueue requestQueue = Volley.newRequestQueue(service.this); // Adding the StringRequest object into requestQueue. requestQueue.add(stringRequest); } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); Log.d("TAG", "Serviço inciado no onStart."); configurarServico(); } //localização @Override public IBinder onBind(Intent arg0) { return mBinder; } }
  19. Olá estou tendo esse erro em meu código alguém poderia me ajudar a resolver isso? grato desde já. java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference at map.app.fragments.ReportFragment.putImgToBytearray(ReportFragment.kt:177) Linha do erro bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream) código private fun putImgToBytearray(): ByteArray { val stream = ByteArrayOutputStream() val drawable = this.imgThumb!!.drawable as BitmapDrawable val bitmap = drawable.bitmap bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream) return stream.toByteArray() } código onActivityResult override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == IMAGE_PICK_CODE && resultCode == RESULT_OK) { try { //Getting the Bitmap from Gallery val bitmap = MediaStore.Images.Media.getBitmap(context.contentResolver, this.imageUri) as Bitmap? this.imgThumb!!.setImageBitmap(bitmap) this.pictureTaken = true } catch (e:IOException) { e.printStackTrace() } } else { Toast.makeText(context, "Error loading image", Toast.LENGTH_LONG) } } método para abrir a galeria e pegar uma imagem,sim é uma adaptação fun openCamera() { try { val imageFile = createImageFile() val callCameraIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); if(callCameraIntent.resolveActivity(activity.packageManager) != null) { val authorities = activity.packageName + ".fileprovider" this.imageUri = FileProvider.getUriForFile(context, authorities, imageFile) callCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri) startActivityForResult(callCameraIntent, IMAGE_PICK_CODE) } } catch (e: IOException) { Toast.makeText(context, "Could not create file!", Toast.LENGTH_SHORT).show() } }
  20. Kellison Ruan

    MOSTRAR PAYPAL NO CHECKOUT DO APP IONIC

    Olá galera, Boa tarde! Estou com um probleminha em Ionic que está quebrando muito minha cabeça por dias. Método de pagamento do paypal aparece em meu site, mas não aparece no app ionic, o que será? Já tentei de tudo. Esse app faz comunicação via API do Woocommerce, e lá está habilitado a forma de pagamento com PayPal, porém só não aparece no app, já que na página de checkout no meu site, aparece. Segue o código da página de checkout do app: import { Component, Inject } from '@angular/core'; import { NavController, NavParams, AlertController, Loading, LoadingController, ToastController, App } from 'ionic-angular'; import { PlacedPage } from '../placed/placed'; import { PaymentGateway } from "../../models/payment-gateway.models"; import { Constants } from "../../models/constants.models"; import { WordpressClient } from '../../providers/wordpress-client.service'; import { Global } from '../../providers/global'; import { Subscription } from "rxjs/Subscription"; import { CartItem } from "../../models/cart-item.models"; import { OrderRequest } from "../../models/order-request.models"; import { Address } from "../../models/address.models"; import { ShippingLine } from "../../models/shipping-line.models"; import { UserResponse } from "../../models/user-response.models"; import { OrderResponse } from "../../models/order-response.models"; import { Currency } from "../../models/currency.models"; import { InAppBrowser, InAppBrowserOptions } from '@ionic-native/in-app-browser'; import { sha512 } from 'js-sha512'; import { APP_CONFIG, AppConfig } from '../../app/app.config'; import { OrderUpdateRequest } from '../../models/order-update-request.models'; import { Coupon } from '../../models/coupon.models'; import { HomePage } from '../home/home'; import { TranslateService } from '@ngx-translate/core'; import { Helper } from '../../models/helper.models'; import { ShippingMethod } from '../../models/shipping-method.models'; import { PayPal, PayPalPayment, PayPalConfiguration, PayPalPaymentDetails } from '@ionic-native/paypal'; @Component({ selector: 'page-payment', templateUrl: 'payment.html', providers: [WordpressClient] }) export class PaymentPage { private loading: Loading; private loadingShown: Boolean = false; private placedPagePushed: Boolean = false; private paymentDone: Boolean = false; private paymentFailAlerted: Boolean = false; private subscriptions: Array<Subscription> = []; private paymentGateways = new Array<PaymentGateway>(); private cartItems: Array<CartItem>; private selectedPaymentGateway; private selectedAddress: Address; private orderRequest: OrderRequest; private orderId = -1; private user: UserResponse; private totalItems = 0; private total = 0; private couponApplied = false; private pickupTime = 0; private deliveryTime = 0; private shippingChargeGlobal: number; constructor(@Inject(APP_CONFIG) private config: AppConfig, public translate: TranslateService, private iab: InAppBrowser, private toastCtrl: ToastController, public navCtrl: NavController, private navParams: NavParams, private service: WordpressClient, private loadingCtrl: LoadingController, private alertCtrl: AlertController, public appCtrl: App) { this.cartItems = this.navParams.get('cart'); this.totalItems = this.navParams.get('totalItems'); this.total = this.navParams.get('total'); this.shippingChargeGlobal = this.navParams.get('shippingChargeGlobal'); let paymentGateways = JSON.parse(window.localStorage.getItem(Constants.PAYMENT_GATEWAYS)); this.selectedAddress = JSON.parse(window.localStorage.getItem(Constants.SELECTED_ADDRESS)); if (paymentGateways != null) { for (let pg of paymentGateways) { if (pg.enabled && this.paymentImplemented(pg.id)) { this.paymentGateways.push(pg); } } } } ionViewWillLeave() { this.subscriptions.forEach((subscription: Subscription) => { subscription.unsubscribe(); }); this.dismissLoading(); } paymentImplemented(id) { return id === "pumcp" || id === "payuindia" || id === "cod"; } paymentMethod(paymentGateway) { this.selectedPaymentGateway = paymentGateway; } placedPage() { if (this.selectedPaymentGateway == null) { this.translate.get('field_error_payment_method').subscribe(value => { this.showToast(value); }); } else { this.orderRequest = new OrderRequest(); this.orderRequest.payment_method = this.selectedPaymentGateway.id ? this.selectedPaymentGateway.id : "cod"; this.orderRequest.payment_method_title = this.selectedPaymentGateway.title ? this.selectedPaymentGateway.title : "cod"; this.orderRequest.set_paid = false; this.orderRequest.billing = this.selectedAddress; this.orderRequest.shipping = this.selectedAddress; this.user = JSON.parse(window.localStorage.getItem(Constants.USER_KEY)); this.orderRequest.customer_id = String(this.user.id); let selectedShippingMethod: ShippingMethod = JSON.parse(window.localStorage.getItem(Constants.SELECTED_SHIPPING_METHOD)); if (selectedShippingMethod) { let shippingTotal = 0; for (let ci of this.cartItems) { if (!ci.product.shipping_cost_use_global && ci.product.shipping_cost != 1) shippingTotal = shippingTotal + ci.product.shipping_cost; } if (this.shippingChargeGlobal != -1) { shippingTotal = shippingTotal + this.shippingChargeGlobal; } this.orderRequest.shipping_lines = new Array<ShippingLine>(); this.orderRequest.shipping_lines.push(new ShippingLine(selectedShippingMethod.method_id, selectedShippingMethod.method_title, String(shippingTotal))); } this.orderRequest.line_items = this.cartItems; for (let item of this.orderRequest.line_items) { item.product = null; } this.translate.get('order_creating').subscribe(value => { this.presentLoading(value); }); let coupon: Coupon = JSON.parse(window.localStorage.getItem(Constants.SELECTED_COUPON)); let subscription: Subscription = this.service.createOrder(window.localStorage.getItem(Constants.ADMIN_API_KEY), this.orderRequest).subscribe(data => { this.orderId = data.id; if (coupon) { this.applyCoupon(coupon); } else { this.orderPlaced(); } }, err => { console.log(err); this.dismissLoading(); let orderId = Helper.extractOrderIdFromError(err); if (orderId != -1) { this.orderId = orderId; if (coupon) { this.applyCoupon(coupon); } else { this.orderPlaced(); } } else { this.translate.get('order_failed').subscribe(value => { this.showToast(value); }); this.appCtrl.getRootNav().setRoot(HomePage); } }); this.subscriptions.push(subscription); } } applyCoupon(coupon) { let couponSubs: Subscription = this.service.applyCouponCode(window.localStorage.getItem(Constants.ADMIN_API_KEY), String(this.orderId), coupon.code).subscribe(data => { this.couponApplied = true; window.localStorage.removeItem(Constants.SELECTED_COUPON); this.translate.get('confirm_order_coupon_applied').subscribe(value => { this.showToast(value); }); this.orderPlaced(); }, err => { console.log(err); this.dismissLoading(); }); this.subscriptions.push(couponSubs); } orderPlaced() { this.dismissLoading(); if (this.selectedPaymentGateway.id && this.selectedPaymentGateway.id === "cod") { this.clearCart(); this.navCtrl.setRoot(PlacedPage); } else if (this.selectedPaymentGateway.id === "pumcp" || this.selectedPaymentGateway.id === "payuindia") { this.initPayUMoney(); } else { this.translate.get('order_placed_cod').subscribe(value => { this.showToast(value); }); this.clearCart(); this.navCtrl.setRoot(PlacedPage); } } initPayUMoney() { let name = this.user.first_name && this.user.first_name.length ? this.user.first_name : this.user.username; let mobile = this.user.username; let email = this.user.email; let bookingId = String(Math.floor(Math.random() * (99 - 10 + 1) + 10)) + this.orderId; let productinfo = this.orderId; let salt = this.config.payuSalt; let key = this.config.payuKey; let amt = this.couponApplied ? this.total : this.totalItems; let string = key + '|' + bookingId + '|' + amt + '|' + productinfo + '|' + name + '|' + email + '|||||||||||' + salt; let encrypttext = sha512(string); //let url = "payumoney/payuBiz.html?amt=" + amt + "&name=" + name + "&mobileNo=" + mobile + "&email=" + email + "&bookingId=" + bookingId + "&productinfo=" + productinfo + "&salt=" + salt + "&key=" + key; let url = "payumoney/payuBiz.html?amt=" + amt + "&name=" + name + "&mobileNo=" + mobile + "&email=" + email + "&bookingId=" + bookingId + "&productinfo=" + productinfo + "&hash=" + encrypttext + "&salt=" + salt + "&key=" + key; let options: InAppBrowserOptions = { location: 'yes', clearcache: 'yes', zoom: 'yes', toolbar: 'no', closebuttoncaption: 'back' }; const browser: any = this.iab.create(url, '_blank', options); browser.on('loadstop').subscribe(event => { browser.executeScript({ file: "payumoney/payumoneyPaymentGateway.js" }); if (event.url == "http://localhost/success.php") { this.paymentSuccess(); browser.close(); } if (event.url == "http://localhost/failure.php") { this.paymentFailure(); browser.close(); } }); browser.on('exit').subscribe(event => { if (!this.paymentDone && !this.paymentFailAlerted) { this.paymentFailure(); } }); browser.on('loaderror').subscribe(event => { this.showToast('something_went_wrong'); }); } paymentFailure() { this.paymentFailAlerted = true; let subscription: Subscription = this.service.updateOrder(window.localStorage.getItem(Constants.ADMIN_API_KEY), String(this.orderId), new OrderUpdateRequest('cancelled')).subscribe(data => { }, err => { console.log(err); }); this.subscriptions.push(subscription); this.translate.get(['payment_fail_title', 'payment_fail_message', 'ok']).subscribe(res => { let alert = this.alertCtrl.create({ title: res.payment_fail_title, message: res.payment_fail_message, buttons: [{ text: res.ok, role: 'cancel', handler: () => { this.done(); console.log('Okay clicked'); } }] }); alert.present(); }); } paymentSuccess() { this.paymentDone = true; this.clearCart(); this.translate.get('just_a_moment').subscribe(value => { this.presentLoading(value); }); let subscription: Subscription = this.service.updateOrder(window.localStorage.getItem(Constants.ADMIN_API_KEY), String(this.orderId), { set_paid: true }).subscribe(data => { this.done(); }, err => { this.done(); this.paymentSuccess(); console.log(err); }); this.subscriptions.push(subscription); } done() { if (!this.placedPagePushed) { this.placedPagePushed = true; this.dismissLoading(); this.appCtrl.getRootNav().setRoot(this.paymentFailAlerted ? HomePage : PlacedPage); } } private presentLoading(message: string) { this.loading = this.loadingCtrl.create({ content: message }); this.loading.onDidDismiss(() => { }); this.loading.present(); this.loadingShown = true; } private dismissLoading() { if (this.loadingShown) { this.loadingShown = false; this.loading.dismiss(); } } private presentErrorAlert(msg: string) { let alert = this.alertCtrl.create({ title: 'Error', subTitle: msg, buttons: ['OK'] }); alert.present(); } showToast(message: string) { let toast = this.toastCtrl.create({ message: message, duration: 3000, position: 'bottom' }); toast.onDidDismiss(() => { console.log('Dismissed toast'); }); toast.present(); } clearCart() { let cartItems = new Array<CartItem>(); window.localStorage.setItem('cartItems', JSON.stringify(cartItems)); } }
  21. isaque_cb2

    erro com NavGraph android studio

    Olá galera, estou com um problema e não consigo resolver de forma alguma, ja tentei reiniciar o android studio (ou o pc), já tentei remover o NavHostFragment e adicionar novamente e NADA! mas o problema é o seguinte: eu estava trabalhando em um projeto e vi uma boa oportunidade de usar esse navgraph, deu tudo certo, mas quando adicionei o navhostfragment ao activity inicial começou esse erro, alguém sabe como resolvo isso? grato! lembrando que mesmo com esse erro, o nav_graph é carregado corretamente!
  22. João Batista Neto

    Android DevConference

    until
    O iMasters Android DevConference 2017 reúne cerca de 1.200 programadores brasileiros e estrangeiros em São Paulo, para palestras nacionais e internacionais, workshops, áreas de comunidade e diversas ações de networking, divididos em dois dias de muito conteúdo. Acompanhe as novas informações no portal e nas nossas redes sociais: Facebook, Twitter e Instagram. Site do evento: http://androidconference2017.imasters.com.br/
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.