how to update Ui from background task - android

My app is not working on android version 4.1 gives exception like android.os.NetworkOnMainThreadException
i have search on stackoverflow advice me to do network thread in background AsyncTask so before use backgroundtask,
My screen look like this http://imgur.com/PlhS03i show multiple rows in nutrition's and ingredient tags after using backgroundtask my screen look like this http://imgur.com/zUvxNpy show only single row in ingredients and nutrition tags
before background task code is this see below
public class fifthscreen extends Activity {
String num = null;
TextView ingredient;
long Menu_ID;
String dish_name;
String status;
HorizontalListView listview;
CategoryListAdapter3 cla;
String DescriptionAPI;
TextView txt1, txt2, txt3;
ImageView img1;
String URL, URL2;
String SelectMenuAPI;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
public static String allergen2;
private AQuery androidAQuery;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fifthscreen);
ingredient = (TextView) findViewById(R.id.ingredient);
img1 = (ImageView) findViewById(R.id.test_button_image);
txt1 = (TextView) findViewById(R.id.menuname);
txt3 = (TextView) findViewById(R.id.description);
Intent iGet = getIntent();
ImageView options = (ImageView) findViewById(R.id.options5);
androidAQuery = new AQuery(this);
options.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent iMenuList = new Intent(fifthscreen.this,
LinkButtons.class);
startActivity(iMenuList);
}
});
dish_name = iGet.getStringExtra("dish_name");
listview = (HorizontalListView) this.findViewById(R.id.listview2);
cla = new CategoryListAdapter3(fifthscreen.this);
listview.setAdapter(cla);
parseJSONData();
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public void parseJSONData() {
SelectMenuAPI = Utils.dishdescription + dish_name;
clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
if (status.equals("1")) {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
String name = school2.getJSONObject(0).getString("name");
txt1.setText(name);
String description = school2.getJSONObject(0).getString(
"description");
txt3.setText(description);
String url1 = school2.getJSONObject(0).getString("image");
androidAQuery.id(img1).image(url1, false, false);
}
JSONObject school3 = json2.getJSONObject("dish_nutrition");
final TableLayout table = (TableLayout) findViewById(R.id.table2);
for (int j = 0; j < school3.length(); j++) {
String s = String.valueOf(j + 1);
final View row = createRow(school3.getJSONObject(s));
table.addView(row);
}
JSONArray school4 = json2.getJSONArray("dish_allergen");
//
for (int i = 0; i < school4.length(); i++) {
JSONObject object = school4.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
Category_image.add(object.getString("image"));
listview.setAdapter(cla);
}
final LinearLayout table3 = (LinearLayout) findViewById(R.id.table3);
JSONArray school5 = json2.getJSONArray("dish_ingredient");
for (int i = 0; i < school5.length(); i++) {
final View row2 = createRow2(school5.getJSONObject(i));
table3.addView(row2);
}
}
else {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
// IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public View createRow(JSONObject item) throws JSONException {
View row = getLayoutInflater().inflate(R.layout.rows, null);
((TextView) row.findViewById(R.id.localTime)).setText(item
.getString("qty"));
((TextView) row.findViewById(R.id.apprentTemp)).setText(item
.getString("name"));
return row;
}
public View createRow2(JSONObject item) throws JSONException {
View row2 = getLayoutInflater().inflate(R.layout.row2, null);
((TextView) row2.findViewById(R.id.name)).setText(item
.getString("name"));
((TextView) row2.findViewById(R.id.subingredients)).setText(item
.getString("sub_ingredients"));
return row2;
}
}
After using AsyncTask see this code below
public class fifthscreen extends Activity {
String num = null;
TextView ingredient;
long Menu_ID;
String dish_name;
String status;
HorizontalListView listview;
CategoryListAdapter3 cla;
String DescriptionAPI;
TextView txt1, txt2, txt3;
ImageView img1;
String URL, URL2;
String SelectMenuAPI;
String description;
int IOConnect = 0;
String name;
String url1;
TableLayout table;
LinearLayout table3;
View row;
View row2;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
public static String allergen2;
private AQuery androidAQuery;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fifthscreen);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ingredient = (TextView) findViewById(R.id.ingredient);
img1 = (ImageView) findViewById(R.id.test_button_image);
txt1 = (TextView) findViewById(R.id.menuname);
// txt2 = (TextView) findViewById(R.id.test_button_text1);
txt3 = (TextView) findViewById(R.id.description);
table = (TableLayout) findViewById(R.id.table2);
table3 = (LinearLayout) findViewById(R.id.table3);
Intent iGet = getIntent();
ImageView options = (ImageView) findViewById(R.id.options5);
androidAQuery = new AQuery(this);
options.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent iMenuList = new Intent(fifthscreen.this,
LinkButtons.class);
startActivity(iMenuList);
}
});
dish_name = iGet.getStringExtra("dish_name");
listview = (HorizontalListView) this.findViewById(R.id.listview2);
cla = new CategoryListAdapter3(fifthscreen.this);
new getDataTask().execute();
// listview.setAdapter(cla);
ImageView btnback = (ImageView) findViewById(R.id.btnback);
btnback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
parseJSONData();
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void> {
getDataTask() {
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
txt1.setText(name);
txt3.setText(description);
androidAQuery.id(img1).image(url1, false, false);
table.addView(row);
table3.addView(row2);
listview.setAdapter(cla);
}
}
public void parseJSONData() {
SelectMenuAPI = Utils.dishdescription + dish_name;
clearData();
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
if (status.equals("1")) {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
name = school2.getJSONObject(0).getString("name");
description = school2.getJSONObject(0).getString(
"description");
url1 = school2.getJSONObject(0).getString("image");
}
JSONObject school3 = json2.getJSONObject("dish_nutrition");
for (int j = 0; j < school3.length(); j++) {
String s = String.valueOf(j + 1);
row = createRow(school3.getJSONObject(s));
}
JSONArray school4 = json2.getJSONArray("dish_allergen");
//
for (int i = 0; i < school4.length(); i++) {
JSONObject object = school4.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
Category_image.add(object.getString("image"));
}
JSONArray school5 = json2.getJSONArray("dish_ingredient");
for (int i = 0; i < school5.length(); i++) {
row2 = createRow2(school5.getJSONObject(i));
}
}
else {
JSONArray school2 = json2.getJSONArray("data");
for (int i = 0; i < school2.length(); i++) {
JSONObject object = school2.getJSONObject(i);
Category_ID.add((long) i);
Category_name.add(object.getString("name"));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
// IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public View createRow(JSONObject item) throws JSONException {
View row = getLayoutInflater().inflate(R.layout.rows, null);
((TextView) row.findViewById(R.id.localTime)).setText(item
.getString("qty"));
((TextView) row.findViewById(R.id.apprentTemp)).setText(item
.getString("name"));
return row;
}
public View createRow2(JSONObject item) throws JSONException {
View row2 = getLayoutInflater().inflate(R.layout.row2, null);
((TextView) row2.findViewById(R.id.name)).setText(item
.getString("name"));
((TextView) row2.findViewById(R.id.subingredients)).setText(item
.getString("sub_ingredients"));
return row2;
}
}
Please Help
Thanks in Advance...:)

