Error:java.lang.IllegalArgumentException: Empty file name Android - android

I'am creating application which gets data from MySQL db. Few days ago I made few big changes one of them is that instead of multiple activity forms,I am using fragments and toolbar to switch between them. After that i noticed that i got this error:
02/com.example.kurpaest.kurpaest W/JNIHelp﹕ Discarding pending exception (java.lang.NullPointerException) to throw java/lang/IllegalArgumentException
09-12 14:50:53.180 15402-15402/com.example.kurpaest.kurpaest E/MSG﹕ **java.lang.IllegalArgumentException: Empty file name**
This error shows up when my top 5 places is returning null. But when I try to debug application it runs smoothly with out error or any kind problem.
My server is on my pc and i connect to it using IP address which is provided by ISP.
One more interesting thing is that this error shows up more often when wifi is used instead of mobile network.
One of my guesses is that servers configuration is incorrect and second part is that all tabs makes there own requests to server instead of one complete request.
In the doInBackground() method the app stops suddenly:
#Override
protected String doInBackground(String... params) {
handler.post(new Runnable() {
#Override
public void run() {
gps = new GpsTracker(context);
}
});
HashMap<String,String> param = new HashMap<String,String>();
//param.put("lat", String.valueOf(gps.getLatitude()));
// param.put("long", String.valueOf(gps.getLongitude()));
JSONObject json = jsonParser.makeHttpRequest(url_all_products,"GET",param);
try{
int success = json.getInt(TAG_SUCCESS);
switch(success){
case 1:
products = json.getJSONArray(TAG_LUNCH);
for(int i = 0;i<5;i++){
JSONObject c = products.getJSONObject(i);
String id = c.getString(TAG_ID);
String name =c.getString(TAG_NAME);
Log.d("MSG", name);
String picture ="images/"+c.getString(TAG_PICTURE)+".png";
Log.d("MSG", picture+"wasd");
String cost = c.getString(TAG_COST);
Log.d("MSG", cost);
String lat = c.getString(TAG_LAT);
String longi = c.getString(TAG_LONG);
Log.d("MSG", lat + longi);
String worktime = c.getString(TAG_WORKTIME);
**Log.d("MSG", worktime);**
String distance = calcDist(lat, longi);
lunchList[i][0] = id;
lunchList[i][1] = name;
lunchList[i][2] = picture;
lunchList[i][3] = cost;
lunchList[i][4] = worktime;
lunchList[i][5] = distance ;
gps.stopUsingGPS();
}
break;
case 2:
handler.post(new Runnable() {
#Override
public void run() {
notNetworkDialog.setTitle("Neizdevās izveidot savienojumu!");
notNetworkDialog
.setMessage("Neizdevās izveidot savienojumu ar datu serveri, serveris nav pieejams \n" +
"Mēģināt velreiz?")
.setCancelable(false)
.setPositiveButton("Jā", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
new LoadLunches().execute();
}
})
.setNegativeButton("Nē", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((Activity)context).finish();
}
});
AlertDialog alertDialog = notNetworkDialog.create();
alertDialog.show();
}
});
break;
case 3:
handler.post(new Runnable() {
#Override
public void run() {
notNetworkDialog.setTitle("Neizdevās izveidot savienojumu!");
notNetworkDialog
.setMessage("Neizdevās izveidot savienojumu ar datu serveri, lūdzu pārliecinaties, ka tālrunis ir savienots ar internetu! \n" +
"Mēģināt velreiz?")
.setCancelable(false)
.setPositiveButton("Jā", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
new LoadLunches().execute();
}
})
.setNegativeButton("Nē", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((Activity)context).finish();
}
});
AlertDialog alertDialog = notNetworkDialog.create();
alertDialog.show();
}
});
break;
case 0:
handler.post(new Runnable() {
#Override
public void run() {
notNetworkDialog.setTitle("Kļūda");
notNetworkDialog
.setMessage("Kļūme pieprasījuma! \n" +
"Mēģināt velreiz?")
.setCancelable(false)
.setPositiveButton("Jā", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
new LoadLunches().execute();
}
})
.setNegativeButton("Nē", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((Activity)context).finish();
}
});
AlertDialog alertDialog = notNetworkDialog.create();
alertDialog.show();
}
});
break;
}
}catch(Exception e){
Log.d("MSG",e.toString());
}
return null;
}
Programs works till Log.d("MSG",worktime).
Then skips calculations and continues at these lines:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pDialog.dismiss();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
lunchAdapter adapter = new lunchAdapter(getActivity(), lunchList, lunchid);
lv.setAdapter(adapter);
}
});
}

