I'm trying to execute a class(GetDirecoes, which is in the MapsActivity) from another activity (DetailsActivity), the idea is, when I click in the floating action button (DetailsActivity) I execute that class (GetDirecoes) and then close my current activity (DetailsActivity), when I close this activity it will automatically open my parent activity (MapsActivity) which is where the method GetDirecoes is.
I'm trying to execute the method with this:
new MapsActivity.GetDirecoes().execute(latRepr, lngRepr);
But it doesn't work giving me the error:
MapsActivity' is not an enclosing class
The correction that android studio offers me is to make GetDirecoes static, but I can't do that because if I do it the entire class breaks, here's the GetDirecoes class:
public class GetDirecoes extends AsyncTask<String, Void, Void> implements Serializable {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MapsActivity.this);
pDialog.setMessage("Aguarde...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... params) {
HttpHandler sh = new HttpHandler();
txtDistanciaTotal = (TextView) findViewById(R.id.txtDistanciaTotal);
txtDuracaoTotal = (TextView) findViewById(R.id.txtDuracaoTotal);
instrucoes = (TextView) findViewById(R.id.Instrucoes);
String url1 = "https://maps.googleapis.com/maps/api/directions/json?origin=";
String url2 = "&destination=";
String url3 = "&key=AIzaSyBh6tmMrC6QaHMJewFGvGc8xOjc0WMajxQ&language=pt";
String latRepr = params[0];
String lngRepr = params[1];
final String jsonStr = sh.makeServiceCall(url1 + mylatitude + "," + mylongitude + url2 + latRepr + "," + lngRepr + url3);
Log.e(TAG, "Link: " + url1 + mylatitude + "," + mylongitude + url2 + latRepr + "," + lngRepr + url3);
Log.e(TAG, "Resposta do URL: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject root = new JSONObject(jsonStr);
JSONArray routes = root.optJSONArray("routes");
if (routes != null) {
JSONObject singleRout = (JSONObject) routes.get(0);
JSONArray legs = (JSONArray) singleRout.get("legs");
if (legs != null) {
JSONObject singleLeg = (JSONObject) legs.get(0);
//Distancia total
JSONObject distanceT = (JSONObject) singleLeg.get("distance");
if (distanceT != null) {
distT = distanceT.getString("text");
}
//Duracao Total
JSONObject durationT = (JSONObject) singleLeg.get("duration");
if (durationT != null) {
duraT = durationT.getString("text");
}
JSONArray steps = (JSONArray) singleLeg.get("steps");
if (steps != null) {
for (int j = 0; j < steps.length(); j++) {
JSONObject singleStep = (JSONObject) steps.get(j);
HashMap<String, String> direcao = new HashMap<>();
JSONObject distance = (JSONObject) singleStep.get("distance");
//Distancia
if (distance != null) {
String dist = distance.getString("text");
direcao.put("textDi", dist);
}
//Duraçao
JSONObject duration = (JSONObject) singleStep.get("duration");
if (duration != null) {
String dura = duration.getString("text");
direcao.put("textDu", dura);
}
//Polylines
JSONObject singlePolyline = (JSONObject) singleStep.get("polyline");
if (singlePolyline != null) {
String points = singlePolyline.getString("points");
Map<String, String> caminho = new HashMap<>();
caminho.put("points", points);
listaPolylines.add((HashMap<String, String>) caminho);
}
//Instruções
String html = singleStep.getString("html_instructions");
direcao.put("html_instructions2", html);
listaDirecoes.add(direcao);
}
}
}
}
} catch (final JSONException e) {
Log.e(TAG, "ERROR: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "ERROR: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "ERROR");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Verifique a sua ligação à internet", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
final ListView list = (ListView) (MapsActivity.this).findViewById(R.id.listaDirecoes);
ListAdapter adapter = new SimpleAdapter(
(MapsActivity.this),
listaDirecoes,
R.layout.list_item_direcoes,
new String[]{"html_instructions2", "textDi", "textDu"},
new int[]{R.id.Instrucoes, R.id.txtDistancia, R.id.txtDuraçao});
list.setAdapter(adapter);
txtDuracaoTotal.setText(duraT);
txtDistanciaTotal.setText(distT);
fazerCaminho(listaPolylines);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
bottom_sheet.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Log.v(TAG, "Parent Touch");
findViewById(R.id.listaDirecoes).getParent().requestDisallowInterceptTouchEvent(false);
return false;
}
});
listaDirecoesChild.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Log.v(TAG, "CHILD TOUCH");
// Disallow the touch request for parent scroll on touch of child view
v.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
}
}
you can go through Call a Class From another class
private Activity activity;
you should initialize, activity
From another class, call it as :
((DetailsActivity) activity).refreshList(latRepr, lngRepr);
Now in, DetailsActivity.class you can do as,
public void refreshList(String latRepr, String lngRepr) {
new GetDirecoes().execute(latRepr, lngRepr);
}
Related
I am making an weather app, on the main screen app shows current weather for a city that is chosen and on the second activity screen you can find weather for next 3 days. I have WeatherInfoTask.java that is used to get JSON for MainActivity and MultipleWeatherTask.java that is used to get JSON for MultipleDays (activity)
so the MainActivity works fine and I get JSON and all of the info is shown on the screen just as it should be, but when I click on the button that should redirect me to the screen of the MultipleDays, I am redirected and just a plain screen is shown without data and this error is shown:
E/StudioProfiler: JVMTI error: 15(JVMTI_ERROR_THREAD_NOT_ALIVE)
These are my files:
public class MainActivity extends AppCompatActivity {
public static String cityName;
Handler handler;
TextView titleText;
TextView temperatureText;
TextView descriptionText;
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(!isNetworkAvailable()){
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing the App")
.setMessage("No Internet Connection, check your settings")
.setPositiveButton("Close", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.show();
}
handler = new Handler();
titleText = (TextView) findViewById(R.id.titleText);
temperatureText = (TextView) findViewById(R.id.temperatureText);
descriptionText = (TextView) findViewById(R.id.descriptionText);
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setHint("Find City");
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
cityName = place.getName().toString();
updateWeather(cityName);
/*Log.i(TAG, "Place: " + place.getName());*/
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("MainActivity", "An error occurred: " + status);
}
});
}
private void updateWeather(final String city){
new Thread(){
public void run(){
final JSONObject json = WeatherInfoTask.getJSON(MainActivity.this, city);
if(json == null){
Toast.makeText(MainActivity.this, "Error loading weather", Toast.LENGTH_LONG).show();
} else {
handler.post(new Runnable(){
public void run(){
SetWeather(json);
}
});
}
}
}.start();
}
private void SetWeather(JSONObject json){
try {
/*cityField.setText(json.getString("name").toUpperCase(Locale.US) +
", " +
json.getJSONObject("sys").getString("country"));*/
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main"); /*"main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15}*/
titleText.setText(R.string.title + cityName);
descriptionText.setText( /*"description":"light intensity drizzle"*/
details.getString("description") +
"\n" + "Humidity: " + main.getString("humidity") + "%" +
"\n" + "Pressure: " + main.getString("pressure") + " hPa");
temperatureText.setText(
String.format("%.2f", main.getDouble("temp"))+ " ℃");
}catch(Exception e){
Log.e("SimpleWeather", "One or more fields not found in the JSON data");
}
}
public void MultipleDays(View view){
Intent intent = new Intent(this, MultipleDays.class);
startActivity(intent);
}
}
Next one:
public class WeatherInfoTask {
private static final String OpenWeatherAPI =
"http://api.openweathermap.org/data/2.5/weather?q=%s&units=metric";
public static JSONObject getJSON(Context context, String city) {
try {
URL url = new URL(String.format(OpenWeatherAPI, city));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("x-api-key", context.getString(R.string.apikey));
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp = ""; /*tmp = temporary*/
while ((tmp = reader.readLine()) != null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
/*This value will be 404 if the request was not successful*/
if (data.getInt("cod") != 200) {
/*greska*/
return null;
}
return data;
} catch (Exception e) {
return null;
}
Next one:
public class MultipleDays extends AppCompatActivity {
Handler handler;
TextView day1;
TextView day2;
TextView day3;
Integer dayCounter = 1;
Date comparisonDate;
Date currentDate;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Float dailyMin;
Float dailyMax;
Float currMin;
Float currMax;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multiple_days);
handler = new Handler();
day1 = (TextView) findViewById(R.id.day1);
day2 = (TextView) findViewById(R.id.day2);
day3 = (TextView) findViewById(R.id.day3);
updateMultipleWeather(MainActivity.cityName);
}
private void updateMultipleWeather(final String city){
new Thread(){
public void run(){
final JSONObject json = MultipleWeatherTask.getJSON(MultipleDays.this, city);
if(json == null){
Toast.makeText(MultipleDays.this, "Error loading weather", Toast.LENGTH_LONG).show();
} else {
handler.post(new Runnable(){
public void run(){
setWeather(json);
}
});
}
}
}.start();
}
private void setWeather(JSONObject json){
try {
JSONArray list = json.getJSONArray("list");
for (int i=0; i < list.length() ; i++){
if(i == 0) {
String string = list.getJSONObject(i).getString("dt_txt");
string = convertDate(string);
comparisonDate = formatter.parse(string.replace("",""));
dailyMin = Float.parseFloat(list.getJSONObject(i).getString("temp_min"));
dailyMax = Float.parseFloat(list.getJSONObject(i).getString("temp_max"));
}
else if ( dayCounter <=3 ){
String string = list.getJSONObject(i).getString("dt_txt");
string = convertDate(string);
currentDate = formatter.parse(string.replace("","")); //datum u obliku "yy-MM-dd"
if ( comparisonDate == currentDate ){ //ako smo i dalje na istom danu
currMin = Float.parseFloat(list.getJSONObject(i).getString("temp_min"));
currMax = Float.parseFloat(list.getJSONObject(i).getString("temp_max"));
if( dailyMin > currMin ) dailyMin = currMin;
if( dailyMax < currMax ) dailyMax = currMax;
}
else {
switch (dayCounter){
case 1: day1.setText("Minimum temperature: " + String.format("%.2f", dailyMin) + "\n" +
"Maximum temperature: " + String.format("%.2f", dailyMax) + "\n" +
"Weather: " + list.getJSONObject(i-1).getString("description"));
dayCounter++;
break;
case 2: day2.setText("Minimum temperature: " + String.format("%.2f", dailyMin) + "\n" +
"Maximum temperature: " + String.format("%.2f", dailyMax) + "\n" +
"Weather: " + list.getJSONObject(i-1).getString("description"));
dayCounter++;
break;
case 3: day3.setText("Minimum temperature: " + String.format("%.2f", dailyMin) + "\n" +
"Maximum temperature: " + String.format("%.2f", dailyMax) + "\n" +
"Weather: " + list.getJSONObject(i-1).getString("description"));
dayCounter++;
break;
}
}
}
}
Next one:
public class MultipleWeatherTask {
private static final String OpenWeatherAPI =
"api.openweathermap.org/data/2.5/forecast?q=%s&units=metric";
public static JSONObject getJSON(Context context, String city) {
try {
URL url = new URL(String.format(OpenWeatherAPI, city));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("x-api-key", context.getString(R.string.apikey));
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp = ""; /*tmp = temporary*/
while ((tmp = reader.readLine()) != null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
/*This value will be 404 if the request was not successful*/
if (data.getInt("cod") != 200) {
/*greska*/
return null;
}
return data;
} catch (Exception e) {
return null;
}
}
}
File ---> Invalidate Caches / Restart will help you.
I have a code, that should display each item in bank a different image, and if it cant find one: display a default one.
I have got everything to work, except the problem is that it does not display the drawables. How can i fix it?
My code:
public class BankViewFragment extends OSRSFragment {
private static final String TAG = "BankViewFragment";
private static Account account;
private ListView lv;
Handler handler;
ArrayList<HashMap<String, String>> ItemList;
public static BankViewFragment newInstance(final Account account) {
BankViewFragment fragment = new BankViewFragment();
Bundle b = new Bundle();
fragment.setArguments(b);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.bank_view, null);
ItemList = new ArrayList<>();
new GetItems().execute();
lv = view.findViewById(R.id.list);
handler = new Handler(Looper.getMainLooper());
return view;
}
public static int getResId(String resourceName, Class<?> c) {
try {
Field idField = c.getDeclaredField(resourceName);
return idField.getInt(idField);
} catch (Exception e) {
throw new RuntimeException("No resource ID found for: "
+ resourceName + " / " + c, e);
}
}
private class GetItems extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
SharedPreferences sharedpreferences = getContext().getSharedPreferences("minescape", Context.MODE_PRIVATE);
String nikas = sharedpreferences.getString("bankname", "null");
String url = "https://api.minesca.pe/game/classic/stats?username=" + nikas;
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "NIKAS: " + nikas);
Log.e(TAG, "ACCOUNT: " + account);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject items = jsonObj.getJSONObject("bank");
Iterator keys = items.keys();
while(keys.hasNext()) {
String dynamicKey = (String)keys.next();
JSONObject line = items.getJSONObject(dynamicKey);
String item = line.getString("item");
//Integer image = getResId(item, Drawable.class);
final Integer image = getResources().getIdentifier(item, "drawable", getActivity().getPackageName());
String amount = line.getString("amount");
Log.e(TAG, "DAIKTAS: " + item);
Log.e(TAG, "KIEKIS: " + amount);
HashMap<String, String> contact = new HashMap<>();
String itembank = item.replaceAll("i_", "");
String itembanks = itembank.replaceAll("_", " ");
contact.put("name", itembanks);
contact.put("email", amount);
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.list_item, null);
// lv = view.findViewById(R.id.list);
// iv = (ImageView) view.findViewById(R.id.logo);
final ImageView ims = (ImageView) view.findViewById(R.id.logo);
handler.post(new Runnable() {
public void run() {
if(image != null) {
if(image == 0) {
ims.setImageResource(R.drawable.i_noted);
Log.e(TAG, "rokas?: " + image);
} else {
Log.e(TAG, "drawable ID ID: " + image);
ims.setImageResource(image);
}
} else {
Log.e(TAG, "null?: " + image);
}
}
});
ItemList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
};
}
} else {
Log.e(TAG, "Couldn't get json from server.");
new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(),
"Couldn't get json from server!",
Toast.LENGTH_LONG).show();
}
};
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(getContext(), ItemList,
R.layout.list_item, new String[]{ "email","name"},
new int[]{R.id.email, R.id.name});
lv.setAdapter(adapter);
}
}
}
Logcat keeps messaging me this:
02-08 14:11:12.331 17584-17584/com.infonuascape.osrshelper W/Resources: Converting to string: TypedValue{t=0x5/d=0x601 a=1 r=0x10500d7}
You should choose right setter:
imageView.setImageDrawable(drawable) - to set drawable which you can get from
resources using getResource().getDrawable(R.drawable.drawable_id).
imageView.setImageResource(id) - to set image using resources id.
imageView.setImageBitmap(bitmap) - to set bitmap which you can create from drawable using:Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.drawable_id).
And if you are using getResources().getIdentifier(...); I offer you to use:
int imageResource = getResources().getIdentifier(item, "drawable", getActivity().getPackageName());
imageview= (ImageView)findViewById(R.id.imageView);
Drawable drawable = getResources().getDrawable(imageResource);
imageView.setImageDrawable(drawable );
Something like this...
I've done a search on another stackoverflow post for 2 hours but still can not solve this problem. I have a variable called copyAudioListIqro with List String datatype in DetailMemilihIqro Activity class. When the variable called audioIqros in the AsyncTask class (precisely in the onPostExecute method) this list has a value from my json and I want to copy audioIqros variable to copyAudioListIqro via updateData method (outside the asynctask class). When I see the log monitor on updateData method I can see the value from copyAudioListIqro, but the problem is, when I access it via readDataAudioURL method(outside the asynctask class) copyAudioListIqro variable becomes null.
What is the solution for this problem?
Thank you
Here is the overall DetailMemilihIqro class
public class DetailMemilhIqro extends AppCompatActivity {
private ProgressDialog pDialog;
private List<ModelAudioIqro> audioIqros;
private List<String> copyAudioListIqro;
private AudioAdapter mAdapter;
private RecyclerView recyclerView;
private String TAG = DetailMemilihIqro.class.getSimpleName();
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_memilih_iqro);
recyclerView = (RecyclerView) findViewById(R.id.rvCVAudioIqro);
pDialog = new ProgressDialog(this);
audioIqros = new ArrayList<>();
mAdapter = new AudioAdapter(getApplicationContext(), audioIqros);
context = getApplicationContext();
copyAudioListIqro = new ArrayList<>();
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
Bundle getPosition = getIntent().getExtras();
int position = getPosition.getInt("positionUserClicked");
Log.d(TAG, "Position User clicked " + position);
if (position == 0) {
String endpoint = "http://latihcoding.com/jsonfile/audioiqro1.json";
new DownloadTask().execute(endpoint);
} else if (position == 1) {
String endpoint = "http://latihcoding.com/jsonfile/audioiqro2.json";
new DownloadTask().execute(endpoint);
} else if (position == 2) {
String endpoint = "http://latihcoding.com/jsonfile/audioiqro3.json";
new DownloadTask().execute(endpoint);
}
readDataAudioURL();
}
public void updateData(List<String> pathUrl) {
for (int i = 0; i < pathUrl.size(); i++) copyAudioListIqro.add(pathUrl.get(i));
Log.d(TAG, "updateData Method " + copyAudioListIqro.toString());
}
public void readDataAudioURL() {
Log.d(TAG, "readDataAudioURL Method " + copyAudioListIqro.toString());
}
public class DownloadTask extends AsyncTask<String, Void, List<String>> {
List<String> modelAudioIqroList;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Downloading json...");
pDialog.show();
}
#Override
protected List<String> doInBackground(String... strings) {
modelAudioIqroList = new ArrayList<>();
int result;
HttpURLConnection urlConnection;
try {
URL url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
// 200 represents HTTP OK
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
Log.d(TAG, "Result " + result);
} else {
//"Failed to fetch data!";
result = 0;
Log.d(TAG, "Result " + result);
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return modelAudioIqroList; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(List<String> audioIqros) {
super.onPostExecute(audioIqros);
pDialog.hide();
if (!audioIqros.isEmpty()) {
updateData(modelAudioIqroList);
} else {
Toast.makeText(context, "Empty", Toast.LENGTH_SHORT).show();
}
}
private void parseResult(String result) {
try {
JSONArray response = new JSONArray(result);
for (int i = 0; i < response.length(); i++) {
JSONObject object = response.getJSONObject(i);
ModelAudioIqro modelAudioIqro = new ModelAudioIqro();
modelAudioIqro.setName(object.getString("name"));
modelAudioIqro.setUrl(object.getString("url"));
String path = modelAudioIqro.getUrl();
Log.d(TAG, "String path " + path);
modelAudioIqroList.add(path);
}
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter.notifyDataSetChanged();
}
}
}
Log for the copyAudioListIqro in the updateDataMethod
Log for the copyAudioListIqro in the readDataAudioURL
readDataAudioURL() call, that is a plain Log call, should be moved. Infact the task is asynch by nature, so oblivously the variable copyAudioListIqro won't have been initialized right after the task's start (.execute() method).
You're doing right, anyway, in notyfiying dataset change to list...You should just move it to postExecute as well...
I suggest to move all "after network" code to that postExecute, so that UI can be updated asynchronously ONLY when data is available and without blocking main thread. You can 'read' variables in the inner class, so just declare them final:
#Override
protected void onPostExecute(List<String> audioIqros) {
super.onPostExecute(audioIqros);
pDialog.hide();
if (!audioIqros.isEmpty()) {
updateData(modelAudioIqroList);
//data is now updated, notify datasets and/or send broadcast
mAdapter.notifyDataSetChanged();
readDataAudioURL();
} else {
Toast.makeText(context, "Empty", Toast.LENGTH_SHORT).show();
}
}
A more elaborate pattern would include broadcast receiver and intents, but I guess this is out of this question's scope.
I want to show progress bar with percentage of the download the data from json. Right now I am getting the data from the url and store in the local database in other class and this class called in MainActivity. Now I want to show the progressbar with percentage of the download file from json url.
This is my code
public class Web_Product {
Context context;
List<Variable> list = new ArrayList<Variable>();
//List<Variable> list1;
String url = "https://api.androidhive.info/progressdialog/hive.jpg";
URL url1 = null;
InputStream is1 = null;
String product_id, product_name, product_image;
private byte[] logoImage;
private JSONArray jsonArray;
public Web_Product(Context context) {
this.context = context;
Log.e("hello", "Message");
}
public void product_insert() {
// new AsyncLogin().execute();
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.e("TEST", "jsonStr:-" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonRootObject = new JSONObject(jsonStr);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("product");
//Iterate the jsonArray and print the info of JSONObjects
for (int i = 0; i < jsonArray.length(); i++) {
Log.e("TEST_P", "in");
JSONObject details = jsonArray.getJSONObject(i);
product_id = details.getString("product_id");
product_name = details.getString("product_name");
product_image = details.getString("product_image");
logoImage = getLogoImage(product_image);
Variable variable_object = new Variable();
variable_object.setProduct_id(product_id);
variable_object.setProduct_name(product_name);
variable_object.setProduct_url_image(logoImage);
list.add(variable_object);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
Log.e("TEST1", " Ritunjay" + list.size());
Product_data product = new Product_data(context);
product.Insert_Product(list);
Log.e("listpo", "" + list);
}
public JSONArray json_web_prod() {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.e("TEST", "jsonStr:-" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonRootObject = new JSONObject(jsonStr);
//Get the instance of JSONArray that contains JSONObjects
jsonArray = jsonRootObject.optJSONArray("product");
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray;
}`
Main Activity
class add extends AsyncTask<String, Integer, String> {
ProgressDialog mProgressDialog;
#Override
protected void onProgressUpdate(Integer... values) {
mProgressDialog.setProgress(values[0]);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("Downloading Data...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
mProgressDialog.dismiss();
flag = true;
Intent intent = getIntent();
startActivity(intent);
finish();
Log.e("flag , post", "" + flag);
}
#Override
protected String doInBackground(String... params) {
web_product = new Web_Product(getApplicationContext());
web_product.product_insert();
return null;
}
}`
In doInBackground , you need to publishProgress also . So that your progress bar can updated , like this
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
Here totalSize will help you to calculate your total remaining data and publishProgress will public it .
I'm having trouble using the value of a variable in a local class and passing it to another class that will be loaded in the intent.
The string value is null and gives an error in the application.
public class Carro extends AppCompatActivity {
ListView lvCarrinhoItems;
Button bFinalizar;
String url2 = "";
String parametros2 = "";
String insertUrl = "http://localhost/registrar.php";
RequestQueue requestQueue;
String result = "";
public static String idOrder = "", dta = "";
public static MeuPedido meuPedido;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shopping_carrinho);
lvCarrinhoItems = (ListView) findViewById(R.id.tela5lv);
LayoutInflater layoutInflater = getLayoutInflater();
final Carrinhos carrinhos = CarrinhoHelper.getCarrinhos();
final TextView tvTotalPrice = (TextView) findViewById(R.id.tvsoma);
final TextView tvObspedido = (TextView) findViewById(R.id.etobscar);
tvTotalPrice.setText((Bandeja.MOEDA+String.valueOf(carrinhos.getTotalPrice().setScale(2, BigDecimal.ROUND_HALF_UP))).replace(".",","));
final TCartItemAdapter tcartItemAdapter = new TCartItemAdapter(this);
tcartItemAdapter.updateCartItems(getCarrinhoItems(carrinhos));
lvCarrinhoItems.setAdapter(tcartItemAdapter);
bFinalizar = (Button) findViewById(R.id.button4);
bFinalizar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alerta = new AlertDialog.Builder(Carro.this);
alerta.setTitle("Confirmação de pedido");
alerta
.setIcon(R.drawable.service)
.setMessage("Deseja confirmar o seu pedido?")
.setCancelable(false)
.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
requestQueue = Volley.newRequestQueue(getApplicationContext());
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
pref = getSharedPreferences("login.conf", Context.MODE_PRIVATE);
final String idcliente = pref.getString("idusuario", null);
final String idrestaurante = CarrinhoHelper.getIdResta();
final String valorpedido = String.valueOf(carrinhos.getTotalPrice());
final String obspedido = tvObspedido.getText().toString();
if (idcliente == null){
Intent intent = new Intent(Carro.this, A2_1semlogin.class);
startActivity(intent);
}else
if (networkInfo != null && networkInfo.isConnected()) {
url2 = "http://localhost/registrarpedido.php";
parametros2 = "idcliente=" + idcliente + "&idrestaurante=" + idrestaurante + "&valorpedido=" + valorpedido + "&obspedido=" + obspedido;
new SolicitaDados2().execute(url2);
} else {
Toast.makeText(getApplicationContext(), "Por favor, verifique sua conexão", Toast.LENGTH_LONG).show();
}
Log.d("DadosRet2", parametros2);
Log.d("DadosRet2", idcliente + ", " + idrestaurante + ", " + valorpedido + ", " + obspedido);
class MyAsyncTaskresources extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
InputStream isr = null;
try{
String URL=params[0];
java.net.URL url = new URL( URL);
URLConnection urlConnection = url.openConnection();
isr = new BufferedInputStream(urlConnection.getInputStream());
}
catch(Exception e){
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
String s = "";
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
final JSONObject json = jArray.getJSONObject(i);
s = s + "login info : " + json.getString("idOrder") + " " + json.getString("idcliente") + " " + json.getString("idrestaurante") + " " + json.getString("data");
**STRING QUE DESEJO ACESSAR = idOrder**
idOrder = json.getString("idOrder");
dta = json.getString("data");
List<CarrinhoItem> carrinhoItems = new ArrayList<CarrinhoItem>();
Log.d(TAG, "Current shopping cart: " + carrinhos);
Map<TSaleable, Integer> itemMap = carrinhos.getItemWithQuantity();
for (Map.Entry<TSaleable, Integer> entry : itemMap.entrySet()) {
final CarrinhoItem carrinhoItem = new CarrinhoItem();
carrinhoItem.setBandeja((Bandeja) entry.getKey());
carrinhoItem.setQuantidade(entry.getValue());
carrinhoItems.add(carrinhoItem);
final String idcomida = carrinhoItem.getBandeja().getIdcomida();
final String quantidade = carrinhoItem.getBandeja().getQuantidade();
final BigDecimal valorunit = carrinhoItem.getBandeja().getPreco();
final String adicional = carrinhoItem.getBandeja().getAdicional();
final String obsproduto = carrinhoItem.getBandeja().getObsproduto();
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("idOrder",idOrder);
parameters.put("idcomida", idcomida);
parameters.put("quantidade", quantidade);
parameters.put("valorunit", valorunit.toString());
parameters.put("adicional", adicional);
parameters.put("obsproduto", obsproduto);
final MeuPedido meupedido = new MeuPedido();
String novaId = idOrder;
meupedido.setmPedido(novaId);
return parameters;
}
};
requestQueue.add(request);
}
break;
}
}
catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}
}
new MyAsyncTaskresources().execute("http://localhost/sel.php?idcliente="+idcliente+"&idrestaurante=" +idrestaurante);
}
});
AlertDialog alertaDialog = alerta.create();
alertaDialog.show();
}
});
}
public static final List<CarrinhoItem> getCarrinhoItems(Carrinhos carrinhos) {
List<CarrinhoItem> carrinhoItems = new ArrayList<CarrinhoItem>();
Log.d(TAG, "Current shopping cart: " + carrinhos);
Map<TSaleable, Integer> itemMap = carrinhos.getItemWithQuantity();
for (Map.Entry<TSaleable, Integer> entry : itemMap.entrySet()) {
final CarrinhoItem carrinhoItem = new CarrinhoItem();
carrinhoItem.setBandeja((Bandeja) entry.getKey());
carrinhoItem.setQuantidade(entry.getValue());
carrinhoItems.add(carrinhoItem);
final String comida = carrinhoItem.getBandeja().getComida();
final String adicional = carrinhoItem.getBandeja().getAdicional();
final String quantidade = carrinhoItem.getBandeja().getQuantidade();
final BigDecimal valor = carrinhoItem.getBandeja().getPreco();
}
return carrinhoItems;
}
private class SolicitaDados2 extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return Conexao.postDados(urls[0], parametros2);
}
#Override
protected void onPostExecute(String resultado) {
if (resultado.contains("pedido_ok")) {
Toast.makeText(getApplicationContext(), "Registro efetuado com sucesso", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Carro.this, Anotafiscal.class);
** LOCAL ONDE DESEJO INSERIR A STRING**
String hjhj = idOrder ;
intent.putExtra("iddopedido",hjhj);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), "Ocorreu um erro no cadastro", Toast.LENGTH_LONG).show();
}
}
}
}