PLEASE HELP, WHAT IS WRONG WITH MY CODE, IT DISPLAYS NOTHING BUT ZEROS AND NULL
I already search through tutorials, i even copied the whole code but i cant get the data from this API, my textviews on int are returning zeros and my textviews on string are returning null after a press the update button.
here is my api link = api link
here is the result
package com.example.firstapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private TextView confirmed, recovered, deaths, country, date;
private RequestQueue mQueue;
private Button update;
private int c,r,d;
private String co,da;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
confirmed = findViewById(R.id.confirmed);
recovered = findViewById(R.id.recovered);
deaths = findViewById(R.id.deaths);
country = findViewById(R.id.country);
date = findViewById(R.id.date);
update = findViewById(R.id.update);
mQueue = Volley.newRequestQueue(this);
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
confirmed.setText(String.valueOf(c));
recovered.setText(String.valueOf(r));
deaths.setText(String.valueOf(d));
country.setText(co);
date.setText(da);
}
});
}
private void jsonParse(){
String url = "https://covid-api.mmediagroup.fr/v1/cases?country=Philippines";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("All");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject cases = jsonArray.getJSONObject(i);
c = cases.getInt("confirmed");
r = cases.getInt("recovered");
d = cases.getInt("deaths");
co = cases.getString("country");
da = cases.getString("updated");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(),
Toast.LENGTH_LONG).show();
}
});
mQueue.add(request);
}
}
I don't know what is the problem here, can someone help
I already fixed it thank you so much.
my solution is I removed JsonArray.
package com.example.firstapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private TextView confirmed, recovered, deaths, country, date;
private RequestQueue mQueue;
private Button update;
private int c,r,d;
private String co,da;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
confirmed = findViewById(R.id.confirmed);
recovered = findViewById(R.id.recovered);
deaths = findViewById(R.id.deaths);
country = findViewById(R.id.country);
date = findViewById(R.id.date);
update = findViewById(R.id.update);
mQueue = Volley.newRequestQueue(this);
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
}
});
}
private void jsonParse(){
String url = "https://covid-api.mmediagroup.fr/v1/cases?country=Philippines";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
//JSONArray jsonArray = response.getJSONArray();
for (int i = 0; i < response.length(); i++) {
JSONObject cases = response.getJSONObject("All");
c = cases.getInt("confirmed");
r = cases.getInt("recovered");
d = cases.getInt("deaths");
co = cases.getString("country");
da = cases.getString("updated");
confirmed.setText(String.valueOf(c));
recovered.setText(String.valueOf(r));
deaths.setText(String.valueOf(d));
country.setText(co);
date.setText(da);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(),
Toast.LENGTH_LONG).show();
}
});
mQueue.add(request);
}
}
I replaced
JSONObject cases = jsonArray.getJSONObject(i);
with
JSONObject cases = response.getJSONObject("All");
and removed
JSONArray jsonArray = response.getJSONArray();
because it is not necessary.
Related
I am trying to use if else in a spinner layout in android. But the if condition is never accepted with a given condition.
Id of spinner is stateView.
stateView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
State = String.valueOf(stateView.getSelectedItem());
try {
if(obj.getString("state").equals(State)){
Log.d("error",State);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
The same code works everywhere else in the block.
I assume the problem is in
if(obj.getString("state").equals(State))
If it is used if(true) the block works correctly, that means code is reaching there but there is a problem in the condition applied int the if statement.
even the below code is not working
if(obj.getString("state").equals("Delhi"))
this code is working outside the listener
private void stateData(final String stateName, final String cityName) {
final RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, arrayResponse -> {
try {
for (int i = 0; i < arrayResponse.length(); i++) {
JSONObject obj = arrayResponse.getJSONObject(i);
if (obj.getString("state").equals(stateName)){
Log.d("error","working");
}
The whole code for reference
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.VoiceInteractor;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
TextView stateActiveCases, stateConfirmed, stateDeceased, stateRecovered, cChanges, rChanges, dChanges;
String State;
Spinner stateView;
FusedLocationProviderClient fusedLocationProviderClient;
RecyclerView recyclerView;
RecyclerView.Adapter<DistrictAdapter.ViewHolder> mAdapter;
RecyclerView.LayoutManager layoutManager;
List<Districts> districtsList;
ArrayList<String> States;
#SuppressLint("SourceLockedOrientationActivity")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.list);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
districtsList = new ArrayList<>();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
final TextView Total = findViewById(R.id.textView4);
final TextView Recovered = findViewById(R.id.textView5);
final TextView Death = findViewById(R.id.textView6);
final TextView TodayCases = findViewById(R.id.textView7);
final TextView TodayDeath = findViewById(R.id.textView8);
final TextView ActiveCases = findViewById(R.id.textView10);
stateActiveCases = findViewById(R.id.textView29);
stateView = findViewById(R.id.spinner);
stateConfirmed = findViewById(R.id.textView26);
stateRecovered = findViewById(R.id.textView27);
stateDeceased = findViewById(R.id.textView28);
cChanges = findViewById(R.id.textView14);
rChanges = findViewById(R.id.textView15);
dChanges = findViewById(R.id.textView16);
States = new ArrayList<>();
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "https://coronavirus-19-api.herokuapp.com/countries/india", null, objectResponse -> {
try {
int cases = objectResponse.getInt("cases");
int recovered = objectResponse.getInt("recovered");
int deaths = objectResponse.getInt("deaths");
int todayCases = objectResponse.getInt("todayCases");
int todayDeaths = objectResponse.getInt("todayDeaths");
int activeCases = objectResponse.getInt("active");
Total.setText(String.valueOf(cases));
Death.setText(String.valueOf(deaths));
Recovered.setText(String.valueOf(recovered));
String tc = ("+" + todayCases);
String td = ("+" + todayDeaths);
TodayCases.setText(tc);
TodayDeath.setText(td);
ActiveCases.setText(String.valueOf(activeCases));
} catch (JSONException ex) {
ex.printStackTrace();
}
}, error -> Log.d("error", "something fishy " + error));
requestQueue.add(jsonObjectRequest);
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 2199);
} else {
getLocation();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 2199) {
getLocation();
}
}
private void getLocation() {
fusedLocationProviderClient.getLastLocation().addOnCompleteListener(task -> {
Location location = task.getResult();
if (location != null) {
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1
);
stateData(addresses.get(0).getAdminArea(), addresses.get(0).getLocality());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void stateData(final String stateName, final String cityName) {
final RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, "https://api.covidindiatracker.com/state_data.json", null, arrayResponse -> {
try {
for (int i = 0; i < arrayResponse.length(); i++) {
JSONObject obj = arrayResponse.getJSONObject(i);
if (obj.getString("state").equals(stateName)) {
stateActiveCases.setText(String.valueOf(obj.getInt("active")));
stateConfirmed.setText(String.valueOf(obj.getInt("confirmed")));
stateRecovered.setText(String.valueOf(obj.getInt("recovered")));
stateDeceased.setText((String.valueOf(obj.getInt("deaths"))));
String stateCChanges, stateRChanges, stateDChanges;
stateCChanges = "+" + obj.getInt("cChanges");
stateRChanges = "+" + obj.getInt("rChanges");
stateDChanges = "+" + obj.getInt("dChanges");
cChanges.setText(stateCChanges);
rChanges.setText(stateRChanges);
dChanges.setText(stateDChanges);
JSONArray array = obj.getJSONArray("districtData");
for (int j = 0; j < array.length(); j++) {
Districts districts = new Districts();
JSONObject obj1 = array.getJSONObject(j);
if (obj1.getString("name").equals(cityName)) {
districts.setName(obj1.getString("name"));
districts.setConfirmed((obj1.getInt("confirmed")));
districtsList.add(districts);
}
}
for (int k = 0; k < array.length(); k++) {
Districts districts = new Districts();
JSONObject obj1 = array.getJSONObject(k);
if (obj1.getString("name").equals(cityName)) {
continue;
}
districts.setName(obj1.getString("name"));
districts.setConfirmed(obj1.getInt("confirmed"));
districtsList.add(districts);
}
}
String state=obj.getString("state");
States.add(state);
stateView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
State = String.valueOf(stateView.getSelectedItem());
((TextView )parent.getChildAt(0)).setTextColor(ContextCompat.getColor(getApplicationContext(),R.color.colorAccent));
((TextView)parent.getChildAt(0)).setTextSize(16);
try {
if(obj.getString("state").equals(State)){
Log.d("error",State);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, States);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
stateView.setAdapter(arrayAdapter);
int spinner = arrayAdapter.getPosition(stateName);
stateView.setSelection(spinner);
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter = new DistrictAdapter(districtsList);
recyclerView.setAdapter(mAdapter);
}, error -> Log.d("error", "something fishy " + error));
requestQueue.add(jsonArrayRequest);
}
}
I want to move the if statement inside the listener such that when I select a state the data for that state is displayed. right now I am getting state data from the parameter which fetches data from GPS location.
Check the whole project on
Github
Any other suggestions are welcome.
Thanks in advance.
I am trying to parse data from json using an API, but I don't know for what reasons when I am calculating the size of m_name3 it is showing 0 but the data is being parsed through the file. When putting toast at String name = o.getString("name"); it is showing the content of name string, so this means it is parsing the data but not storing in arraylist. I don't know why. Please help!
package com.example.amitc.pvrathome;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import okhttp3.OkHttpClient;
public class msms extends AppCompatActivity {
String img_src;
private ArrayList<String> m_name3 = new ArrayList<>();
private ArrayList<String> m_release_year3 = new ArrayList<>();
private ArrayList<String> m_genre3 = new ArrayList<>();
private ArrayList<String> m_director3 = new ArrayList<>();
private ArrayList<String> m_rating3 = new ArrayList<>();
private ArrayList<String> m_actor3 = new ArrayList<>();
private ArrayList<String> m_desc3 = new ArrayList<>();
private ArrayList<String> m_imgsrc3 = new ArrayList<>();
StringRequest stringRequest;
Context mContext;
String url_all = "https://www.dropbox.com/s/ofzv2j16vq9ofmq/100MovieList.json?dl=1";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.msms);
new getIncomingIntent().execute();
ImageView imageView = findViewById(R.id.msms_image);
mContext = this;
Glide.with(this)
.load(img_src)
.apply(new RequestOptions()
.placeholder(R.drawable.rec)
.dontAnimate()
.error(R.drawable.movies))
.into(imageView);
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//txt.setText("Searching by: "+ query);
} else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
String uri = intent.getDataString();
final int index = Integer.parseInt(uri.replaceAll("[^0-9]", ""));
//
stringRequest = new StringRequest(Request.Method.GET,
url_all,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("movies");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
String name = o.getString("name");
String year = o.getString("year");
String genre = o.getString("genre");
String rating = o.getString("rating");
String director = o.getString("directors_name");
String actor = o.getString("cast");
String img_src = o.getString("poster_src");
String desc = o.getString("description");
m_name3.add(name);
m_release_year3.add(year);
m_genre3.add(genre);
m_rating3.add(rating);
m_director3.add(director);
m_actor3.add(actor);
m_imgsrc3.add(img_src);
m_desc3.add(desc);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Some error Occured", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(msms.this);
requestQueue.add(stringRequest);
Toast.makeText(this, "Index: "+ m_name3.size(), Toast.LENGTH_SHORT).show();
// TextView m_name = findViewById(R.id.msms_name);
// m_name.setText(m_name3.get(index));
//
// TextView m_name1 = findViewById(R.id.msms_name1);
// m_name1.setText(m_name3.get(index));
// // TextView m_year = (TextView) findViewById(R.id.msms_year);
// // m_year.setText(year);
//
// TextView m_genre = findViewById(R.id.msms_genre);
// m_genre.setText(m_genre3.get(index));
//
// TextView m_rating = findViewById(R.id.msms_rating);
// m_rating.setText(m_rating3.get(index));
//
// TextView m_desc = findViewById(R.id.msms_desc);
// m_desc.setText(m_desc3.get(index));
//
// TextView m_direc = findViewById(R.id.msms_direc);
// m_direc.setText(m_director3.get(index));
//
// TextView m_actor = findViewById(R.id.msms_actor);
// m_actor.setText(m_actor3.get(index));
// Glide.with(this)
// .load(img_src)
// .apply(new RequestOptions()
// .placeholder(R.drawable.rec)
// .dontAnimate()
// .error(R.drawable.movies))
// .into(imageView);
}
}
public class getIncomingIntent extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
String name = getIntent().getStringExtra("names");
// String year = getIntent().getStringExtra("years");
String genre = getIntent().getStringExtra("genres");
String rating = getIntent().getStringExtra("ratings");
String desc = getIntent().getStringExtra("decss");
String director = getIntent().getStringExtra("direcs");
String actor = getIntent().getStringExtra("stars");
img_src = getIntent().getStringExtra("img1");
TextView m_name = (TextView) findViewById(R.id.msms_name);
m_name.setText(name);
TextView m_name1 = (TextView) findViewById(R.id.msms_name1);
m_name1.setText(name);
// TextView m_year = (TextView) findViewById(R.id.msms_year);
// m_year.setText(year);
TextView m_genre = (TextView) findViewById(R.id.msms_genre);
m_genre.setText(genre);
TextView m_rating = (TextView) findViewById(R.id.msms_rating);
m_rating.setText(rating);
TextView m_desc = (TextView) findViewById(R.id.msms_desc);
m_desc.setText(desc);
TextView m_direc = (TextView) findViewById(R.id.msms_direc);
m_direc.setText(director);
TextView m_actor = (TextView) findViewById(R.id.msms_actor);
m_actor.setText(actor);
return null;
}
}
}
EDITED:
package com.example.amitc.pvrathome;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import okhttp3.OkHttpClient;
public class msms extends AppCompatActivity {
String img_src;
private ArrayList<String> m_name3 = new ArrayList<>();
private ArrayList<String> m_release_year3 = new ArrayList<>();
private ArrayList<String> m_genre3 = new ArrayList<>();
private ArrayList<String> m_director3 = new ArrayList<>();
private ArrayList<String> m_rating3 = new ArrayList<>();
private ArrayList<String> m_actor3 = new ArrayList<>();
private ArrayList<String> m_desc3 = new ArrayList<>();
private ArrayList<String> m_imgsrc3 = new ArrayList<>();
StringRequest stringRequest;
Context mContext;
String url_all = "https://www.dropbox.com/s/ofzv2j16vq9ofmq/100MovieList.json?dl=1";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.msms);
new getIncomingIntent().execute();
ImageView imageView = findViewById(R.id.msms_image);
mContext = this;
Glide.with(this)
.load(img_src)
.apply(new RequestOptions()
.placeholder(R.drawable.rec)
.dontAnimate()
.error(R.drawable.movies))
.into(imageView);
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//txt.setText("Searching by: "+ query);
} else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
String uri = intent.getDataString();
final int index = Integer.parseInt(uri.replaceAll("[^0-9]", ""));
//
stringRequest = new StringRequest(Request.Method.GET,
url_all,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("movies");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
String name = o.getString("name");
String year = o.getString("year");
String genre = o.getString("genre");
String rating = o.getString("rating");
String director = o.getString("directors_name");
String actor = o.getString("cast");
String img_src = o.getString("poster_src");
String desc = o.getString("description");
m_name3.add(name);
m_release_year3.add(year);
m_genre3.add(genre);
m_rating3.add(rating);
m_director3.add(director);
m_actor3.add(actor);
m_imgsrc3.add(img_src);
m_desc3.add(desc);
}
ProgressDialog progress;
progress= new ProgressDialog(mContext);
progress.setMessage("Loading...");
progress.show();
TextView m_name = findViewById(R.id.msms_name);
m_name.setText(m_name3.get(index));
TextView m_name1 = findViewById(R.id.msms_name1);
m_name1.setText(m_name3.get(index));
// TextView m_year = (TextView) findViewById(R.id.msms_year);
// m_year.setText(year);
TextView m_genre = findViewById(R.id.msms_genre);
m_genre.setText(m_genre3.get(index));
TextView m_rating = findViewById(R.id.msms_rating);
m_rating.setText(m_rating3.get(index));
TextView m_desc = findViewById(R.id.msms_desc);
m_desc.setText(m_desc3.get(index));
TextView m_direc = findViewById(R.id.msms_direc);
m_direc.setText(m_director3.get(index));
TextView m_actor = findViewById(R.id.msms_actor);
m_actor.setText(m_actor3.get(index));
ImageView imageView = findViewById(R.id.msms_image);
Glide.with(getApplicationContext())
.load(img_src)
.apply(new RequestOptions()
.placeholder(R.drawable.rec)
.dontAnimate()
.error(R.drawable.movies))
.into(imageView);
progress.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Some error Occured", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(msms.this);
requestQueue.add(stringRequest);
}
}
public class getIncomingIntent extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
String name = getIntent().getStringExtra("names");
// String year = getIntent().getStringExtra("years");
String genre = getIntent().getStringExtra("genres");
String rating = getIntent().getStringExtra("ratings");
String desc = getIntent().getStringExtra("decss");
String director = getIntent().getStringExtra("direcs");
String actor = getIntent().getStringExtra("stars");
img_src = getIntent().getStringExtra("img1");
TextView m_name = (TextView) findViewById(R.id.msms_name);
m_name.setText(name);
TextView m_name1 = (TextView) findViewById(R.id.msms_name1);
m_name1.setText(name);
// TextView m_year = (TextView) findViewById(R.id.msms_year);
// m_year.setText(year);
TextView m_genre = (TextView) findViewById(R.id.msms_genre);
m_genre.setText(genre);
TextView m_rating = (TextView) findViewById(R.id.msms_rating);
m_rating.setText(rating);
TextView m_desc = (TextView) findViewById(R.id.msms_desc);
m_desc.setText(desc);
TextView m_direc = (TextView) findViewById(R.id.msms_direc);
m_direc.setText(director);
TextView m_actor = (TextView) findViewById(R.id.msms_actor);
m_actor.setText(actor);
return null;
}
}
}
Since your stringRequest runs on a different thread, you can't be sure if you already have the response by the time you are showing the toast, so you should have a look at the size only after you have the response.
In short, move the toast inside of onResponse:
stringRequest = new StringRequest(Request.Method.GET,
url_all,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("movies");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
String name = o.getString("name");
String year = o.getString("year");
String genre = o.getString("genre");
String rating = o.getString("rating");
String director = o.getString("directors_name");
String actor = o.getString("cast");
String img_src = o.getString("poster_src");
String desc = o.getString("description");
m_name3.add(name);
m_release_year3.add(year);
m_genre3.add(genre);
m_rating3.add(rating);
m_director3.add(director);
m_actor3.add(actor);
m_imgsrc3.add(img_src);
m_desc3.add(desc);
}
Toast.makeText(msms.this, "Index: "+ m_name3.size(), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Some error Occured", Toast.LENGTH_SHORT).show();
}
});
When tapping an image (from a previous activity) I get to this activity (where I pass the clientid) that reads a JSONArray and use a setter to set the nick.
I then use a getter to do a textview setText.
The problem is that the first time no nick is set. When I go back to the previous activity and tap the same image again, only then the nick is set.
Why isn't the nick displayed from the first time.
(ps: I'm quite new to Java/Android Studio)
package com.smartvibes.smartbeat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class profileViewActivity extends AppCompatActivity {
RequestQueue rs;
String url, id, nick, age, city, mainpic, numpics, extrapic0, extrapic1, extrapic2, extrapic3, extrapic4, extrapic5;
TextView profileIntro;
static String pnick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_view);
Bundle getProfileId = getIntent().getExtras();
if (getProfileId == null) {
return;
}
String profileid = getProfileId.getString("profileid");
url = "https://www.smartvibes.be/profiles/api/profileview.php?id=" + profileid;
rs = Volley.newRequestQueue(this);
sendjsonrequest();
profileIntro = (TextView) findViewById(R.id.profileIntro);
profileIntro.setText(getPnick());
}
public void sendjsonrequest() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
setPnick(response.getString("nick"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
rs.add(jsonObjectRequest);
}
public static void setPnick(String nick) {
pnick = nick;
}
public static String getPnick(){
return pnick;
}
}
Because sendjsonrequest is an async call
You need to update textView in onResponse Method itself, like below
setPnick(response.getString("nick"));
profileIntro.setText(getPnick());
I have one method with this url:
String url = "http://brunos.000webhostapp.com/teste/obter_id.php?descricao=" + value;
And i want to return the result of this method.
i have tried the VolleyCallback callback but i cant send the value to the method
package com.example.fabio.domoticaa;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Divi_Dispo extends AppCompatActivity {
String x;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_divi__dispo);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final String[] count = new String[1];
final String[] id = new String[1];
Intent intent = getIntent();
String value = intent.getStringExtra("divisao");
final EditText nomediv = (EditText) findViewById(R.id.editText4);
Count(value);
nomediv.setText(x);//want set th result of Count(value)
}
public void Count(String value) {
final String[] count = new String[1];
// Send data
try {
RequestQueue queue = Volley.newRequestQueue(Divi_Dispo.this);
String url = "http://brunos.000webhostapp.com/teste/obter_id.php?descricao=" + value ;
JsonArrayRequest jsonRequest = new JsonArrayRequest
(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONObject jObj = new JSONObject(String.valueOf(response.get(0)));
count[0] = jObj.getString("COUNT(id)");//want return this valor
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonRequest);
} catch (Exception ex) {
} finally {
}
}
public interface VolleyCallback {
void onSuccess(String result);
}
}
I have a problem about uploading images from android to a server, the problem is about the android version, my application can run on android version 2.3 but can not run on version > 2.3. these is my code
function TambahLokasi()
{
$base = $_REQUEST["gambar"];
if (isset($base)){
$suffix = createRandomID();
$image_name = "img_".$suffix."_".date("Y-m-d-H-m-s").".jpg";
$binary = base64_decode($base);
header("Content-Type: bitmap; charset=utf-8");
$file = fopen("gambar/" . $image_name, "wb");
fwrite($file, $binary);
fclose($file);
$username = $_POST['USERNAME'];
$loc_name = $_POST['LOCATION_NAME'];
$category = $_POST['CATEGORY'];
$address = $_POST['ADDRESS'];
$city = $_POST['CITY'];
$descript = $_POST['DESCRIPTION'];
$own = $_POST['OWNER'];
$lat = $_POST['lat'];
$lng = $_POST['lng'];
$query = "insert into location (USERNAME,LOCATION_NAME,CATEGORY,ADDRESS,CITY,DESCRIPTION,OWNER,lat,lng,gambar)values ('$username', '$loc_name', '$category', '$address','$city','$descript','$own','$lat','$lng','$image_name')";
//$query = "insert into pasien values ('','n', 'n', 'n', 'n','bar','','','n','n','n')";
$hasil = mysql_query($query);
if($hasil)
{
$respon["success"] = "1";
$respon["pesan"] = "Data berhasil diinput";
echo json_encode($respon);
}
else
{
$respon["success"] = "0";
$respon["pesan"] = "Data gagal diinput. Mohon cek kembali.";
echo json_encode($respon);
die($image_name);
}
}else {
die("No POST");
}
}
function createRandomID() {
$chars = "abcdefghijkmnopqrstuvwxyz0123456789?";
//srand((double) microtime() * 1000000);
$i = 0;
$pass = "";
while ($i <= 5) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
and this is java code
package com.adi.lib;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import com.adi.peta.AddLocation;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;
import android.widget.Button;
public class HttpUploader extends AsyncTask<String, Void, String>
{
String ba1;
Base64 base;
ProgressDialog pDialog;
Intent intent;
AddLocation add;
#SuppressWarnings("static-access")
protected String doInBackground(String... path)
{
String output = null;
for(String sdPath : path)
{
Bitmap bmp = BitmapFactory.decodeFile(sdPath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
double width = bmp.getWidth();
double height = bmp.getHeight();
double ratio = 400/width;
int newHeight = (int)(ratio*height);
bmp = Bitmap.createScaledBitmap(bmp, 400, newHeight, true);
bmp.compress(CompressFormat.JPEG, 90, bao);
byte[] ba= bao.toByteArray();
ba1 = base.encodeToString(ba, 0);
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("USERNAME", add.strUsername));
params.add(new BasicNameValuePair("LOCATION_NAME", add.strLocName));
params.add(new BasicNameValuePair("CATEGORY", add.strCategory));
params.add(new BasicNameValuePair("ADDRESS", add.strAddress));
params.add(new BasicNameValuePair("CITY", add.strCity));
params.add(new BasicNameValuePair("DESCRIPTION", add.strDesc));
params.add(new BasicNameValuePair("OWNER", add.strowner));
params.add(new BasicNameValuePair("lat", add.strlat));
params.add(new BasicNameValuePair("lng", add.strLng));
params.add(new BasicNameValuePair("gambar", ba1));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://batiktour.adi-hidayat.com/Android/AddLocation.php");
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
output = EntityUtils.toString(entity);
Log.i("GET RESPONSE--",output);
Log.e("log_tag ******", "good connection");
bmp.recycle();
}
catch (Exception e)
{
Log.e("log_tag ******",
"Error in http connection " + e.toString());
}
}
return output;
}
}
AddLocation.java
package com.adi.peta;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.ErrorManager;
import android.widget.AdapterView.OnItemSelectedListener;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.w3c.dom.Text;
import com.adi.lib.HttpUploader;
import com.adi.lib.JSONParser;
import com.adi.lib.SessionManager;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.R.string;
import android.location.Address;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.widget.AdapterView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class AddLocation extends FragmentActivity implements LocationListener
{
Uri currImageURI;
GoogleMap googlemap;
ProgressDialog pDialog;
SessionManager session;
JSONParser jsonParser = new JSONParser();
EditText loc_name, address, city, desc, owner, latitude, longitude;
Spinner category;
Button submit, browse, gps;
String[] items = { "Tulis", "Cap", "Campuran" };
String id_user, tempcate, email, name, phone;
TextView path,status;
String image_name;
private static String url = "http://batiktour.adi-hidayat.com/Android/AddLocation.php";
public static String strUsername;
public static String strLocName;
public static String strCategory;
public static String strAddress;
public static String strCity;
public static String strDesc;
public static String strowner;
public static String strlat;
public static String strLng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_location);
session = new SessionManager(getApplicationContext());
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG)
.show();
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
name = user.get(SessionManager.KEY_NAME);
email = user.get(SessionManager.KEY_USER);
// phone = user.get(SessionManager.KEY_PHONE);
TextView status = (TextView) findViewById(R.id.status);
status.setText(Html.fromHtml(email));
loc_name = (EditText) findViewById(R.id.locName);
address = (EditText) findViewById(R.id.address);
city = (EditText) findViewById(R.id.city);
desc = (EditText) findViewById(R.id.desc);
owner = (EditText) findViewById(R.id.owner);
latitude = (EditText) findViewById(R.id.tvLAT);
longitude = (EditText) findViewById(R.id.tvLNG);
category = (Spinner) findViewById(R.id.category);
submit = (Button) findViewById(R.id.submit);
browse = (Button) findViewById(R.id.browse);
gps = (Button) findViewById(R.id.ubahGPS);
path = (TextView) findViewById(R.id.path);
category = (Spinner)findViewById(R.id.category);
ArrayAdapter aa = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
category.setAdapter(aa);
category.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
strCategory = items[position];
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapTambah);
googlemap = fm.getMap();
googlemap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
ImageView img = new ImageView(this);
browse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"), 1);
}
});
gps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
double chgLat;
double chgLng;
chgLat = Double.parseDouble(latitude.getText().toString());
chgLng = Double.parseDouble(longitude.getText().toString());
LatLng latlng = new LatLng(chgLat, chgLng);
googlemap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
googlemap.animateCamera(CameraUpdateFactory.zoomTo(15));
googlemap.addMarker(new MarkerOptions()
.position(latlng)
.title("POSISI")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
}
});
googlemap.setOnMapClickListener(new OnMapClickListener()
{
#Override
public void onMapClick(LatLng latlong)
{
double lat = latlong.latitude;
double lng = latlong.longitude;
latitude.setText(String.valueOf(lat));
longitude.setText(String.valueOf(lng));
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latlong);
googlemap.clear();
// Animating to the touched position
googlemap.animateCamera(CameraUpdateFactory.newLatLng(latlong));
// Placing a marker on the touched position
googlemap.addMarker(markerOptions);
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if(loc_name.getText().toString().trim().length()>0 &&
address.getText().toString().trim().length()>0 &&
city.getText().toString().trim().length()>0 &&
owner.getText().toString().trim().length()>0 &&
desc.getText().toString().trim().length()>0 &&
latitude.getText().toString().trim().length()>0 &&
longitude.getText().toString().trim().length()>0
){
if (path.getText().equals("")) {
Toast.makeText(getApplicationContext(),
"Belum Pilih Gambar", Toast.LENGTH_LONG).show();
} else {
String idUser;
session = new SessionManager(getApplicationContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
idUser = user.get(SessionManager.KEY_USER);
strUsername = idUser;
strLocName = loc_name.getText().toString();
strAddress = address.getText().toString();
strCity = city.getText().toString();
strDesc = desc.getText().toString();
strowner = owner.getText().toString();
strlat = latitude.getText().toString();
strLng = longitude.getText().toString();
new AddLoc().execute();
}
}
else
{
Toast.makeText(getApplicationContext(), "Isilah yang kosong", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onLocationChanged(Location location) {
EditText tvLAT = (EditText) findViewById(R.id.tvLAT);
EditText tvLNG = (EditText) findViewById(R.id.tvLNG);
Button gps = (Button) findViewById(R.id.ubahGPS);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googlemap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googlemap.animateCamera(CameraUpdateFactory.zoomTo(15));
googlemap.addMarker(new MarkerOptions().position(latLng)
.title("You're Here"));
tvLAT.setText(String.valueOf(latitude));
tvLNG.setText(String.valueOf(longitude));
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
// currImageURI is the global variable I’m using to hold the
// content:
currImageURI = data.getData();
path.setText(getRealPathFromURI(currImageURI));
}
}
}
// Convert the image URI to the direct file system path of the image file
#SuppressWarnings("deprecation")
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
android.database.Cursor cursor = managedQuery(contentUri, proj,
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
class AddLoc extends AsyncTask<String, String, String> {
String hasil,success;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddLocation.this);
pDialog.setMessage("Menyimpan...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
HttpUploader uploader = new HttpUploader();
try {
image_name = uploader.execute(getRealPathFromURI(currImageURI)).get();
} catch (InterruptedException e) {
Log.e("note1", "upload");
hasil="Interupasi terdapat kesalahan";
Log.e("kesalahan", hasil);
finish();
} catch (ExecutionException e) {
Log.e("note1", "upload2");
hasil="Eksekusi terdapat kesalahan";
Log.e("kesalahan", hasil);
finish();
}
return image_name;
}
protected void onPostExecute(String notifikasi) {
pDialog.dismiss();
Intent dash = new Intent(AddLocation.this,Dashboard.class);
startActivity(dash);
}
}
}
The culprit is most likely related to this line:
image_name = uploader.execute(getRealPathFromURI(currImageURI)).get();
You're firing an AsyncTask from inside another AsyncTask, and the first one blocks until the second is completed. But, from the documentation:
Starting with HONEYCOMB, tasks are executed on a single thread to
avoid common application errors caused by parallel execution.
Since the second task never gets to start (in Android >= 3.0), the first one never gets to finish.
You could fix this by using executeOnExecutor(THREAD_POOL_EXECUTOR)...
... but I would suggest changing your code. Since the first task does nothing (i/o, networking) that would need a background thread, that code can just run in the UI thread. Provide the second (now, only) task with a callback to call in onPostExecute() when it has the result. See android asynctask sending callbacks to ui for a good example of this pattern.
Using get() on AsyncTasks is rarely a good idea.