I didn't find real cause of such error in my case. Because i recived all data from my DB and further there is no any other files which name could be wrong or missing. So my workaround was quite simple.
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
lunchAdapter adapter = new lunchAdapter(getActivity(), lunchList, lunchid);
lv.setAdapter(adapter);
}
});
i added new lines
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if(lunchlist==null){
new LoadLunches().execute();
}else{
lunchAdapter adapter = new lunchAdapter(getActivity(), lunchList, lunchid);
lv.setAdapter(adapter);
}
});

Related

How to parse result of QR-scanning Zbar android?

I use Zbar library for QR-scanning.
I try to parse result of this scanning, but I lost some information. For parsing I use this library.
Does any other library can parse handleResult(Result rawResult) rawResult?
This my code :
#Override
public void handleResult(final Result rawResult) {
Log.v("myLog", rawResult.getContents()); // Prints scan results
Log.v("myLog", rawResult.getBarcodeFormat().getName()); // Prints the scan format (qrcode, pdf417 etc.)
unswer = rawResult.getContents();
if (unswer.contains("VCARD")){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Содержимое");
builder.setMessage(unswer = rawResult.getContents());
builder.setPositiveButton("Добавить контакт", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String parseVcard = unswer;
VCard vCard = VCardParser.parse(parseVcard);
String name = vCard.getName();
String fname = vCard.getFormattedName();
Log.d("myLog", name + " " + fname);
addContact(fname + " " + name);
}
});
builder.setNegativeButton("Отмена", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mScannerView.resumeCameraPreview(SimpleScannerActivity.this);
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
vCard.getFormattedName() is not going to return you a value because your rawResult does not contain a "FN" value. When you look at the value you sent it only contains "N" which means you'll only have value with vCard.getName();

Show dialog box when json string is not true

public class Recyclerview extends AppCompatActivity {
private RecyclerView mRecyclerView;
CustomAdapter cu;
ArrayList<Employee> arr, arr1;
Toolbar toolbar;
TextView t1, t2;
long l = 0;
private ProgressDialog progress;
int j;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview);
toolbar = (Toolbar) findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
final RecyclerView rv = (RecyclerView) findViewById(R.id.rv);
rv.setHasFixedSize(true);
arr = new ArrayList<Employee>();
arr = InitializeData();
final LinearLayoutManager llm = new LinearLayoutManager(Recyclerview.this);
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
cu = new CustomAdapter(Recyclerview.this, arr);
final bank ban = new bank(Recyclerview.this);
rv.setAdapter(cu);
registerForContextMenu(rv);
ImageButton refresh = (ImageButton) findViewById(R.id.refresh);
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progress = ProgressDialog.show(Recyclerview.this, "dialog title",
"dialog message", true);
Toast.makeText(Recyclerview.this, "ok", Toast.LENGTH_LONG).show();
if (isNetworkAvailable()) {
String url = ConstantValues.BASE_URL;
RequestBody formBody = new FormBody.Builder()
.add("key1", "value1")
.add("key2", "value2")
.add("key3", "value3")
.build();
try {
post(url, formBody, new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.e("JSONDemo", "IOException", e);
}
#Override
public void onResponse(final Call call, final Response response) throws IOException {
String JSON = response.body().string();
Log.e("res", " " + JSON);
try {
JSONObject jsonObj = new JSONObject(JSON);
JSONArray resultarr = jsonObj.getJSONArray("result");
final JSONArray resultarr1 = jsonObj.getJSONArray("result1");
if (resultarr1.length() == 0 ) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(Recyclerview.this);
builder1.setMessage("No data found");
builder1.setCancelable(true);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
} else {
ban.OpenDB();
/*Delete old Data from Table*/
ban.Delete("");
for (int i = 0; i < resultarr1.length(); i++) {
Employee emp = new Employee();
JSONObject result1obj = resultarr1.getJSONObject(i);
String result1Id = result1obj.getString(ConstantValues.Bank_ID);
String result1NAME = result1obj.getString(ConstantValues.Bank_NAME);
Log.e("result", " " + result1Id);
Log.e("result", " " + result1NAME);
emp.setId(result1obj.getString(ConstantValues.Bank_ID));
emp.setName(result1obj.getString(ConstantValues.Bank_NAME));
arr.add(emp);
l = ban.InsertQryForTabEmpData(result1Id, result1NAME);
}
ban.CloseDB();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
// you can access all the UI componenet
if (progress.isShowing())
progress.dismiss();
cu.notifyDataSetChanged();
}
});
} catch (Exception e) {
Log.e("JSONDemo", "onResponse", e);
AlertDialog.Builder builder1 = new AlertDialog.Builder(Recyclerview.this);
builder1.setMessage("No data found");
builder1.setCancelable(true);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
}
}
});
} catch (Exception e) {
Log.e("JSONDemo", "Post Exception", e);
}
} else {
Toast.makeText(Recyclerview.this, "Internet not available", Toast.LENGTH_LONG).show();
}
}
});
}
private ArrayList<Employee> InitializeData() {
ArrayList<Employee> arr_emp = new ArrayList<Employee>();
bank ban = new bank(Recyclerview.this);
long l = 0;
ban.OpenDB();
arr_emp = ban.AllSelectQryForTabEmpData();
ban.CloseDB();
return arr_emp;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private final OkHttpClient client = new OkHttpClient();
Call post(String url, RequestBody formBody, Callback callback) throws IOException {
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Call call = client.newCall(request);
call.enqueue(callback);
return call;
}
}
By calling wrong Api it should give dialog box saying unavailable data and is it possible to write dialog box in catch but its not showing dialog box do help me to get rid out of it I dont know where to use if and else...error is coming on String JSON = response.body().string(); thank you in advance
Create a method called like showAlertDialog
public void showAlertDialog(String title, String message) {
final AlertDialog.Builder builder1 = new AlertDialog.Builder(Recyclerview.this);
builder1.setTitle(title);
builder1.setMessage(message);
builder1.setCancelable(true);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
runOnUiThread(new Runnable() {
#Override
public void run() {
builder1.show();
}
});
}
Call this method from catch block.
One things which i can notice in your code is that
1) You are not creating dialog
2) You are not showing your dialog
With respect to code this is what you need to do extra in your code:
AlertDialog alertDialog = builder1.create();
alertDialog.show();
You can create separate method which you can call in your try and catch block:
public void showErrorAlert()
{
builder1 = new AlertDialog.Builder(Recyclerview.this);
builder1.setMessage("No data found");
builder1.setCancelable(true);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = builder1.create();
alertDialog.show();
}
Hope this helps you somehow.