Use the Handler object from your MainActivity and post a runnable. To use it from the backgrund you need to make the object a static that you can call outside of your MainActivity or you can create a static instance of the Activity to access it.
Inside the Activity
private static Handler handler;
handler = new Handler();
handler().post(new Runnable() {
public void run() {
//ui stuff here :)
}
});
public static Handler getHandler() {
return handler;
}
Outside the Activity
MainActivity.getHandler().post(new Runnable() {
public void run() {
//ui stuff here :)
}
});

You can use **runOnUiThread()** like this:
try {
// code runs in a thread
runOnUiThread(new Runnable() {
#Override
public void run() {
// YOUR CODE
}
});
} catch (final Exception ex) {
Log.i("---","Exception in thread");
}

You need to create AsyncTask class and use it
Read here more: AsyncTask
Example would look like this:
private class UploadTask extends AsyncTask<Void, Void, Void>
{
private String in;
public UploadTask(String input)
{
this.in = input;
}
#Override
protected void onPreExecute()
{
//start showing progress here
}
#Override
protected Void doInBackground(Void... params)
{
//do your work
return null;
}
#Override
protected void onPostExecute(Void result)
{
//stop showing progress here
}
}
And start task like this:
UploadTask ut= new UploadTask(input);
ut.execute();

you are handling ui in these methods
public View createRow(JSONObject item) throws JSONException {
View row = getLayoutInflater().inflate(R.layout.rows, null);
((TextView) row.findViewById(R.id.localTime)).setText(item
.getString("qty"));
((TextView) row.findViewById(R.id.apprentTemp)).setText(item
.getString("name"));
return row;
}
public View createRow2(JSONObject item) throws JSONException {
View row2 = getLayoutInflater().inflate(R.layout.row2, null);
((TextView) row2.findViewById(R.id.name)).setText(item
.getString("name"));
((TextView) row2.findViewById(R.id.subingredients)).setText(item
.getString("sub_ingredients"));
return row2;
}
which are called in background thread
if possible do it in onPostExecute or you can use runOnUiThread and Handler.

