I am trying to develop an app that can check if an update of itself is available, and then prompt the user to upgrade or not. One of the things I am having trouble with it being able to pull a the applications version number from online. Assuming that my url is correct and the div class actually exists, which is safe to assume, where is the issue in my code? Here is my code below:
Update called from a button click
public String url = "http://www.myurl.com"
UPDATE.setOnClickListener(new View.OnClickListener() {
String versionString = "";
#Override
public void onClick(View v) {
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(connManager.TYPE_WIFI);
if (mWifi.isConnected()) {
new VersionCheck().execute();
}
}
});
//If wifi is connected then try to pull the version from offline.
private class VersionCheck extends AsyncTask<Void, Void, Void>{
String stringVersion;
int convertedString;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(UpdateActivity.this);
progressDialog.setTitle("Checking Current Version Number");
progressDialog.setMessage("Loading...");
progressDialog.setIndeterminate(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try{
Document document = Jsoup.connect(URL1).get();
Elements element = document.select("div.VERSION_NUM");
stringVersion = element.toString();
convertedString = Integer.parseInt(stringVersion);
}catch (IOException ex){
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
String versionName = "";
int cVersion;
try {
versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
try{
cVersion = Integer.parseInt(versionName);
if(convertedString > cVersion){
Toast.makeText(getApplicationContext(), "NEW Version :D", Toast.LENGTH_SHORT).show();
//Ideally create new dialog here to download the new version
}
}catch (NumberFormatException i){
i.printStackTrace();
}
} catch (PackageManager.NameNotFoundException e) {
}
}
}
Any questions please ask, I will post as much information as I am allowed to.
Thank everyone!
Related
My app crashes when the link is empty. I am trying to download Instagram videos. The apps work fine with public links. But I put a private link the app crashes. This means with a private link the apps get no HTML from the website. And the download links remain empty. Which causes the app to crash. I want when enter a private link app wouldn't crash
I tried to use if-else statements in the onPostExecute method but it didn't work or maybe I am doing it the wrong way.
This AsyncTask class
private class InstaVideo extends AsyncTask<Void, Void, Void> {
String dlink, imglink;
#Override
protected void onPreExecute() {
ProgressBar progressBar = (ProgressBar) findViewById(R.id.loading_indicator);
progressBar.setVisibility(View.VISIBLE);
DoubleBounce doubleBounce = new DoubleBounce();
progressBar.setIndeterminateDrawable(doubleBounce);
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
try {
Document doc = Jsoup.connect("https://www.10insta.net/#grid-gallery")
.data("url", temp)
.post();
Log.v("Hello", doc.title());
Element srctag = doc.select("img.card-img-top").first();
Element ptag = doc.select("p.card-text").first();
Element atag = ptag.select("a").first();
imglink = srctag.attr("src");
dlink = "https://www.10insta.net/";
dlink += atag.attr("href");
Log.i("DownloadActivity",dlink);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (dlink=="https://www.10insta.net/download.php?url=") {
Toast.makeText(DownloadActivity.this,"Link is private",Toast.LENGTH_SHORT).show();
} else {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
TextView t = (TextView) findViewById(R.id.imgtxt);
if (Content.id == 2) {
t.setText("Video Preview");
} else {
t.setText("Image Preview");
}
t.setVisibility(View.VISIBLE);
Button b = (Button) findViewById(R.id.instadownload);
b.setVisibility(View.VISIBLE);
final ImageView img = (ImageView) findViewById(R.id.instaimg);
Picasso.get().load(imglink).placeholder(R.drawable.loading).into(img);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(dlink);
DownloadManager.Request req = new DownloadManager.Request(uri);
req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
if (Content.id == 2) {
req.setDestinationInExternalPublicDir("/VideoDownloader", "insta.mp4");
} else {
req.setDestinationInExternalPublicDir("/VideoDownloader", "insta.jpg");
}
StyleableToast.makeText(getBaseContext(), "Download Started", Toast.LENGTH_SHORT, R.style.mytoast).show();
Long ref = dm.enqueue(req);
}
});
}
}
}
doInBackground fetch HTML from the website and filters the required video download link. This works fine with public links but crashes with private links.
Now I want when I enter a private link app wouldn't crash. help is much appreciated
Error Image
Since you have mentioned if-else not working to check image path then try to consume the exception using try - catch block.
try {
Picasso.get().load(imglink).placeholder(R.drawable.loading).into(img);
} catch(Exception ex) {
ex.printStackTrace();
t.setVisibility(View.GONE);
b.setVisibility(View.GONE);
}
Besides this, you use == operator to compare String which give you false always. Try using equals()/equalsIgnoreCase()
if (dlink.equalsIgnoreCase("https://www.10insta.net/download.php?url="))
I am trying to develop an application that reads jokes from a URL. I am using an AsyncTask to read from URL and then put the string to a textView. But I can't figure out why it isn't working.
Here is my code:
public class MainActivity extends AppCompatActivity {
private Button oneJokeBtn, threeJokesBtn;
private final static String ERROR_TAG = "Download Error";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Capturing our buttons from the view
oneJokeBtn = findViewById(R.id.joke_1);
threeJokesBtn = findViewById(R.id.joke_3);
// Register the onClick listener
oneJokeBtn.setOnClickListener(buttonHandler);
threeJokesBtn.setOnClickListener(buttonHandler);
// Declaring the Spinner
Spinner spinner = findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.length_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
// Spinner onItemSelector implemented in the OnCreate Method
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
Toast.makeText(parent.getContext(), R.string.short_toast, Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(parent.getContext(), R.string.medium_toast, Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(parent.getContext(), R.string.long_toast, Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
/** AsyncTask that reads one joke directly from the URL and adds it to the textView */
private class Download1JokeAsyncTask extends AsyncTask <Void, Void, String> {
private ProgressDialog progressDialog;
private String mResponse = "";
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage(getString(R.string.progress_msg));
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected String doInBackground(Void... voids) {
String joke = null;
try {
// Open a connection to the web service
URL url = new URL( "http://www-staff.it.uts.edu.au/~rheise/sarcastic.cgi" );
URLConnection conn = url.openConnection();
// Obtain the input stream
BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream()));
// The joke is a one liner, so just read one line.
joke = in.readLine();
// Close the connection
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
Log.e(ERROR_TAG, "Exception: ", e);
mResponse = getString(R.string.fail_msg);
} catch (IOException e) {
e.printStackTrace();
Log.e(ERROR_TAG, "Exception: ", e);
mResponse = getString(R.string.fail_msg);
}
return joke;
}
#Override
protected void onPostExecute(String joke) {
TextView tv = findViewById(R.id.tv_joke);
if (joke == null) {
tv.setText(R.string.fail_msg);
}
else {
tv.setText(joke);
}
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
/** AsyncTask that reads three jokes directly from the URL and adds it to the textView */
private class Download3JokeAsyncTask extends AsyncTask<Void, Integer, String[]> {
private ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setProgress(0);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setCancelable(true);
mProgressDialog.setMessage(getString(R.string.three_jokes_btn));
mProgressDialog.show();
}
#Override
protected String[] doInBackground(Void... voids) {
int count = 2;
for (int i = 0; i < 2; i++){
try {
URL url = new URL("http://www.oracle.com/");
URLConnection conn = url.openConnection();
// Obtain the input stream
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// The joke is a one liner, so just read one line.
String joke;
while ((joke = in.readLine()) != null) {
System.out.println(joke);
}
// Close the connection
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
Log.e(ERROR_TAG, "Exception: ", e);
} catch (IOException e) {
e.printStackTrace();
Log.e(ERROR_TAG, "Exception: ", e);
}
publishProgress((int) ((i / (float) count) * 100));
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
setProgress(0);
}
#Override
protected void onPostExecute(String[] strings) {
super.onPostExecute(strings);
}
}
/** onClickListener that gets the id of the button pressed and download jokes accordingly */
OnClickListener buttonHandler = new OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.joke_1:
new Download1JokeAsyncTask().execute();
break;
case R.id.joke_3:
new Download3JokeAsyncTask().execute();
break;
}
}
};
The AsyncTask is called Download1JokeAsyncTask, it is supposed to read from URL and then put it into a text view. and I've put an error message to appear in the text view if the joke (the string where the joke is stored) is null.
And always the text view says that it failed to download a message.
Please help.
I went to your joke page and inspecting the source (in Firefox) and I found this:
<html>
<head>
<link rel="alternate stylesheet" type="text/css" href="resource://content-accessible/plaintext.css" title="Wrap Long Lines">
</head>
<body>
<pre>I'm really good at stuff until people watch me do that stuff.</pre>
</body>
</html>
So you could save the whole output as a String and then use this:
string.substring(string.indexOf("<pre>"), string.indexOf("</pre>");
string.substring(4);
Basically you are downloading only the first line of the page which would be the content declaration.
Instead you need to download the sixth line and remove the pre tags.
Good Luck!
In my app i am loading bulk data from web and it insert into sqlite table, when i store data into sqlite table my App UI getting slow and show ANR dialog,
below is my code for load data from web and insert to sqlite table
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
if (array.length() != 0) {
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
AirportModel model = new AirportModel();
String cityName = object.getString("airport_city_name");
String cityCode = object.getString("airport_city_code");
String country = object.getString("airport_country_name");
String name = object.getString("airport_name");
dbHelper.insertAiports(cityName, cityCode, name, country);
}
}
Toast.makeText(getApplicationContext(), String.valueOf(array.length()), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Founded JSON Exception", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(FlightSearchActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(FlightSearchActivity.this);
queue.add(request);
this my code for insert data to sqlite table
public void insertAiports(String airportCityName, String aiportCityCode, String airportName, String airportConutryName) {
SQLiteDatabase database = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(AIRPORT_FIELD_CITY_NAME, airportCityName);
values.put(AIRPORT_FIELD_CITY_CODE, aiportCityCode);
values.put(AIRPORT_FIELD_NAME, airportName);
values.put(AIRPORT_FIELD_COUNTRY_NAME, airportConutryName);
database.insert(TABLE_AIRPORTS, null, values);
}
when run this code my app UI getting slow and show dialog "app isn't responding
Do you want close ?"
Anyone can suggest a idea to insert bulk data to sqlite table without hanging of my UI.
If you are doing bulk operations in db, use transactions for better performance.
Eg:
db.beginTransaction();
try {
// do your bulk insert
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
You should use an AsyncTask to do bulk processes in background, not in the main thread (UI thread).
https://developer.android.com/reference/android/os/AsyncTask.html
perform database operation on separate thread because it takes time. you can use:
1.AsyncTask
2.Service
use AsyncTask get json data under it and add data to sqlite,
look at the demo of it :
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText time;
private TextView finalResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
time = (EditText) findViewById(R.id.in_time);
button = (Button) findViewById(R.id.btn_run);
finalResult = (TextView) findViewById(R.id.tv_result);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AsyncTaskRunner runner = new AsyncTaskRunner();
String sleepTime = time.getText().toString();
runner .execute(sleepTime);
}
});
}
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
private String resp;
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
publishProgress("Sleeping..."); // Calls onProgressUpdate()
try {
int time = Integer.parseInt(params[0])*1000;
Thread.sleep(time);
resp = "Slept for " + params[0] + " seconds";
} catch (InterruptedException e) {
e.printStackTrace();
resp = e.getMessage();
} catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
progressDialog.dismiss();
finalResult.setText(result);
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this,
"ProgressDialog",
"Wait for "+time.getText().toString()+ " seconds");
}
#Override
protected void onProgressUpdate(String... text) {
finalResult.setText(text[0]);
}
}
}
I am trying to download file using AsyncTask and also wanted to implement cancel button in progress dialog to cancel the download.
i think the problem is in "doInBackground" method. here is my asynctask:
public class Download_result extends AsyncTask<String,Integer,Void>{
ProgressDialog progressDialog;
Context context;
String pdfFile;
Download_result(Context context, String pdfFile){
this.context=context;
this.pdfFile=pdfFile;
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Downloading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(200);
progressDialog.setCancelable(false);
progressDialog.setProgress(0);
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Download_result.this.cancel(true); //cancel asynctask here
dialog.dismiss();
}
});
progressDialog.show();
}
#Override
protected Void doInBackground(String... params) {
//given below
}
#Override
protected void onProgressUpdate(Integer... values) {
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result) {
progressDialog.cancel();
}
}
"doInBackground" method:
#Override
protected Void doInBackground(String... params) {
String url_1=params[0];
int file_length=0;
try {
URL url = new URL(url_1);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
file_length=urlConnection.getContentLength();
filesize=file_length;
File sdCard = Environment.getExternalStorageDirectory();
File new_folder = new File (sdCard.getAbsolutePath() + "/xxx");
File input_file = new File(new_folder,pdfFile);
InputStream inputStream = new BufferedInputStream(url.openStream(),8192);
byte[] data=new byte[1024];
int total=0,count=0;
OutputStream outputStream = new FileOutputStream(input_file);
while ((count=inputStream.read(data))!=-1){
total+=count;
outputStream.write(data,0,count);
int progress= (total*200)/file_length;
downloadedsize=total;
publishProgress(progress);
if(isCancelled()){
break; or return null; // same result
}
}
inputStream.close();
outputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
try this:
boolean downloadstatus = true;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Downloading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(200);
progressDialog.setCancelable(false);
progressDialog.setProgress(0);
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
download.cancel(true);
downloadstatus=false; //add boolean check
dialog.dismiss();
}
});
progressDialog.show();
}
Now in your doInbackGround()
while ((count=inputStream.read(data))!=-1){
if(!your_AsyncTask.isCancelled() || downloadstatus !=false){
total+=count;
outputStream.write(data,0,count);
int progress= (total*200)/file_length;
downloadedsize=total;
publishProgress(progress);
}else{
break;
}
}
This is a reply to my own post(may be in future someone need this):
Actualy my asynctask get cancel, but i didn't know because i thought that when we cancel the asynctask the file should not be there. But actualy when we cancel async task the file is stored but with the smaller size.
eg. Suppose the file is 1mb and i have cancel asynctask while progress dialog shows 50% then only 500kb file is stored, and i thought this is the actual file. sorry for my mistake.
So the logic is when someone press cancel you need to delete the half downloaded file too.
and sorry for my English, it's terrible i know.
This question already has answers here:
Updating progress dialog in Activity from AsyncTask
(2 answers)
How to use AsyncTask to show a ProgressDialog while doing background work in Android? [duplicate]
(2 answers)
Closed 8 years ago.
I want to add progressbar while new activity is not opened.
on next activity I am also fetching data so I want to add a progress bar on next activity also.
Here is my code.
login=(Button)dialog.findViewById(R.id.buttonLogin);
login.setOnClickListener(new OnClickListener() {
#SuppressLint("DefaultLocale")
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(LoginUsername.getText()==null||LoginUsername.getText().toString().equals(""))
{
LoginUsername.setHint("Enter Username");
LoginUsername.setHintTextColor(Color.RED);
}
else if(LoginPassword.getText()==null||LoginPassword.getText().toString().equals("")||LoginPassword.getText().toString().length()<6)
{
LoginPassword.setText("");
LoginPassword.setHint("Enter Password");
LoginPassword.setHintTextColor(Color.RED);
}
else
{
String username=LoginUsername.getText().toString();
String password=LoginPassword.getText().toString();
username1=username.toLowerCase();
// fetch the Password form database for respective user name
//String loginentries=database.getSingleEntry(username1);
//type=database.getType(username1);
try{
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost("http://www.universal-cinemas.com/android/login.php");
JSONObject jobj=new JSONObject();
jobj.put("username",username1);
jobj.put("password", password);
post.setEntity(new StringEntity(jobj.toString()));
Log.i("Info", "Sending request");
HttpResponse res=client.execute(post);
Log.i("Info", "Executed");
InputStream inp=res.getEntity().getContent();
BufferedReader bf = new BufferedReader(new InputStreamReader(inp));
StringBuilder sb= new StringBuilder();
sb.append(bf.readLine()+"\n");
String tmp="0";
while((tmp=bf.readLine())!=null)
{
sb.append(tmp+"\n");
}
String result= sb.toString();
JSONArray jarray=new JSONArray(result);
for(int i=0;i<jarray.length();i++)
{
a=1;
JSONObject job=jarray.getJSONObject(i);
type=job.getString("type");
currency=job.getString("currency");
}
}
catch(Exception e)
{
e.printStackTrace();
}
if(a==1)
{
i=new Intent(getApplicationContext(),User_MainOptions_List.class);
startActivity(i);
finish();
Toast.makeText(getApplicationContext(), "Welcome "+username, Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Username and Password is not correct", Toast.LENGTH_SHORT).show();
}
}
}
});
dialog.show();
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes(); // retrieves the windows attributes
lp.dimAmount=0.7f;// sets the dimming amount to zero
dialog.getWindow().setAttributes(lp); // sets the updated windows attributes
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND); // adds the flag to blur bg
}
});
class MyLodingAsycTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
runOnUiThread(new Runnable() {
public void run() {
progressDialog = new ProgressDialog(CameraActivity.this);
progressDialog.setMessage("Loding...");
progressDialog.setCancelable(false);
progressDialog.show();
}
});
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
runOnUiThread(new Runnable() {
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
#Override
protected Void doInBackground(Void... params) {
//call HTTP service
return null;
}
}
try this
private class MyAsync extends AsyncTask {
ProgressDialog PD;
#Override
protected void onPreExecute() {
super.onPreExecute();
PD = new ProgressDialog(MainActivity.this);
PD.setTitle("Please Wait..");
PD.setMessage("Loading...");
PD.setCancelable(false);
PD.show();
}
#Override
protected Void doInBackground(Void... params) {
//do what u want
return result;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
PD.dismiss();
}
}
}