Android 4.4 SQLite Not Updating

I have a fully functional SQLite database in my Android App which works perfect on my testing devices (Android 4.0 - 4.3), but I have a user running KitKat and they are unable to update the database. To summarize my code, I have a user click a switch, then asks whether they want to make the change, if so it updates the database table.
Here is my calls to the database from the Activity:
StatusData statusData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_macro);
statusData = new StatusData(getBaseContext());
}
#Override
public void onClick(View v) {
AlertDialog.Builder alertDialogBuilder;
AlertDialog alertDialog;
switch (v.getId())
case R.id.switchOffSeason:
String season,
seasonHeading = "";
alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog message
if (switchOffSeason.isChecked()) {
season = "This will delete all your current settings and default to the standard diet. This cannot be undone";
seasonHeading = "Set Standard Diet";
} else {
season = "This will delete all your current settings and default to Off-Season diet. This cannot be undone.";
seasonHeading = "Set Off-Season Diet";
}
// set title
alertDialogBuilder.setTitle(seasonHeading);
alertDialogBuilder
.setMessage(season)
.setCancelable(false)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
String passedTask = "offSeason";
dropTable task = new dropTable(passedTask);
task.execute(passedTask);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
if (switchOffSeason.isChecked()) {
switchOffSeason.setChecked(false);
} else {
switchOffSeason.setChecked(true);
}
dialog.cancel();
}
});
alertDialog = alertDialogBuilder.create();
private class dropTable extends AsyncTask<String, Void, String> {
String task;
public dropTable(String passedTask) {
super();
task = passedTask;
}
#Override
protected String doInBackground(String... params) {
if (task.equals("reset")) {
String offSeason = statusData.profileTable()[10];
profileTable = statusData.profileTable();
statusData.dropReloadMacrosTable(new String[] {
profileTable[11], profileTable[12], profileTable[13],
profileTable[14], profileTable[15], profileTable[16],
profileTable[17], offSeason });
} else if (task.equals("offSeason")) {
if (switchOffSeason.isChecked()) {
statusData.updateFieldProfile(new String[] { "offseason",
"1" });
} else {
statusData.updateFieldProfile(new String[] { "offseason",
"0" });
}
String offSeason = statusData.profileTable()[10];
statusData.dropReloadMacrosTable(new String[] {
profileTable[11], profileTable[12], profileTable[13],
profileTable[14], profileTable[15], profileTable[16],
profileTable[17], offSeason });
}
return "Executed";
}
Here is my StatusData (Database) class:
public void updateFieldProfile(String updateArray[]) {
open();
Log.i("log", "in method");
String fieldToUpdate = updateArray[0];
String valueToUpdate = updateArray[1];
String query = "UPDATE PROFILE SET " + fieldToUpdate + "="
+ "= ?";
Log.i("logQuery", query);
Cursor c = db.rawQuery(query, new String[] {valueToUpdate});
c.moveToFirst();
c.close();
db.close();
}

Search for network printer NetworkOnMainThreadException [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 8 years ago.
I get a android.os.NetworkOnMainThreadException when I run this code the jar is provide by the printer manufacture. The error come right at the StarIOPort.searchPrinter. I don't get the error running the demo code provide from the manufacture.
I'm trying to see if there is any network printers available on the local network.
private void PortDiscovery(String interfaceName)
{
final EditText editPortName;
ArrayList<String> arrayPortName;
List<PortInfo> BTPortList;
List<PortInfo> TCPPortList;
final ArrayList<PortInfo> arrayDiscovery;
try {
if (true == interfaceName.equals("BT")) {
BTPortList = StarIOPort.searchPrinter("BT:");
for (PortInfo portInfo : BTPortList) {
arrayDiscovery.add(portInfo);
}
}
if (true == interfaceName.equals("LAN")) {
TCPPortList = StarIOPort.searchPrinter("TCP:");
for (PortInfo portInfo : TCPPortList) {
arrayDiscovery.add(portInfo);
}
}
arrayPortName = new ArrayList<String>();
for(PortInfo discovery : arrayDiscovery) {
String portName;
portName = discovery.getPortName();
if(discovery.getMacAddress().equals("") == false) {
portName += "\n - " + discovery.getMacAddress();
if(discovery.getModelName().equals("") == false) {
portName += "\n - " + discovery.getModelName();
}
}
arrayPortName.add(portName);
}
} catch (StarIOPortException e) {
e.printStackTrace();
}
editPortName = new EditText(this);
new AlertDialog.Builder(this).setTitle("Please Input Port Name").setView(editPortName).setPositiveButton("OK", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int button){
EditText portNameField = (EditText)findViewById(R.id.printerName);
portNameField.setText(editPortName.getText());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int button) {
}
})
.setItems(arrayPortName.toArray(new String[0]), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int select) {
EditText portNameField = (EditText)findViewById(R.id.printerName);portNameField.setText(arrayDiscovery.get(select).getPortName());
}
})
.show();
}
You're getting the NetworkOnMainThreadException because the Android OS does not allow heavy processes (like network related operations) to run on the main thread (also called the UI Thread sometimes) because those operations/process may take a lot of resources and time to operate, and therefore, the application may lag.
A solution is to put your process in an executable thread and instantiate that thread in your onCreate() or where ever you need it, for example, on an onClickListener();. Do is like so:
private class Print extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d("Hi", "Print Commencing");
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Printing...");
String message= "Printing";
SpannableString ss2 = new SpannableString(message);
ss2.setSpan(new RelativeSizeSpan(2f), 0, ss2.length(), 0);
ss2.setSpan(new ForegroundColorSpan(Color.BLACK), 0, ss2.length(), 0);
pDialog.setMessage(ss2);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
Log.d("Hi", "Printing");
//Toast.makeText(getApplicationContext(), "Printing.", Toast.LENGTH_LONG).show();
//insert your code here
return "Executed!";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Toast.makeText(getApplicationContext(), "Done printing.", Toast.LENGTH_LONG).show();
Log.d("Hi", "Done Printing.");
pDialog.dismiss();
}
}
and call it from a function like so:
new Print().execute("")
In the onPreExecute(), I initialize a progressDialog that is not cancellable to guarantee that your process ends properly. You should insert your code in the doInBackground(); part.