Related

cannot select radio button

I have a RadioGroup in which I have 5 RadioButton's. Also I have a button next. On click of next button the text of radiobuttons changes. It all works fine but some of the radio buttons are not selected. This is my xml file
public class SampleTestQuestionsActivity extends AppCompatActivity {
String totalques, timee, namee, idd;
String strServerResponse;
ProgressDialog nDialog;
ConnectionDetector cd;
Pojo pojo;
SamplePaperPojo samplePaperPojo;
RadioButton s_rb_1, s_rb_2, s_rb_3, s_rb_4, s_rb_5;
RadioGroup s_rbgrp;
private Toolbar toolbar;
TextView s_section, s_time, s_question;
Button s_submit, s_next, s_previous;
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
long startTime;
private final long interval = 1 * 1000;
final Context context = this;
ArrayList<String> al_que_title;
ArrayList<String> al_que_id;
ArrayList<String> al_ans1;
ArrayList<String> al_ans2;
ArrayList<String> al_ans3;
ArrayList<String> al_ans4;
ArrayList<String> al_ans5;
ArrayList<String> al_correct;
ArrayList<String> al_exp;
ArrayList<String> al_desc;
String submitQuestionId;
ArrayList<SamplePaperPojo> sampleTest;
RadioButton selectedRbButton;
public static int inc = 0;
String correctAns;
ArrayList<String> selectedAns;
int selectedpos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample_test_questions);
toolbar = (Toolbar) findViewById(R.id.app_bar);
toolbar.setTitle("Sample Tests");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
al_que_title = new ArrayList<String>();
al_que_id = new ArrayList<String>();
al_ans1 = new ArrayList<String>();
al_ans2 = new ArrayList<String>();
al_ans3 = new ArrayList<String>();
al_ans4 = new ArrayList<String>();
al_ans5 = new ArrayList<String>();
al_correct = new ArrayList<String>();
al_exp = new ArrayList<String>();
al_desc = new ArrayList<String>();
selectedAns = new ArrayList<String>();
Intent i =getIntent();
namee = i.getStringExtra("test_name");
totalques = i.getStringExtra("test_ques");
timee = i.getStringExtra("test_time");
idd = i.getStringExtra("test_id");
sampleTest = new ArrayList<SamplePaperPojo>();
Log.e("test_id", ""+idd);
Long ti = Long.valueOf(timee);
startTime = 1000*ti;
s_section = (TextView) findViewById(R.id.sampleSectionName);
s_time = (TextView) findViewById(R.id.sampleTimer);
s_question = (TextView) findViewById(R.id.sampleQuestion);
s_submit = (Button) findViewById(R.id.sampleSubmitAnswer);
s_next = (Button) findViewById(R.id.sampleNext);
s_previous = (Button) findViewById(R.id.samplePrevious);
s_rbgrp = (RadioGroup) findViewById(R.id.s_rbgrp);
s_rb_1 = (RadioButton) findViewById(R.id.SA);
s_rb_2 = (RadioButton) findViewById(R.id.SB);
s_rb_3 = (RadioButton) findViewById(R.id.SC);
s_rb_4 = (RadioButton) findViewById(R.id.SD);
s_rb_5 = (RadioButton) findViewById(R.id.SE);
countDownTimer = new MyCountDownTimer(startTime, interval);
s_time.setText(s_time.getText() + String.valueOf(startTime / 1000));
new NetCheck().execute();
s_next.setVisibility(View.GONE);
s_previous.setVisibility(View.GONE);
s_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int index_selected = s_rbgrp.indexOfChild(s_rbgrp
.findViewById(s_rbgrp.getCheckedRadioButtonId()));
// get selected radio button from radioGroup
int selectedId = s_rbgrp.getCheckedRadioButtonId();
if (selectedId==-1){
AlertDialog alertDialog = new AlertDialog.Builder(
SampleTestQuestionsActivity.this).create();
alertDialog.setMessage("Please select atleast one answer.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
s_next.setVisibility(View.VISIBLE);
}
});
s_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitQuestionId = al_que_id.get(inc).toString();
s_rb_1.setTextColor(Color.parseColor("#000000"));
s_rb_2.setTextColor(Color.parseColor("#000000"));
s_rb_3.setTextColor(Color.parseColor("#000000"));
s_rb_4.setTextColor(Color.parseColor("#000000"));
s_rb_5.setTextColor(Color.parseColor("#000000"));
int selectedId = s_rbgrp.getCheckedRadioButtonId();
selectedRbButton = (RadioButton) findViewById(selectedId);
selectedRbButton.setChecked(false);
inc = inc + 1;
s_question.setText("" + al_que_title.get(inc).toString());
s_rb_1.setText("" + al_ans1.get(inc).toString());
s_rb_2.setText("" + al_ans2.get(inc).toString());
s_rb_3.setText("" + al_ans3.get(inc).toString());
s_rb_4.setText("" + al_ans4.get(inc).toString());
s_rb_5.setText("" + al_ans5.get(inc).toString());
s_next.setVisibility(View.GONE);
}
});
}
private class NetCheck extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
nDialog = new ProgressDialog(SampleTestQuestionsActivity.this);
nDialog.setMessage("Loading..");
nDialog.setTitle("Please Wait");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.e("Post exec calleld", "dfds");
nDialog.dismiss();
s_question.setText("" + al_que_title.get(inc).toString());
s_rb_1.setText("" + al_ans1.get(inc).toString());
s_rb_2.setText("" + al_ans2.get(inc).toString());
s_rb_3.setText("" + al_ans3.get(inc).toString());
s_rb_4.setText("" + al_ans4.get(inc).toString());
s_rb_5.setText("" + al_ans5.get(inc).toString());
countDownTimer.start();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
cd = new ConnectionDetector(getApplicationContext());
if (!cd.isConnectingToInternet()) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(
new Runnable() {
#Override
public void run() {
AlertDialog alertDialog = new AlertDialog.Builder(
SampleTestQuestionsActivity.this).create();
alertDialog.setMessage("Error connecting to internet.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
);
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(
"http://url");
httpRequest.setHeader("Content-Type", "application/json");
SharedPreferences preff = getSharedPreferences(
"MyPref", MODE_PRIVATE);
String userid = preff.getString("id", null);
Log.e("Student id", "" + userid);
JSONObject json = new JSONObject();
json.put("mocktest_id", idd);
json.put("section_id", 1);
Log.e("JSON Object", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
httpRequest.setEntity(se);
HttpResponse httpRes = httpClient.execute(httpRequest);
java.io.InputStream inputStream = httpRes.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
strServerResponse = sb.toString();
Log.e("Server Response", "" + strServerResponse.toString());
if (strServerResponse != null) {
try {
JSONArray arr1 = new JSONArray(strServerResponse);
JSONObject jsonObj1 = arr1.getJSONObject(0);
samplePaperPojo = new SamplePaperPojo();
for (int i = 0; i < arr1.length(); i++) {
JSONObject jobjj11 = arr1
.getJSONObject(i);
String qq_id = jobjj11.optString("id");
String qq_title = jobjj11.optString("title");
String qq_des = jobjj11.optString("description");
String ans_a = jobjj11.optString("ans_a");
String ans_b = jobjj11.optString("ans_b");
String ans_c = jobjj11.optString("ans_c");
String ans_d = jobjj11.optString("ans_d");
String ans_e = jobjj11.optString("ans_e");
String right_ans = jobjj11.optString("right_ans");
String explanation = jobjj11.optString("explanation");
samplePaperPojo.setSampleQuesId(qq_id);
samplePaperPojo.setSampleQuesTitle(qq_title);
samplePaperPojo.setSampleAns1(ans_a);
samplePaperPojo.setSampleAns2(ans_b);
samplePaperPojo.setSampleAns3(ans_c);
samplePaperPojo.setSampleAns4(ans_d);
samplePaperPojo.setSampleAns5(ans_e);
samplePaperPojo.setSampleRightAns(right_ans);
samplePaperPojo.setSampleQuesDescription(qq_des);
samplePaperPojo.setSampleExplaination(explanation);
sampleTest.add(samplePaperPojo);
al_que_id.add(qq_id);
al_que_title.add(qq_title);
al_ans1.add(ans_a);
al_ans2.add(ans_b);
al_ans3.add(ans_c);
al_ans4.add(ans_d);
al_ans5.add(ans_e);
al_correct.add(right_ans);
al_exp.add(explanation);
al_desc.add(qq_des);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler",
"Couldn't get any data from the url");
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}
The radio button which I previously selected is not selected when the text is changed after i click on next button. Please help
You should replace:
int selectedId = s_rbgrp.getCheckedRadioButtonId();
selectedRbButton = (RadioButton) findViewById(selectedId);
selectedRbButton.setChecked(false);
with:
s_rbgrp.clearCheck();

ListView Empty When Poputaing

I am trying to add items from database onto a listView, when I use System.out.println I see values but upon trying to populate them onto a custom listview returns no data in the listview.
When launching the app, I get a single row of listview item but of course it's empty.
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
String jsonResult;
String url = "http://www.mywebsite/query.php";
ListView list;
List<String> arrName;
List<String> arrNumber;
List<String> arrUsername;
List<String> arrStatus;
String name;
String number;
String username;
String status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
arrName = Arrays.asList(name);
arrNumber = Arrays.asList(number);
arrUsername = Arrays.asList(username);
arrStatus = Arrays.asList(status);
list = (ListView) findViewById(R.id.listContacts);
ConatctsAdapter adapter = new ConatctsAdapter(this, arrName, arrNumber, arrUsername, arrStatus);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
accessWebService();
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { //SINGLE CLICK
// TODO Auto-generated method stub
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("main");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
name = jsonChildNode.getString("Name");
number = jsonChildNode.getString("Number");
username = jsonChildNode.getString("Username");
status = jsonChildNode.getString("Status");
System.out.println("Name: "+name);
System.out.println("Number: "+number);
System.out.println("Username: "+username);
System.out.println("Status: "+status);
}
} catch (JSONException e) {
Log.i("Error Log: ", e.toString());
System.out.println("Error: "+e.toString());
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
ContactsAdapter adapter = new ContactsAdapter(this, arrName, arrNumber, arrUsername, arrStatus);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
class ContactsAdapter extends ArrayAdapter<String>
{
Context context;
List<String> Name;
List<String> Number;
List<String> Username;
List<String> Status;
ContactsAdapter(Context c, List<String> Name, List<String> Number, List<String> Username, List<String> Status)
{
super(c, R.layout.activity_contacts_single, R.id.textName, Name);
this.context=c;
this.Name=Name;
this.Number=Number;
this.Username=Username;
this.Status=Status;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row=convertView;
if(row==null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.activity_contacts_single, parent, false);
}
TextView txtName = (TextView) row.findViewById(R.id.textName);
TextView txtNumber = (TextView) row.findViewById(R.id.textNumber);
TextView txtUsername = (TextView) row.findViewById(R.id.textUsername);
TextView txtStatus = (TextView) row.findViewById(R.id.textStatus);
txtName.setText(Name.get(position));
txtNumber.setText(Number.get(position));
txtUsername.setText(Username.get(position));
txtStatus.setText(Status.get(position));
return row;
}
}
}
It's because you haven't add those items into your lists, Change this part of your code:
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("main");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
name = jsonChildNode.getString("Name");
number = jsonChildNode.getString("Number");
username = jsonChildNode.getString("Username");
status = jsonChildNode.getString("Status");
//add this part to your code
arrName.add(name);
arrNumber.add(number);
arrUsername.add(username);
arrStatus.add(status);
System.out.println("Name: "+name);
System.out.println("Number: "+number);
System.out.println("Username: "+username);
System.out.println("Status: "+status);
}
} catch (JSONException e) {
Log.i("Error Log: ", e.toString());
System.out.println("Error: "+e.toString());
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
ContactsAdapter adapter = new ContactsAdapter(this, arrName, arrNumber, arrUsername, arrStatus);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
for your second problem I think you can change your code this way:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
//arrName = Arrays.asList(name);
//arrNumber = Arrays.asList(number);
//arrUsername = Arrays.asList(username);
//arrStatus = Arrays.asList(status);
arrName = new ArrayList<String>();
arrNumber =new ArrayList<String>();
arrUsername =new ArrayList<String>();
arrStatus =new ArrayList<String>();
list = (ListView) findViewById(R.id.listContacts);
ConatctsAdapter adapter = new ConatctsAdapter(this, arrName, arrNumber, arrUsername, arrStatus);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
accessWebService();
}

my llistview load multiple time same data on screen

my listview repeat data some time which click on buttons fastly what do i do please help me see this images http://imgur.com/ed5uDtp after some time is show like this http://imgur.com/jAt4yn7
is show correctly data on listview but some time when click fastly buttons is load duplicate data how i will fixed this? plaa help me
public class thirdstep extends Activity implements View.OnClickListener {
int count = 0;
String id;
String title;
String tmpString, finaldate;
String valll;
ProgressBar prgLoading;
TextView txtAlert;
int IOConnect = 0;
String mVal9;
Button e01;
Button e02;
Button e03;
Button e04;
Button e05;
String SelectMenuAPI;
String url;
String URL;
String URL2, URL3, URL4;
String menu_title;
JSONArray school;
ListView listCategory;
String status;
String School_ID;
String Menu_ID;
String School_name;
String Meal_groupid;
String _response;
String _response2;
String CategoryAPI;
String SelectMenuAPI2;
TextView menu_nametxt;
thirdstepAdapter cla;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> school_name = new ArrayList<String>();
static ArrayList<String> menu_name = new ArrayList<String>();
static ArrayList<String> dish_name = new ArrayList<String>();
static ArrayList<String> dish_ID = new ArrayList<String>();
static ArrayList<String> day = new ArrayList<String>();
static ArrayList<Long> Vacation_ID = new ArrayList<Long>();
static ArrayList<String> Vacation_name = new ArrayList<String>();
static ArrayList<String> Vacation_Date = new ArrayList<String>();
String mydate;
String mode;
String s2;
ArrayList<String> myList,myList2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list2);
listCategory = (ListView) findViewById(R.id.thirdscreenlist);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
e01 = (Button) findViewById(R.id.e01);
e02 = (Button) findViewById(R.id.e02);
e03 = (Button) findViewById(R.id.e03);
e04 = (Button) findViewById(R.id.e04);
e05 = (Button) findViewById(R.id.e05);
e01.setOnClickListener(this);
e02.setOnClickListener(this);
e03.setOnClickListener(this);
e04.setOnClickListener(this);
e05.setOnClickListener(this);
cla = new thirdstepAdapter(thirdstep.this);
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(thirdstep.this, fifthscreen.class);
startActivity(intent);
}
});
new getDataTask().execute();
}
void clearData() {
Category_ID.clear();
school_name.clear();
menu_name.clear();
dish_name.clear();
dish_ID.clear();
day.clear();
Vacation_ID.clear();
Vacation_name.clear();
Vacation_Date.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void> {
getDataTask() {
if (!prgLoading.isShown()) {
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
prgLoading.setVisibility(8);
if ((Category_ID.size() > 0) || IOConnect == 0) {
listCategory.setAdapter(cla);
cla.notifyDataSetChanged() ;
listCategory.invalidateViews();
} else {
txtAlert.setVisibility(0);
menu_nametxt.setText("");
listCategory.setVisibility(View.GONE);
}
}
}
public void parseJSONData() {
clearData();
SelectMenuAPI="";
SelectMenuAPI = Utils.Schoolmenu +Menu_ID+"&sid="+School_ID+"&lid=" +
SchoolLevelId+"&mealid="+Meal_groupid;
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
Log.i("url",""+URL2);
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
HttpEntity resEntity = response.getEntity();
_response=EntityUtils.toString(resEntity);
JSONObject json5 = new JSONObject(_response);
status = json5.getString("status");
if (status.equals("1")) {
JSONArray school5 = json5.getJSONArray("data");
}
}
else {
}
SelectMenuAPI2="";
SelectMenuAPI2 = Utils.SchoolVacation+mVal9;
// clearData();
URL3 = SelectMenuAPI2;
URL4 = URL3.replace(" ", "%20");
Log.i("url",""+URL4);
JSONObject json2 = new JSONObject(_response);
status = json2.getString("status");
if (status.equals("1")) {
if (Vacation_Date.contains(mydate)) {
message = "holiday";
JSONObject json4 = new JSONObject(str2);
status = json4.getString("status");
if (status.equals("1")) {
school = json4.getJSONArray("data");
for (int k = 0; k < school.length(); k++) {
JSONObject jb = (JSONObject) school .getJSONObject(k);
Vacation_ID.add((long) k);
String[] mVal = new String[school.length()];
if(school.getJSONObject(k).getString("date").equals(mydate))
{
mVal[k] = school.getJSONObject(k).getString("title");
mVal3 = mVal[k];
}
}
}
} else {
JSONArray school = json2.getJSONArray("data");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
if (object.getString("Schedule").equals("weekly")) {
if (object.getString("day").equals(Todayday)) {
Category_ID.add((long) i);
school_name
.add(object.getString("school_name"));
dish_ID.add(object.getString("dish_id"));
dish_name.add(object.getString("dish_name"));
menu_name.add(object.getString("menu_title"));
day.add(object.getString("day"));
count = count + 1;
String[] mVal = new String[school.length()];
for (int k = 0; k < school.length(); k++) {
mVal[k] = school.getJSONObject(k).getString("menu_title");
message = "weekly";
mVal2 = mVal[0];
}
}
if(dish_name != null &&
!dish_name.isEmpty())
{
message = "weekly";
}
else {
message = "error";
}
}
else {
message = "error";
}
}
}
}
else {
message = "error";
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.e01:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e02:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e03:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e04:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e05:
listCategory.setVisibility(View.GONE);
// do stuff;
new getDataTask().execute();
break;
}
}
}
You are calling asynctask twice and that is making all parts twice, I mean you are cleaning twice before filling and fill arrays twice. You should control your async task for do not execute before last one finished.
1-Create a boolean value
2-Put condition on onClicks:
if(yourBoolean){
new getDataTask().execute();}
3- in your asyncTask's onPreExecute make yourBoolean=false and onPostExecute make yourBoolean=true again.
Try this..
Just remove the below line and try it..
listCategory.invalidateViews();
because
ListView.invalidateViews() is used to tell the ListView to invalidate all its child item views (redraw them). Note that there not need to be an equal number of views than items. That's because a ListView recycles its item views and moves them around the screen in a smart way while you scroll.

