Ir para conteúdo
Batysta Azevedo

Pull to Refresh Conflito

Recommended Posts


Gente estou tentando colocar um webview com Pull to Refresh e um codigo que faz o file de enviar arquivos abrir dentro do webview.
Até ai consegui fazer os dois só que quando eu uso os dois codigos juntos um deles para de funcionar.
Não sei oq fazer, me ajudem por favor.


activity_main.xml codigos:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.smart.projeto.MainActivity">

<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/wvSite"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp" />

</android.support.v4.widget.SwipeRefreshLayout>
</android.support.constraint.ConstraintLayout>


MainActivity.java codigo:

package com.example.smart.projeto;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

WebView web;

SwipeRefreshLayout swipe;

private ValueCallback<Uri> mUploadMessage;
public ValueCallback<Uri[]> uploadMessage;
private final static int FILECHOOSER_RESULTCODE=1;
public static final int REQUEST_SELECT_FILE = 100;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);



swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {

LoadWeb();
}
});

LoadWeb();







}

public void LoadWeb(){

web = (WebView) findViewById(R.id.wvSite);

web = new WebView(this);
web.getSettings().setJavaScriptEnabled(true);
web.getSettings().setAllowFileAccess(true);
web.getSettings().setAllowFileAccess(true);
web.getSettings().setAllowContentAccess(true);
web.loadUrl("http://clubgames.biz/teste/");
swipe.setRefreshing(true);
web.setWebViewClient(new WebViewClient(){


public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

web.loadUrl("file:///android_asset/error.html");
}

public void onPageFinished(WebView view, String url){

//Hide the SwipeReefreshLayout

swipe.setRefreshing(false);
}



});

web.setWebChromeClient(new WebChromeClient()
{
protected void openFileChooser(ValueCallback uploadMsg, String acceptType)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
}


// For Lollipop 5.0+ Devices
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
{
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}

uploadMessage = filePathCallback;

Intent intent = fileChooserParams.createIntent();
try
{
startActivityForResult(intent, REQUEST_SELECT_FILE);
} catch (ActivityNotFoundException e)
{
uploadMessage = null;
Toast.makeText(MainActivity.this, "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
return false;
}
return true;
}

//For Android 4.1 only
protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{
mUploadMessage = uploadMsg;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
}

protected void openFileChooser(ValueCallback<Uri> uploadMsg)
{
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}


});

setContentView(web);

}




@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
if (requestCode == REQUEST_SELECT_FILE)
{
if (uploadMessage == null)
return;
uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
uploadMessage = null;
}
}
else if (requestCode == FILECHOOSER_RESULTCODE)
{
if (null == mUploadMessage)
return;
// Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
// Use RESULT_OK only if you're implementing WebView inside an Activity
Uri result = intent == null || resultCode != MainActivity.RESULT_OK ? null : intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
else
Toast.makeText(MainActivity.this, "Failed to Upload Image", Toast.LENGTH_LONG).show();
}






@Override
public void onBackPressed(){

if (web.canGoBack()){
web.goBack();
}else {
finish();
}
}


}