Android AsyncTask Dialog fast close

My code:
private class selectBookInAutor extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
arr_book_title.clear();
arr_book_href.clear();
mProgressDialog = new ProgressDialog(_context);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
Document doc = null;
StringBuilder sb = new StringBuilder();
try {
doc = Jsoup.connect(params[0]).userAgent("Mozilla").get();
Elements links = doc.select("li>a");
for (Element link : links) {
sb.append(link.text());
arr_book_title.add(link.text());
arr_book_href.add(Jsoup.clean(link.attr("abs:href"), Whitelist.basic()));
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override
protected void onPostExecute(String result) {
if (result != ""){
final CharSequence[] items = arr_book_title.toArray(new CharSequence[arr_book_title.size()]);
final ArrayList seletedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(_context);
builder.setTitle("Select The Difficulty Level");
builder.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
if (isChecked) {
seletedItems.add(indexSelected);
}else if(seletedItems.contains(indexSelected)){
seletedItems.remove(Integer.valueOf(indexSelected));
}
}
}).setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
for (Object s : seletedItems){
String[] separated = selGroupParam.split(";");
String _idautor = separated[0].toString();
long id_book = db.insertBOOK(_idautor, arr_book_href.get(Integer.valueOf(s.toString())).toString(), "", arr_book_title.get(Integer.valueOf(s.toString())).toString());
new **saveBookInAutor().execute(arr_book_href.get(Integer.valueOf(s.toString())).toString(), _idautor, String.valueOf(id_book));**
}
refreshList();
}
}).setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
}).create().show();
}else{
Toast.makeText(_context, "Error", Toast.LENGTH_SHORT).show();
}
mProgressDialog.dismiss();
}
}
private class saveBookInAutor extends AsyncTask<String, Void, String> {
String _idautor, _idbook;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog2 = new ProgressDialog(_context);
mProgressDialog2.setMessage("Save to file");
mProgressDialog2.setIndeterminate(false);
mProgressDialog2.show();
}
#Override
protected String doInBackground(String... params) {
Document doc = null;
String _html = "";
_idautor = params[1];
_idbook = params[2];
try {
doc = Jsoup.connect(params[0]).userAgent("Mozilla").get();
_html = doc.select("dd").outerHtml();
} catch (IOException e) {
e.printStackTrace();
}
return Jsoup.clean(_html, Whitelist.basic());
}
#Override
protected void onPostExecute(String result) {
if (result != ""){
Toast.makeText(_context, "Save file", Toast.LENGTH_SHORT).show();
String html = "<html lang='ru'><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/></head><body>"+result+"</body></html>";
//String html = result;
**savePageToFile(_idautor + "_" + String.valueOf(_idbook), html);**
}else{
Toast.makeText(_context, "Error", Toast.LENGTH_SHORT).show();
}
mProgressDialog2.dismiss();
}
}
public void refreshList() {
Intent intent = new Intent(_context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
_context.startActivity(intent);
}
public void savePageToFile(String filename, String html) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(_context.openFileOutput(filename, Context.MODE_PRIVATE));
outputStreamWriter.write(html);
outputStreamWriter.close();
}
catch (IOException e) {
//Log.e("Exception", "File write failed: " + e.toString());
}
}
When you select a page and clicking "Ok" ProgressDialog mProgressDialog2 opens and displays just a 1 second. Because of this, I do not see the download Page or not.
How to make mProgressDialog2 displayed all the while to save the page as a file?
Thank you!
UPD
What i want is :
Start mProgressDialog.
After downloading the page disappears and AlertDialog comes with the question what to choose.
After choosing, mProgressDialog2 should be displayed as long as it downloads and saves the file in the webpage.
However mProgressDialog2 disappears in 1 second, and process of saving the file goes on in silence.
In your onPostExecute method, you unconditionally call
mProgressDialog2.dismiss();
This is closing the dialog immediately after it is displayed. That call should be moved to the handler code for each of the buttons. (i.e.the onClick method for the positive and negative buttons)
in onPostExecute(), compare Strings like
if(!result.equals(""))
and try once.
use equals() method for String comparisons.

Categories

Resources