Well this code works fine in java but when i started to run it on Android 4.0 emulator it crashes. While Debugging i noticed that it crushed on httpConn.connect(); line
public class GetStringFromUrl {
public static String getString(String urlPageAdress) throws Exception
{
URL url = new URL(urlPageAdress);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestProperty("Accept-Encoding", "UTF-8");
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.connect(); //crashes on this line dunno know why
InputStream in = null;
if (httpConn.getContentEncoding() != null && httpConn.getContentEncoding().toString().contains("gzip")) {
in = new GZIPInputStream(httpConn.getInputStream());
} else {
in = httpConn.getInputStream();
}
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayBuffer baf = new ByteArrayBuffer(1000);
int read = 0;
int bufSize = 1024;
byte[] buffer = new byte[bufSize];
while (true) {
read = bis.read(buffer);
if (read == -1) {
break;
}
baf.append(buffer, 0, read);
}
String body = new String(baf.toByteArray());
return body;
} }
method is used in Main Activity
public class MainActivity extends Activity{
ToggleButton toogleButton;
public final static String EXTRA_MESSAGE = "ru.kazartsevaa.table.MESSAGE";
int upDown;
int SpinnerCount;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
upDown=0;
setContentView(R.layout.activity_main);
}
public void onClick(View v) throws Exception
{ System.out.print(SpinnerCount);
// if(upDown==0) //0 - вылет 1 прилет
//{
switch (v.getId())
{
case R.id.UpDownButton:
{
//toogleButton = (ToggleButton) findViewById(R.id.UpDownButton);
// toogleButton.setOnCheckedChangeListener(this);
}
case R.id.SheremetievoButton:
{
Spinner SherSpinner = (Spinner) findViewById(R.id.SheremetievoSpinner);
String SpinnerCount= SherSpinner.getItemAtPosition(SherSpinner.getSelectedItemPosition()).toString();
System.out.print(SpinnerCount);
new Thread(){ public void run() {
try {
String body = GetStringFromUrl.getString("www.xyz.com");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }.start();
int crowd;
}
}
Note: After changing to new thread it stopped crushing but still writes
Are you doing this in the main thread? Should work if you execute this in a separate thread.
public void onClick(View v) {
try{
new Thread(){
public void run() {
GetStringFromUrl.getString("www.xyz.com");
}
}.start();
}catch(Exception e){
e.printStackTrace();
}
}
Related
I have a PDF file on my Firebase. I am using the AndroidPDFViewer library. Then I retrieve data using AsyncTask.
I want to know how to stop my ProgressBar using the isFinishedI() function in my view class, as this while loop doesn't exit ?
public class PDFHandler {
private PDFView pdfView = null;
private RetriverPDFStream retriverPDFStream;
private RetriverPDFStream getRetriverPDFStream(){ return this.retriverPDFStream; }
public void setPdfView(PDFView pdfView)
{
this.pdfView = pdfView;
}
public void openOnline(String link)
{
retriverPDFStream = new RetriverPDFStream();
retriverPDFStream.execute(link);
}
public boolean isFinished ()
{
if(getRetriverPDFStream().getStatus() == AsyncTask.Status.RUNNING){
return false;
}else{
return true;
}
}
//This class to retrieve pdf online asynchronously
public class RetriverPDFStream extends AsyncTask<String,Void, InputStream> {
#Override
protected InputStream doInBackground(String... strings) {
InputStream inputStream = null;
try{
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
if(urlConnection.getResponseCode() == 200)
{
inputStream = new BufferedInputStream(urlConnection.getInputStream());
}
}catch (IOException e){
return null;
}
return inputStream;
}
#Override
protected void onPostExecute(InputStream inputStream) {
pdfView.fromStream(inputStream).load();
}
}
}
On create method
protected void onCreate(Bundle savedInstanceState) {
pdfView = findViewById(R.id.pdfView);
progressBar = findViewById(R.id.progressBar);
//This is function read PDF from URL
PDFHandler pdfHandler = new PDFHandler();
pdfHandler.setPdfView(pdfView);
pdfHandler.openOnline(link);
progressBar.setVisibility(View.VISIBLE);
while(!pdfHandler.isFinished()){
progressBar.setVisibility(View.INVISIBLE);
}
public boolean isFinished ()
{
if(getRetriverPDFStream().getStatus() == AsyncTask.Status.FINISHED)
{
return true;
}
else
{
return false;
}
}
I have a problem. When I do a query in the stream, I have downloaded the data from the URL, everything works. But when I call AsynsTask example by pressing doInBackground() method that returns the same data, but they are updated on the URL. And they will not be updated as long as the program is restarted.
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL("data.php?"+new Random().nextInt(200));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
jSON_R = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return jSON_R;
}
All code
public class ParseTask extends AsyncTask<Void, Void, String> {
int intRow = 0;
String jSON_R = "";
private List<User> movieList;
Activity act;
ListView list;
LAdapter adapter;
boolean Unique = true;
public ParseTask (Activity act){
this.act = act;
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL("data.php?"+new Random().nextInt(200));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
jSON_R = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return jSON_R;
}
#Override
protected void onPostExecute(String strJson) {
super.onPostExecute(strJson);
list = (ListView) act.findViewById(R.id.listVew);
Button b = (Button) act.findViewById(R.id.refresh);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//To do
}
});
movieList = new ArrayList<>();
adapter = new LAdapter(act, movieList);
list.setAdapter(adapter);
try {
JSONObject dataJsonObj = new JSONObject(strJson);
JSONArray jsa = dataJsonObj.getJSONArray("data");
for (int i = 0; i < jsa.length(); i++) {
JSONObject data1 = chat.getJSONObject(i);
String mes = data1.getString("mes1");
String mes2 = data1.getString("mes2");
String mes3 = data1.getString("mes3");
User m = new User(mes, mes2, mes3);
movieList.add(0, m);
}
adapter.notifyDataSetChanged();
intRow = jsa.length();
} catch (JSONException e) {
e.printStackTrace();
}
list.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem > 1){
Unique = false;
}else{
Unique = true;
}
}
});
Thread thread = new Thread() {
#Override
public void run() {
try {
while (true){
sleep(5000);
if (Unique){
act.runOnUiThread(new Runnable() {
#Override
public void run() {
Update();
}
});
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
private void Update(){
try {
JSONObject dataJsonObj = new JSONObject(strJson);
JSONArray jsa = dataJsonObj.getJSONArray("data");
for (int i = 0; i < jsa.length(); i++) {
JSONObject data1 = chat.getJSONObject(i);
String mes = data1.getString("mes1");
String mes2 = data1.getString("mes2");
String mes3 = data1.getString("mes3");
User m = new User(mes, mes2, mes3);
movieList.add(0, m);
}
adapter.notifyDataSetChanged();
intRow = jsa.length();
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
Calling the object in such a way
new ParseTask(getActivity()).execute();
Close the connection.
I mean use (better) reader.close() or inputStream.close()
Or try jsoup library https://jsoup.org/
I have a Server in Java and a Client in Android. In Android I have an AsyncTask for the receive of the video continuous by the server and a Thread that read the video with the MediaPlayer.
I launch the MediaPlayer after 5s but only the receipt packets are read at the moment when the MediaPlayer is launched.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
vidSurface = (SurfaceView) findViewById(R.id.surfView);
ConcurrentLinkedDeque<OutputStream[]> list = new ConcurrentLinkedDeque<>();
Connexion connexion = new Connexion(list);
connexion.execute();
new Thread(new Task2(list)).start();
}
private class Connexion extends AsyncTask<Void, Void, Void> {
private ConcurrentLinkedDeque<OutputStream[]> list;
public Connexion(ConcurrentLinkedDeque<OutputStream[]> list) {
this.list = list;
}
#Override
protected Void doInBackground(Void... params) {
ConcurrentLinkedDeque<OutputStream[]> list = new ConcurrentLinkedDeque<>();
DownloadVideo dv = new DownloadVideo(list);
dv.connexion();
return null;
}
}
public void launchVideo() {
Thread.sleep(5000);
vidHolder = vidSurface.getHolder();
vidHolder.addCallback(this);
}
class Task2 implements Runnable {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
Log.d("1", "Thread2");
launchVideo();
}
});
}
Thanks a lot.
Download Video :
public void connexion() {
try {
client = new Socket(IP_SERVER, 9003); // Creating the server socket.
if (client != null) {
// Receive video
InputStream in = client.getInputStream();
OutputStream out[] = new OutputStream[1];
// Store on device
out[0] = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Movies/chrono2.mp4");
byte buf[] = new byte[1024];
int n;
while ((n = in.read(buf)) != -1) {
out[0].write(buf, 0, n);
//Adding last in the queue
list.addLast(out);
Log.d("byte" , "" + out);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
In my application, I have an expandablelistview and I want to open a PDF downloaded from the internet when I click on a specific child. The problem is that the pdf file (Read.pdf) is always empty, meaning that the download is not working.
Downloader Class:
public class Downloader {
public static void DownloadFile(String fileURL, File directory) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Part of the Activity:
private void registerClick() {
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
if ((groupPosition == 0) && (childPosition == 0)){
File file = new File(Environment.getExternalStorageDirectory()+File.separator+"IAVE", "Read.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile("https://www.cp.pt/StaticFiles/Passageiros/1_horarios/horarios/PDF/lx/linha_cascais.pdf", file);
AbrirPDF.showPdf();
} else {
}
return false;
}
});
}
I think the OpenPDF (AbrirPDF) doesn't have any problem, but I will post it...
public class AbrirPDF {
public static void showPdf()
{
File file = new File(Environment.getExternalStorageDirectory()+File.separator+"IAVE/Read.pdf");
PackageManager packageManager = ContextGetter.getAppContext().getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ContextGetter.getAppContext().startActivity(intent);
}
}
Thank you.
Ideally, your download should happen in a separate thread to avoid locking your app.
Here is an example that also includes a progress bar.
public class MainActivity extends Activity {
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
private static String file_url = "https://www.cp.pt/StaticFiles/Passageiros/1_horarios/horarios/PDF/lx/linha_cascais.pdf";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadFileFromURL().execute(file_url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/2011.kml");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
}
}
}
I have a little issue about a little thing I don't understand.
It's just a simple request: how do I display an xml I just got in a thread?
There is my method postData to get the xml, I make it display in a log.v as you can see below in the code, but I can't display it to a TextView out of the thread.
public class RecupXml_Activity extends Activity {
TextView campagne;
String user = "toto";
String password = "tata";
String theCampagneXml;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
campagne = (TextView) findViewById(R.id.campagneTest);
postData(user, password);
}
public void postData(final String login, final String password) {
Thread background = new Thread(new Runnable() {
URL url;
String buffer;
String theCampagneXml = null;
#Override
public void run() {
try {
URLConnection urlConnection;
String body = "login=" + URLEncoder.encode(login, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8");
url = new URL("http://3pi.tf/apps/sms/");
urlConnection = url.openConnection();
((HttpURLConnection) urlConnection).setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length", "" + body.length());
OutputStreamWriter writer = null;
BufferedReader reader = null;
writer = new OutputStreamWriter(urlConnection.getOutputStream());
writer.write(body);
writer.flush();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((buffer = reader.readLine()) != null) {
theCampagneXml = buffer;
}
Log.v("test", "xml = " + theCampagneXml);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
campagne.post(new Runnable() {
#Override
public void run() {
campagne.setText("salut voici ta campagne : " + theCampagneXml);
}
});
}
});
background.start();
}
}
It appears in my Log but not in the TextView:/ I have a white empty Activity.
The problem is that you call postData() on UI-tread, meaning that the method also returns theCampagneXml on UI-thread, while your network operation goes on a worker thread. The following code with some changes and additions fixes the problem:
public class MainActivity extends Activity {
TextView campagne;
String user = "toto";
String password = "tata";
String theCampagneXml; // new
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
campagne = (TextView) findViewById(R.id.text);
postData(user, password); // new
}
public void postData(final String login, final String password) { // note: the return type has been changed
Thread background = new Thread(new Runnable() {
URL url;
String buffer;
String theCampagneXml = null; // new
#Override
public void run() {
try {
// no changes here but declaring `theCampagneXml` as class member
}
campagne.post(new Runnable() {
#Override
public void run() {
campagne.setText("hello, here is your XML : "+ theCampagneXml);
}
});
}
});
background.start();
}
}
Once the network operation is done and theCampagneXml is initialized, use post() for the TextView campagne that runs on UI-thread.
Additional info can be found in Processes and Threads.