AndroidManifest.xml codigo:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.smart.projeto">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisar ser um membro para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar Agora

  • Conteúdo Similar

    • Por lucas.sardelari
      Olá
      Estou tendo um problema ao compilar uma biblioteca no Android Studio pelo NDK Quando executo o comando ndk-build, um problema é lançado:
       
      Android NDK: Found platform level in ./project.properties. Setting APP_PLATFORM to android-19. Android NDK: WARNING: APP_PLATFORM android-19 is higher than android:minSdkVersion 1 in ./AndroidManifest.xml. NDK binaries will *not* be compatible with devices older than android-19. See https://android.googlesource.com/platform/ndk/+/master/docs/user/common_p roblems.md for more information. [arm64-v8a] Compile : FerrugemLib <= FerrugemLib.c In file included from jni/FerrugemLib.c:15: In file included from jni\CL/cl.h:32: jni\CL/cl_version.h:34:9: warning: cl_version.h: CL_TARGET_OPENCL_VERSION is not defined. Defaulting to 220 (OpenCL 2.2) [-W#pragma-messages] #pragma message("cl_version.h: CL_TARGET_OPENCL_VERSION is not defined. Defaulting to 220 (OpenCL 2.2)") ^ jni/FerrugemLib.c:346:1: warning: control reaches end of non-void function [-Wreturn-type] } ^ jni/FerrugemLib.c:535:1: warning: control reaches end of non-void function [-Wreturn-type] } ^ jni/FerrugemLib.c:733:25: warning: 'clCreateCommandQueue' is deprecated [-Wdeprecated-declarations] openCLObjects->queue = clCreateCommandQueue(openCLObjects->context, openCLObjects->device, 0, &err); ^ jni\CL/cl.h:1760:72: note: 'clCreateCommandQueue' has been explicitly marked deprecated here cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED; ^ jni\CL/cl_platform.h:91:70: note: expanded from macro 'CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED' #define CL_EXT_SUFFIX__VERSION_1_2_DEPRECATED __attribute__((deprecated)) ^ jni/FerrugemLib.c:839:1: warning: control reaches end of non-void function [-Wreturn-type] } ^ jni/FerrugemLib.c:944:1: warning: control reaches end of non-void function [-Wreturn-type] } ^ jni/FerrugemLib.c:1977:1: warning: control reaches end of non-void function [-Wreturn-type] } ^ jni/FerrugemLib.c:2034:1: warning: control reaches end of non-void function [-Wreturn-type] } ^ 8 warnings generated. [arm64-v8a] SharedLibrary : libFerrugemLib.so C:/Android/Sdk/ndk-bundle/build//../toolchains/aarch64-linux-android-4.9/prebuilt/windows-x86_64/lib/gcc/aarch64-linux-android/4.9.x/../../../../aarch64-linux-android/bin\ld: cannot find OpenCL: No such file or directory clang++.exe: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [obj/local/arm64-v8a/libFerrugemLib.so] Error 1 Meu Android.mk
      LOCAL_PATH := $(call my-dir)
      LOCAL_C_INCLUDES += PATH_TO_CL_FOLDER
       
      include $(CLEAR_VARS) LOCAL_MODULE := decodeYUV420SP LOCAL_SRC_FILES := decodeYUV420SP.c LOCAL_LDLIBS := -llog -ljnigraphics include $(BUILD_SHARED_LIBRARY) include $(CLEAR_VARS) LOCAL_MODULE := FerrugemLib LOCAL_SRC_FILES := FerrugemLib.c LOCAL_LDLIBS := -lOpenCL LOCAL_LDLIBS += -llog -ljnigraphics LOCAL_ALLOW_UNDEFINED_SYMBOLS := true include $(BUILD_SHARED_LIBRARY) APP_OPTIM := debug LOCAL_CFLAGS := $(call my-dir) Alguem poderia ajudar em como eu conseguir fazer dar o build com este comando: -lOpenCL
      Me propuseram a trocar o -lOpenCL por -framework OpenCL porem sem sucesso.
      Obrigado.
    • Por Carcleo
      Tenho um objeto 
       
      MediaPlayer mPlayer = new MediaPlayer();
       
      Objetivo: Tocar o Streaming de uma Web Rádio e funciona corretamente.
       
      Porém, quando clico em Play, leva um tempo até que a Rádio Web comece a tocar.
       
      Existe alguma forma de enquanto o streaming estiver carregando, eu pegar o percentual para passar para uma  SeekBar por exemplo?, 
       
      Como?
       
      Segue o que eu já fiz:
       
      package carcleo.com.player; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.ProgressDialog; import android.app.TaskStackBuilder; import android.content.Context; import android.content.Intent; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnBufferingUpdateListener; import android.os.AsyncTask; import android.os.Build; import android.support.annotation.RequiresApi; import android.support.v4.app.NotificationCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.SeekBar; import android.widget.TextView; import java.io.IOException; public class player extends AppCompatActivity implements OnBufferingUpdateListener{ private MediaPlayer mPlayer; private String URL; private Button btnPlayPause; private Boolean conexao = false; private SeekBar sb; private TextView textView; private TextView textView2; private TextView textView3; private NotificationManager mNotificationManager; private AudioManager audioManager; private ProgressDialog progressDialog; @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.player); sb = findViewById(R.id.seekBar); textView = findViewById(R.id.textView); textView2 = findViewById(R.id.textView2); textView3 = findViewById(R.id.textView3); progressDialog = new ProgressDialog(this); btnPlayPause = (Button) findViewById(R.id.btnPlayPause); btnPlayPause.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { try { tocaPausa(); } catch (IOException e) { e.printStackTrace(); } } }); configuraAudioManager(); } private void tocaPausa() throws IOException { if (conexao == true) { if (!mPlayer.isPlaying()) { mPlayer.start(); btnPlayPause.setBackgroundResource(R.drawable.pause); } else { mPlayer.pause(); btnPlayPause.setBackgroundResource(R.drawable.play); } } else { String url = "rtsp://cdn-the-2.musicradio.com:80/LiveAudio/Capital"; // your URL here new Play().execute(url); } } private void configuraAudioManager() { audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); int volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); sb.setMax(maxVolume); sb.setProgress(volume); sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, AudioManager.FLAG_SHOW_UI); Double total = progress * 6.666666666666667; String valor =Integer.toString(Integer.valueOf(total.intValue())); textView.setText(valor+" %"); } @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) {} }); } @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) private void notificacao (){ NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.home) .setContentTitle("Rádio Capital") .setContentText("Agora deu"); Intent resultIntent = new Intent(this, player.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(player.class); stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(1, mBuilder.build()); } private void contaBuffer () { textView2.setText(Integer.toString(mPlayer.getDuration())); mPlayer.setOnBufferingUpdateListener( new MediaPlayer.OnBufferingUpdateListener() { public void onBufferingUpdate(MediaPlayer mp, int percent) { double ratio = percent / 100.0; int bufferingLevel = (int)(mp.getDuration() * ratio); sb.setSecondaryProgress(bufferingLevel); textView2.setText(Integer.toString(bufferingLevel)); } } ); } public void mostraBuffer() { mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { mediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() { @Override public boolean onInfo(MediaPlayer mp, int what, int extra) { if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END){ progressDialog.dismiss(); return true; } else if(what == MediaPlayer.MEDIA_INFO_BUFFERING_START){ progressDialog.show(); } return false; } }); } }); } @Override public void onBufferingUpdate(MediaPlayer mp, int percent) { textView3.setText(Integer.toString(percent)); } class Play extends AsyncTask<String, Void ,Boolean > { @Override protected void onPreExecute() { btnPlayPause.setBackgroundResource(R.drawable.carregando); btnPlayPause.setEnabled(false); } @Override protected Boolean doInBackground(String... params) { try { mPlayer = new MediaPlayer(); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mPlayer.setDataSource(params[0]); mostraBuffer(); mPlayer.prepare(); // might take long! (for buffering, etc) return true; } catch (IOException e) { e.printStackTrace(); } return false; } @Override protected void onPostExecute(Boolean result) { if (result == true){ btnPlayPause.setEnabled(true); mPlayer.start(); conexao = true; btnPlayPause.setBackgroundResource(R.drawable.pause); contaBuffer(); } else { conexao = false; } } } }
    • Por Lenon John
      Eu preciso inserir mais de 3000 itens no ArrayList, o que gera o erro: method code too large.
      Acredito que usando um TXT como "BANCO DE DADOS" vai resolver o meu problema.
       
      Atualmente eu faço assim:
      -----------------------------------------------------
      ArrayList lista = new ArrayList();

      // inserindo os itens no ArrayList
      lista.add(new produtoItem(R.drawable.imagem, "AA", "AA", "AA", "AA"));

      adapter = new produtoAdapter(this, lista);
      ListView listView = (ListView) findViewById(R.id.listView1);
      listView.setAdapter(adapter);
      -----------------------------------------------------
       
      Como pegar os dados de um TXT e inserir no meu arrayList?

      OBS: Esse APP precisa funcionar sem a necessidade de internet. Ou seja, não posso usar um banco dados externo.
    • Por paodimelaun
      Estou desenvolvendo um jogo RPG para mobile e preciso de membros para formar a equipe, estou precisando pessoas que possam: fazer pixel art, logos, desenhos, ícones, efeitos sonoros, músicas. Programadores experientes também são bem vindos. 
      interessados favor deixar seu skype nos comentários.
       
      Segue o GDD(ainda imcompleto)
      https://drive.google.com/open?id=1gNtg7URzmi1n9UYMmjiyKe_WXDmjHVkZkQFLCeWq_Wo
    • Por Emerson.Oliveira
      estou fazendo um simples APP web view, quero que quando o usuário acessar o APP apareça uma logo e em baixo icone de carregando, nessa logo nesse gif carregando vai ter uma verificação se a pessoa está conectado a uma internet ou não, se tiver conectado manda para web view, se não tiver conectado aparece uma mensagem vermelho que o celular está sem conexão no momento, como fazer isso se alguém tiver alguma ideia não manjo muito em fazer APP
×

Informação importante

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