how to fix getDataTask method error?

below is my code there is a problem some where in getDataTask if i remove this class is work fine and print Toast message Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); but what is problem in my getDataTask im parsing below json file problem is some where in doinbackground method help me please
{"status":0,"message":"No such school found"}
public class thirdstep extends Activity {
ListView listCategory;
String status;
String message;
String MenuSelect;
ProgressBar prgLoading;
long Cat_ID;
String Cat_name;
String CategoryAPI;
int IOConnect = 0;
TextView txtAlert;
thirdstepAdapter cla;
static ArrayList<String> Category_ID = new ArrayList<String>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list2);
ImageButton btnback = (ImageButton) findViewById(R.id.btnback);
listCategory = (ListView) findViewById(R.id.listCategory2);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
cla = new thirdstepAdapter(thirdstep.this);
new getDataTask().execute();
listCategory.setAdapter(cla);
btnback.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
Intent iGet = getIntent();
Cat_ID = iGet.getLongExtra("category_id", 0);
Cat_name = iGet.getStringExtra("category_name");
Toast.makeText(this, Cat_ID + Cat_name, Toast.LENGTH_SHORT).show();
MenuSelect = Utils.MenuSelect;
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(thirdstep.this, fourthscreen.class);
iMenuList.putExtra("Cat_ID",Cat_ID);
iMenuList.putExtra("Menuitem", Category_ID.get(position));
startActivity(iMenuList);
}
});
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void>{
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
prgLoading.setVisibility(8);
if((Category_ID.size() > 0) || IOConnect == 0){
listCategory.setVisibility(0);
listCategory.setAdapter(cla);
}else{
txtAlert.setVisibility(0);
}
}
}
public void parseJSONData() {
CategoryAPI = Utils.MenuList + Cat_ID;
clearData();
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json = new JSONObject(str);
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
message = json2.getString("message");
if (status.equals("1")) {
JSONObject data = json.getJSONObject("data");
JSONArray school = data.getJSONArray("menu_groups");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
Category_ID.add(object.getString("id"));
Category_name.add(object.getString("title"));
Category_image.add(object.getString("image"));
}
}
else
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You are calling parseJSONData() in doInbackground and you have this
Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); // in parseJSONData()
you cannot update ui from doInbackground. You need to update ui on the ui thread. Return result in doInbackground. In onPostExecute update ui.

