Hello I'm new at android. There is a arrayList and a ListView. I used AsyncTask class to invoke the database from MYSQL DB. This AsyncTask class sets mArrayList(this is the arrayList). To update the list view when I return from another activity, I used onResume(). This is the part.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mold_breakage_history);
brokenMoldListView = findViewById(R.id.brokenMoldListView);
mArrayList = new ArrayList<>();
GetData task = new GetData();
task.execute("http://www.cafe24.com/aaa.php");
}
#Override
protected void onResume() {
super.onResume();
mArrayList = new ArrayList<>();
GetData task = new GetData();
task.execute("http://www.cafe24.com/aaa.php");
In onResume(), I initialized the mArrayList and invoke AsyncTask again to update ListView. The problem is when this activity was first executed, the ListView was duplicated. But, when I back from next page of this Activity, the problem is disappeared. I hope that this issue is not present when activity is first executed. Please help.
This is code of AsyncTask class.
#SuppressLint("StaticFieldLeak")
private class GetData extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
String errorString = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(MoldBreakageHistoryActivity.this,
"Please Wait", null, true, true);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
Log.d(TAG, "response - " + result);
mJsonString = result;
showResult();
}
#Override
protected String doInBackground(String... params) {
String serverURL = params[0];
try {
URL url = new URL(serverURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.connect();
int responseStatusCode = httpURLConnection.getResponseCode();
Log.d(TAG, "response code - " + responseStatusCode);
InputStream inputStream;
if (responseStatusCode == HttpURLConnection.HTTP_OK) {
inputStream = httpURLConnection.getInputStream();
} else {
inputStream = httpURLConnection.getErrorStream();
}
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
return sb.toString().trim();
} catch (Exception e) {
Log.d(TAG, "InsertData: Error ", e);
errorString = e.toString();
return null;
}
}
}
private void showResult() {
try {
JSONObject jsonObject = new JSONObject(mJsonString);
JSONArray jsonArray = jsonObject.getJSONArray(TAG_JSON);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject item = jsonArray.getJSONObject(i);
String brokenDate = item.getString(TAG_BROKEN_DATE);
String moldCode = item.getString(TAG_MOLD_CODE);
String finalHitting = item.getString(TAG_FINAL_HITTING_TIMES);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put(TAG_BROKEN_DATE, brokenDate);
hashMap.put(TAG_MOLD_CODE, moldCode);
hashMap.put(TAG_FINAL_HITTING_TIMES, finalHitting);
mArrayList.add(hashMap);
}
ListAdapter adapter = new SimpleAdapter(
MoldBreakageHistoryActivity.this, mArrayList, R.layout.list_item_broken_mold,
new String[]{TAG_BROKEN_DATE, TAG_MOLD_CODE, TAG_FINAL_HITTING_TIMES},
new int[]{R.id.brokenDateListItem, R.id.brokenMoldListItem, R.id.finalHittingTimesListItem}
);
brokenMoldListView.setAdapter(adapter);
} catch (JSONException e) {
Log.d(TAG, "showResult : ", e);
}
}
Remove this:
mArrayList = new ArrayList<>();
GetData task = new GetData();
task.execute("http://www.cafe24.com/aaa.php");
from onCreate. onResume is executed right after onCreate and your async task was executing twice, that's why it was duplicated in the first place. When you hit the back only the onResume was executed, so the problem would happen then.
please just remove
mArrayList = new ArrayList<>();
GetData task = new GetData();
task.execute("http://www.cafe24.com/aaa.php");
From your onCreate method. but, if you need to do som scenario in onCreate and other one in onResume you can use mArrayList.clear(); before execute the new task only.
Related
I am trying to get mysql data from remote server www.kudossoft.in/get_data030518.php. but i am getting nothing when i check httpurl response code that is blank.
i have also add uses permission for internet in mainifest
my code is following please see.
i have also checked my php files permission that is ok.
and i am also inserting some data from another activity in same database that is working properly.
MainActivity code:
public class MainActivity extends AppCompatActivity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
getJSON("http://kudossoft.in/get_data300518.php");
}
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String[] heroes = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
heroes[i] = obj.getString("name");``
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, heroes);
listView.setAdapter(arrayAdapter);
}
}
I want to make sure that my activity starts after execution of async task. As of now it gets started before the async task completes in background
This is where new activity is called. Before calling the new activity i am calling PagerAsyncTask. I want to make sure that new activity is called only after successful completion of PagerAsyncTask.
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new PagerAsyncTask().execute();
sharedPreferences = getSharedPreferences(Constants.MY_PREFS, 0);
SharedPreferences.Editor editor = getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putBoolean("hasadd", false);
editor.commit();
Log.e("hi", "dsscdds");
startActivity(new Intent(SplashScreenActivity.this, NavigationActivity.class));
PagerAsyncTask
class PagerAsyncTask extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
StringBuilder sb=null;
BufferedReader reader=null;
String serverResponse=null;
try {
URL url = new URL("https://enigmatic-woodland-35608.herokuapp.com/pager.json");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
connection.connect();
int statusCode = connection.getResponseCode();
//Log.e("statusCode", "" + statusCode);
if (statusCode == 200) {
sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
connection.disconnect();
if (sb!=null)
serverResponse=sb.toString();
Log.e("haha", serverResponse);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return serverResponse;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//All your UI operation can be performed here
//Response string can be converted to JSONObject/JSONArray like
try {
//String mr[] = new String[5];
JSONObject response=new JSONObject(s);
Iterator<?> keys = response.keys();
int i=0;
while( keys.hasNext() ) {
String key = (String)keys.next();
Log.e("hi",key);
Log.e("hey",response.getString(key));
// mr[i]=response.getString(key);
// Log.e("e=",mr[i]);
i++;
}
Log.e("I", String.valueOf(i));
Iterator<?> keys1 = response.keys();
mr = new String[i];
int k=0;
while ( keys1.hasNext() )
{
String key = (String)keys1.next();
mr[k++]=response.getString(key);
Log.e("fdvfd",mr[k-1]);
}
for (int j=0;j<mr.length;j++)
{
Log.e("dsd",mr[j]);
}
isComplete=true;
setMr(mr);
setSet(1);
new RestaurantFragment().setmResources(mr);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
There are a couple of ways to do this
1) use startActivity inside onPostExecute()
2)Pass activity reference to Async task and call some function in the activity from onPostExecute as show here
3)pass a function callback to AsyncTask as shown here. Though this is unnecessarily complicated for your task
You need to move the startActivity to the postExecute of the AsyncTask.
Your onCreate without the startActivity:
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new PagerAsyncTask().execute();
sharedPreferences = getSharedPreferences(Constants.MY_PREFS, 0);
SharedPreferences.Editor editor = getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putBoolean("hasadd", false);
editor.commit();
Log.e("hi", "dsscdds");
The PagerAsyncTask onPostExecute:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//All your UI operation can be performed here
//Response string can be converted to JSONObject/JSONArray like
try {
JSONObject response=new JSONObject(s);
Iterator<?> keys = response.keys();
int i=0;
while( keys.hasNext() ) {
String key = (String)keys.next();
Log.e("hi",key);
Log.e("hey",response.getString(key));|
i++;
}
Log.e("I", String.valueOf(i));
Iterator<?> keys1 = response.keys();
mr = new String[i];
int k=0;
while ( keys1.hasNext() )
{
String key = (String)keys1.next();
mr[k++]=response.getString(key);
Log.e("fdvfd",mr[k-1]);
}
for (int j=0;j<mr.length;j++)
{
Log.e("dsd",mr[j]);
}
isComplete=true;
setMr(mr);
setSet(1);
new RestaurantFragment().setmResources(mr);
startActivity(new Intent(SplashScreenActivity.this, NavigationActivity.class));
} catch (JSONException e) {
e.printStackTrace();
}
Also, the code new RestaurantFragment().setmResources(mr); probably does nothing, since you are not attaching the fragment to anywhere
I have a listview populated by the data from mysql database. It works fine but when I select an item then press back , the previous listview fecth again data from database that duplicates the items in my listview.
Here's is my code :
public class CityPage extends Activity{
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
CityAdapter cityAdapter;
ListView listCity;
ArrayList<City> records;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_page);
context = this;
records = new ArrayList<City>();
listCity = (ListView) findViewById(R.id.cities);
cityAdapter = new CityAdapter(context, R.layout.city_layout, R.id.city_name, records);
listCity.setAdapter(cityAdapter);
listCity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myIntent = new Intent(view.getContext(),City_attractions.class);
Toast.makeText(CityPage.this, "Opening", Toast.LENGTH_LONG).show();
String info1 = records.get(position).getCityName();
String info2 = records.get(position).getDescription();
myIntent.putExtra("info1", info1);
myIntent.putExtra("info2", info2);
startActivity(myIntent);
}
});
}
#Override
protected void onStart() {
super.onStart();
fetchCity fetch = new fetchCity();
fetch.execute();
}
private class fetchCity extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://iguideph-001-site1.btempurl.com/getcity.php");
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (Exception e) {
if (pd != null)
pd.dismiss(); //close the dialog if error occurs
Log.e("ERROR", e.getMessage());
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("ERROR", "Error converting result " + e.toString());
}
//parse json data
try {
// Remove unexpected characters that might be added to beginning of the string
result = result.substring(result.indexOf(""));
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
City p = new City();
p.setCityName(json_data.getString("place_name"));
p.setDescription(json_data.getString("description"));
records.add(p);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
if (pd != null) pd.dismiss(); //close dialog
Log.e("size", records.size() + "");
cityAdapter.notifyDataSetChanged(); //notify the ListView to get new records
}
}
}
try remove those lines from onstart() and put them inside oncreate() function
fetchCity fetch = new fetchCity();
fetch.execute();
Good luck !
I have seen one similar question to this, but i couldn't solve my problem like he did.
Here i'm getting data from url:
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
#Override
protected void onPreExecute() {
setProgressBarIndeterminateVisibility(true);
}
#Override
protected Integer doInBackground(String... params) {
Integer result = 0;
HttpURLConnection urlConnection;
try {
URL url = new URL(params[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
} else {
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result) {
// Download complete. Let us update UI
progressBar.setVisibility(View.GONE);
if (result == 1) {
giftListAdapter = new GiftListAdapter(GiftsActivity.this, gifts);
recyclerView.setAdapter(giftListAdapter);
} else {
SuperActivityToast.create(GiftsActivity.this, getString(R.string.no_internet_connection),
SuperToast.Duration.SHORT, Style.getStyle(Style.RED, SuperToast.Animations.FLYIN)).show();
}
}
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("gifts");
gifts = new ArrayList<>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
GiftItem item = new GiftItem();
item.setThumbnail(post.optString("image"));
item.setTitle(post.optString("title"));
item.setDescription(post.optString("description"));
item.setSource(getString(R.string.source) + " " + post.optString("source"));
item.setTotalRating(post.optInt("rating"));
item.setPrice(post.optDouble("price"));
gifts.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
And here i'm executing that url. I'm trying now to parse this second url and load all items after first data is loaded:
new AsyncHttpTask().execute(url_movies);
new AsyncHttpTask().execute(url_books); // This is the second url i'm trying to get
How could i do that?
I'm trying now to parse this second url and load all items after first
data is loaded:
Then instead of calling execute method just after first, call it inside onPostExecute method when first url all items are loaded successfully.
Also add second call in if-else block to avoid it execute again :
#Override
protected void onPostExecute(Integer result) {
// Download complete. Let us update UI
progressBar.setVisibility(View.GONE);
... your code here
if(params[0].equals(url_movies)){
new AsyncHttpTask().execute(url_books);
}
}
also add
If you want both urls than send them as an String array like this
String urls[] = new String[]{"url1" , "url2"};
new AsyncHttpTask().execute(urls);
and in doinbackground method exec them like
url1 = params[0];
url2 = params[1];
i have create an android application on where the user can select the start and end point of the location.
This application will use the Google-Direction web service and make the HTTPRequest.
I will make this as short, I want to call the asynctask method in the JSONParser class from the main_activity.
The issue is, I don't know how to display the result in the main_activtiy method
here is the asynctask method
public class JSONParser {
InputStream is = null;
JSONObject jObj = null;
String json = "";
public JSONParser() {
}
public void getJSONFromUrl(final String url, final responseListener target) {
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... params) {
HttpURLConnection httpURLConnection = null;
StringBuilder stringBuilder = new StringBuilder();
try {
httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = inputStreamReader.read(buff)) != -1) {
stringBuilder.append(buff, 0, read);
}
return stringBuilder.toString();
} catch (MalformedURLException localMalformedURLException) {
return "";
} catch (IOException localIOException) {
return "";
} finally {
if (httpURLConnection != null)
httpURLConnection.disconnect();
}
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
target.onResponseComplete(result);
}
}.execute();
}
here is how the main method is calling the method
new JSONParser().getJSONFromUrl(url, new responseListener() {
#Override
public void onResponseComplete(String response) {
try {
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
JSONArray step = new JSONObject(response).getJSONArray("routes").getJSONObject(0).getJSONArray("legs")
.getJSONObject(0).getJSONArray("steps");
for (int i = 0; i < step.length(); i++) {
HashMap<String,Object> row = new HashMap<String,Object>();
row.put("Distance", step.getJSONObject(i).getJSONObject("distance").getString("text"));
list.add(row);
}
}catch (Exception e){
e.printStackTrace();
}
}
});
}
the issue right know is how i want to display the Arraylist List value and put it into the TextView call jarak
You can change your List to be
ArrayList<HashMap<String, String>>
as you are getting a string from
step.getJSONObject(i).getJSONObject("distance").getString("text")
To get it out you can use (assuming your textview is called jarak)
for(HashMap<String,String> map : list) {
for(Entry<String, String> entry : map.entrySet()) {
jarak.setText(entry.getKey() + ", " + entry.getValue());
}
}
Hope that helps