How to write data from edit text into excel file in android?
I want to bypass data from editText into excel file without opening it from storage. Can i know how to do it?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Activity activity = this;
scanBtn = (Button) findViewById(R.id.BtnScn);
resultSC = (TextView) findViewById(R.id.SC_text);
ExelWrite = (Button) findViewById(R.id.ExelWrite);
SetTemp = (EditText) findViewById(R.id.SetTemp);
scanBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view){
startActivity(new Intent(getApplicationContext(),ScanCodeActivity.class));
}
});
ExelWrite.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.ExelWrite:
saveExcelFile(this,"Staff_Temperature.xls");
break;
}
}
private static boolean saveExcelFile(MainActivity context, String fileName) {
// check if available and not read only
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
Log.e(TAG, "Storage not available or read only");
return false;
}
boolean success = false;
This is where I create The workbook for the excel
//New Workbook
Workbook wb = new HSSFWorkbook();
Cell c = null;
//Cell style for header row'
CellStyle cs = wb.createCellStyle();
cs.setFillForegroundColor(HSSFColor.LIME.index);
cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//New Sheet
Sheet sheet1 = null;
sheet1 = wb.createSheet("RiSE");
// Generate column headings
Row row = sheet1.createRow(0);
c = row.createCell(0);
c.setCellValue("Staff Credential");
c.setCellStyle(cs);
c = row.createCell(1);
c.setCellValue("Staff Temperature");
c.setCellStyle(cs);
sheet1.setColumnWidth(0, (15 * 500));
sheet1.setColumnWidth(1, (15 * 500));
This is where I create Path for the file. I think It should be here, but I dont know how to call it
// Create a path where we will place our List of objects on external storage
File file = new File(context.getExternalFilesDir(null), fileName);
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}
return success;
}
public static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
public static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
Related
I am trying to run a task at background using AsyncTask, but it isn't working
I have tried a lot of solutions but none worked. My code should show me html codes of prothomalo.com at the logcat, but is is not doing that, instead it is showing a lot of errors.
public class BG extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d("myBG", "onPreExecute: ran");
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("myBG", "onPostExecute: ran");
Log.d("myBG", s);
}
#Override
protected String doInBackground(String... urls) {
Log.d("myBG", "doInBackground: ran");
String result = "";
URL url;
HttpURLConnection conn;
try {
url = new URL(urls[0]);
conn = (HttpURLConnection) url.openConnection();
InputStream in = conn.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
} catch (Exception e) {
e.printStackTrace();
return "Something went wrong";
}
return result;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
text = findViewById(R.id.text8);
BG myTask = new BG();
myTask.execute("https://www.prothomalo.com");
}
}The logcat should show if my background activity has run or not, but it showing a lot of errors
its a class assignment and I need to finish it today.
So basically the captured image is saved but it won't show up in the imgVpic imageview camera open up and the image captured is saved correctly with the correct file name but it just won't show up in the thumbnail that I set up, I checked in the gallery and the picture is there but again .. the image won't show in this imgVpic image view (i kept repeating this cause I can't post this question without "more details" since my post is mostly code, pls help I'm a student and I hate my teacher)
here is the code that I used
public class CaptureImgActivity extends AppCompatActivity {
final int CAMERA_RESULT=0;
Uri imgUri=null;
Button btTakePic;
ImageView imgVPic;
private void CaptureImageUri(){
String dir= Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM).getAbsolutePath();
File folder=new File(dir + File.separator+"test");
boolean success=true;
if (!folder.exists()){
try {
success=folder.mkdir();
Toast.makeText(this,"Folder Create Successfull", Toast.LENGTH_SHORT).show();
}catch (Exception e){
success = !success;
e.printStackTrace();
}
}
if (success){
dir=dir+ File.separator+"test";
}
Calendar calendar=Calendar.getInstance();
File file= new File(dir,"test"+(calendar.getTimeInMillis()+".jpg"));
if (!file.exists()){
try {
file.createNewFile();
imgUri= FileProvider.getUriForFile(CaptureImgActivity.this,BuildConfig.APPLICATION_ID,file);
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imgUri);
startActivityForResult(intent,CAMERA_RESULT);
}catch (Exception e){
e.printStackTrace();
}
}else {
try {
file.delete();
file.createNewFile();
imgUri= FileProvider.getUriForFile(CaptureImgActivity.this,BuildConfig.APPLICATION_ID,file);
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imgUri);
startActivityForResult(intent,CAMERA_RESULT);
}catch (Exception e){
e.printStackTrace();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == CAMERA_RESULT && requestCode == RESULT_OK){
try {
Uri imgUri=data.getData();
Bitmap bitmap= MediaStore.Images.Media.getBitmap(this.getContentResolver(),imgUri);
imgVPic.setImageBitmap(bitmap);
}catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capture_img);
btTakePic = (Button) findViewById(R.id.btTakePic);
imgVPic = (ImageView) findViewById(R.id.imgVPic);
btTakePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CaptureImageUri();
}
});
}
}
I tried in both method like choose image from gallery and Capture Image by adding
android:requestLegacyExternalStorage="true"
My Code is Different from yours but work as the same process but this works for me
Uri imgUri=null;
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_PICTURE = 1;
private Intent pictureActionIntent = null;
Bitmap bitmap;
String selectedImagePath;
private void SelectImage() {
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(
getActivity());
myAlertDialog.setTitle("Upload Pictures Option");
myAlertDialog.setMessage("How do you want to set your picture?");
myAlertDialog.setPositiveButton("Gallery",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent pictureActionIntent = null;
pictureActionIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(
pictureActionIntent,
GALLERY_PICTURE);
}
});
myAlertDialog.setNegativeButton("Camera",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
imgUri= FileProvider.getUriForFile(Objects.requireNonNull(getContext()), BuildConfig.APPLICATION_ID + ".provider", file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
startActivityForResult(intent, CAMERA_REQUEST);
}
});
myAlertDialog.show();
}
OnActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
bitmap = null;
selectedImagePath = null;
if (resultCode == RESULT_OK && requestCode == CAMERA_REQUEST) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
if (!f.exists()) {
Toast.makeText(getContext(), "Error while capturing image", Toast.LENGTH_LONG).show();
return;
}
try {
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
bitmap = Bitmap.createScaledBitmap(bitmap, 400, 400, true);
int rotate = 0;
try {
ExifInterface exif = new ExifInterface(f.getAbsolutePath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
bitmap.getHeight(), matrix, true);
mImageView.setImageBitmap(bitmap);
//storeImageTosdCard(bitmap);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (resultCode == RESULT_OK && requestCode == GALLERY_PICTURE) {
if (data != null) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getActivity().getContentResolver().query(selectedImage, filePath,
null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
selectedImagePath = c.getString(columnIndex);
c.close();
bitmap = BitmapFactory.decodeFile(selectedImagePath); // load
mImageView.setImageBitmap(bitmap);
} else {
Toast.makeText(getContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
}
}
And both method works for me and displayed thumbnail
I have my download manager, and it work perfect if I try to download a file. But I have a problem.
I have 4 CardView in my activity and I set it onClickListener, so when I click one CardView it will download the file.
Here is the code to call the download function
cardviewR1 = findViewById(R.id.card_viewR1);
cardviewR1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pDialogDL = new ProgressDialog(this);
pDialogDL.setMessage("A message");
pDialogDL.setIndeterminate(true);
pDialogDL.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialogDL.setCancelable(true);
final DownloadTask downloadTask = new DownloadTask(this);
downloadTask.execute(R1Holder);
pDialogDL.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
}
});
and here is the download function
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+getString(R.string.r1)+"_"+NameHolder+".zip");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
pDialogDL.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
pDialogDL.setIndeterminate(false);
pDialogDL.setMax(100);
pDialogDL.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
pDialogDL.dismiss();
if (result != null)
Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
}
}
The code work in my app, but the problem is, when I try to add second CardView which is like this
cardviewR2 = findViewById(R.id.card_viewR2);
cardviewR2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pDialogDL = new ProgressDialog(this);
pDialogDL.setMessage("A message");
pDialogDL.setIndeterminate(true);
pDialogDL.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialogDL.setCancelable(true);
final DownloadTask downloadTask = new DownloadTask(this);
downloadTask.execute(R2Holder);
pDialogDL.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
}
});
Yes it will download the second file, but it will overwrite the first file. I think the problem is right here
output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+getString(R.string.r1)+"_"+NameHolder+".zip");
Anyone can help me with this code?
I need your help, Thanks
Fixed it by create a new Download Class separately in different file with activity, so the AsyncTask will be call again and again
thanks
I created a listview which contain a url such as abc:554/user=admin&password=&channel=1
When I click the listview,the url would be passed onto the next class and use it for setDataSource.But the problem I am having is that setDataSource does not detect the url.I have tried to hardcode the url and use Toast to display the url when it is trying to connect and it works.But when passing the string,nothing happens.Here are my code
1st class trying to pass the string
OnItemClickListener getURLOnItemClickListener
= new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
String clickedFile = (String) parent.getItemAtPosition(position);
getURL(clickedFile);
}
};
void getURL(final String file){
if (clickAble == true){
FileInputStream fis;
String content = "";
try {
fis = openFileInput(file);
byte[] input = new byte[fis.available()];
while (fis.read(input) != -1) {}
content += new String(input);
//Toast.makeText(getBaseContext(),content,Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Intent i = new Intent(addressActivity.this, liveActivity.class);
String strName = content.toString();
i.putExtra("urlAddress", strName);
startActivity(i);
}
}
2nd class where the passed string is set
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live);
final String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString = null;
} else {
newString = extras.getString("urlAddress");
}
} else {
newString = (String) savedInstanceState.getSerializable("urlAddress");
}
urlLink = "rtsp://" + newString + "&stream=1.sdp?";
videoPlay();
}
void videoPlay(){
mPlayer1 = new MediaPlayer();
mCallback1 = new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
mPlayer1.setDataSource(urlLink);
mPlayer1.setDisplay(surfaceHolder);
mPlayer1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mPlayer1.start();
Toast.makeText(getBaseContext(),"Connecting...",Toast.LENGTH_LONG).show();
}
});
mPlayer1.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mPlayer1.release();
}
};
final SurfaceView surfaceView1 =
(SurfaceView) findViewById(R.id.surfaceView1);
// Configure the Surface View.
surfaceView1.setKeepScreenOn(true);
// Configure the Surface Holder and register the callback.
SurfaceHolder holder1 = surfaceView1.getHolder();
holder1.addCallback(mCallback1);
holder1.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
I manage to find the answer and it was ridiculously plain and simple.On the second class around these lines of codes on the top
final String newString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString = null;
} else {
newString = extras.getString("urlAddress");
}
} else {
newString = (String) savedInstanceState.getSerializable("urlAddress");
}
urlLink = "rtsp://" + newString + "&stream=1.sdp?";
videoPlay();
}
All I did was change
urlLink = "rtsp://" + newString + "&stream=1.sdp?";
into
urlLink = "rtsp://" + newString.toString().trim() + "&stream=1.sdp?";
Just adding toString() did not work,so I tried adding trim() and it works.If someone can explain it to me why this work it would be much appreciated
I'm beginning to develop in android using the material from http://developer.android.com.
I took one of their examples and modified it, so that my application can connect to a webpage. It works well when it is opened but if I click on an actionBar item which should open another page the new page isn't opened in the WebView, but it's launched the default browser.
I tried in many way to understand how to avoid that, but my little experience didn't allow me to fixe the problem.
Can you help me?
Many thanks.
Nino
public class MainActivity extends Activity {
public static final String WIFI = "Wi-Fi";
public static final String ANY = "Any";
public static String PAGINA ="http://www.kibao.org/simu/wap.php?lng=";
public static String BASE ="http://www.kibao.org";
public static String ATTUALE ="";
public static String lng = "";
final Context context = this;
private static boolean wifiConnected = false;
private static boolean mobileConnected = false;
public static boolean refreshDisplay = true;
public static String sPref = null;
public static String pagina = "";
private NetworkReceiver receiver = new NetworkReceiver();
#Override
public void onCreate(Bundle savedInstanceState) {
lng = getResources().getString(R.string.lng);
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new NetworkReceiver();
this.registerReceiver(receiver, filter);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public void onStart() {
super.onStart();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
sPref = sharedPrefs.getString("listPref", "Wi-Fi");
updateConnectedFlags();
if (refreshDisplay) {
ATTUALE=PAGINA.concat(lng);
loadPage(ATTUALE);
}
}
#Override
public void onDestroy() {
super.onStop();
String ciao = getResources().getString(R.string.ciao);
show_toast(ciao);
if (receiver != null) {
this.unregisterReceiver(receiver);
}
}
private void updateConnectedFlags() {
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
if (activeInfo != null && activeInfo.isConnected()) {
wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
} else {
wifiConnected = false;
mobileConnected = false;
}
}
private void loadPage(String pgUrl) {
if (((sPref.equals(ANY)) && (wifiConnected || mobileConnected))
|| ((sPref.equals(WIFI)) && (wifiConnected))) {
new DownloadWebpageTask().execute(pgUrl);
} else {
showErrorPage();
}
}
// Displays an error if the app is unable to load content.
private void showErrorPage() {
....
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.items, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu1:
if (refreshDisplay) {
ATTUALE=BASE.concat("/partite.php?lng=");
ATTUALE=ATTUALE.concat(lng);
loadPage(ATTUALE);
}
return true;
....
default:
return super.onOptionsItemSelected(item);
}
}
private InputStream downloadUrl(String urlString) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
InputStream stream = conn.getInputStream();
return stream;
}
public class NetworkReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connMgr =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (WIFI.equals(sPref) && networkInfo != null
&& networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
refreshDisplay = true;
Toast.makeText(context, R.string.wifi_connected, Toast.LENGTH_SHORT).show();
} else if (ANY.equals(sPref) && networkInfo != null) {
refreshDisplay = true;
} else {
refreshDisplay = false;
Toast.makeText(context, R.string.lost_connection, Toast.LENGTH_SHORT).show();
}
}
}
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
return loadWebpageFromNetwork(urls[0]);
} catch (IOException e) {
return getResources().getString(R.string.connection_error);
}
}
#Override
protected void onPostExecute(String result) {
setContentView(R.layout.main);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl(ATTUALE);
}
}
private String loadWebpageFromNetwork(String urlString) throws IOException {
InputStream stream = null;
try {
stream = downloadUrl(urlString);
pagina = getStringFromInputStream(stream);
} finally {
if (stream != null) {
stream.close();
}
}
return pagina;
}
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
........
}
This DownloadWebpageTask tries to "download" a webpage into a string, using a webview. This is not the correct way to do it. You are using the wrong tutorial. Don't use AsyncTasks for this. Start all over, using this:
http://developer.android.com/reference/android/webkit/WebView.html
or
http://www.mkyong.com/android/android-webview-example/
Simply call webview.loadUrl(url) again with a different url if you want to load a different page. It's as simple as that.
I've found another solution that works. I added the line
myWebView.setWebViewClient(new WebViewClient());
in the onPostExecute:
protected void onPostExecute(String result) {
setContentView(R.layout.main);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl(ATTUALE);
}
Thanks, Frank.
PS I've tried to add a comment to the last Frank's post, but I didn't succeed!