Show data on Listview is duplication

I'm doing a app can update data every 1 minutes, data will from database mysql on server to show on listview of my app android. My problem is when show data the first is ok but when show data the second on listview, data of the first and the second is duplication.Can you help me!
Source code:
public class Hoadon extends Activity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> al1 = new ArrayList<String>();
ArrayList<String> al2 = new ArrayList<String>();
ArrayList<String> al3 = new ArrayList<String>();
ArrayList<String> al1a = new ArrayList<String>();
String date;
String name;
String address;
String url;
String code;
int responseCode;
private String IDinvoice;
private TimerTask mTimerTask;
private Timer t=new Timer();
private final Handler handler=new Handler();
private ListView listview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hoadon);
int currentOrientation = getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
try {
URL url = new URL("http://longvansolution.tk/monthlytarget.php");
URLConnection connection = url.openConnection();
connection.setConnectTimeout(2000);
HttpURLConnection httpConnection = (HttpURLConnection) connection;
responseCode = httpConnection.getResponseCode();
} catch (Exception e) {
}
try {
if (isNetworkAvailable() == true
//&& responseCode == HttpURLConnection.HTTP_OK
) {
//new LoadData().execute();
al.clear();
al1.clear();
al2.clear();
al3.clear();
al1a.clear();
doTimerTask();
} else {
AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setMessage("No Internet Connection available!!!");
ad.show();
}
} catch (Exception e) {
}
Bundle extras = getIntent().getExtras();
if (extras != null) {
IDinvoice = extras.getString("IDinvoice");
}
}
public void doTimerTask(){
mTimerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
new LoadData().execute();
Log.d("TIMER", "TimerTask run");
}
});
}};
// public void schedule (TimerTask task, long delay, long period)
t.schedule(mTimerTask, 500, 10000); //
}
#Override
public void onBackPressed() {
//do something with bitmap
}
private class LoadData extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
// can use UI thread here
protected void onPreExecute() {
this.progressDialog = ProgressDialog.show(
Hoadon.this, "", " Loading...");
}
#Override
protected void onPostExecute(final Void unused) {
this.progressDialog.dismiss();
try {
listview = (ListView) findViewById(R.id.listView1);
this.progressDialog.dismiss();
listview.setAdapter(new DataAdapter(Hoadon.this,
al.toArray(new String[al.size()]), al1a
.toArray(new String[al1a.size()]), al1
.toArray(new String[al1.size()]), al2
.toArray(new String[al2.size()])));
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String t = al3.get(position);
Intent i = new Intent(Hoadon.this,
Signature.class);
i.putExtra("url", t);
startActivity(i);
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// HTTP post
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(
"http://longvansolution.tk/monthlytarget.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
// buffered reader
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 80);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
date = json_data.getString("date");
address = json_data.getString("address");
name = json_data.getString("name");
url = json_data.getString("url");
code = json_data.getString("code");
al.add(date);
al1a.add(code);
al1.add(name);
al2.add(address);
al3.add(url);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
} catch (ParseException e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
return null;
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null, otherwise check
// if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
// Log.i("net status:", "Online...!!!");
return true;
}
// Log.i("net status:", "offline...!!!");
return false;
}
}
Source DataAdapter
public class DataAdapter extends BaseAdapter {
Context mContext;
private LayoutInflater mInflater;
String[] date;
String[] code;
String[] address;
String[] name;
public DataAdapter(Context c, String[] date,String[] code, String[] name, String[] address) {
this.date = date;
this.code=code;
this.name = name;
this.address = address;
mContext = c;
mInflater = LayoutInflater.from(c);
}
public void clearData() {
// clear the data
Arrays.fill(date, null);
Arrays.fill(code, null);
Arrays.fill(address, null);
Arrays.fill(name, null);
}
public int getCount() {
return date.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.customgrid, parent, false);
holder = new ViewHolder();
holder.date = (TextView) convertView.findViewById(R.id.date);
holder.code=(TextView)convertView.findViewById(R.id.mahd);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.address = (TextView) convertView.findViewById(R.id.address);
if (position == 0) {
convertView.setTag(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
holder.date.setText(date[position]);
holder.code.setText(code[position]);
holder.name.setText(name[position]);
holder.address.setText(address[position]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return convertView;
}
static class ViewHolder {
TextView date,code;
TextView name, address;
}
}
you should clear your arralist every LoadData task.
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
al.clear();
al1.clear();
al2.clear();
al3.clear();
al1a.clear();
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
date = json_data.getString("date");
address = json_data.getString("address");
name = json_data.getString("name");
url = json_data.getString("url");
code = json_data.getString("code");
al.add(date);
al1a.add(code);
al1.add(name);
al2.add(address);
al3.add(url);
}

Categories

Resources