In this i want to cancel the asynctask i called aysnc task in listview onclickitem...
so if there is no data in particular row's then it will stop execution and remain on same activity.
I called the class in click and if condition if false as file_path is null then it will remain on same activity will not proceed further in another activity.
but in my case it will move to another activity i tried lot many things on this like oncancelled(), cancel(), etc methods but they are not working i put all in loop as well as switch case to break.
public class EAdFragment extends Fragment {
ListView lvAdSurvey;
JSONObject json = null;
public static final String FIRST_COLUMN = "Upl_ID";
public static final String SECOND_COLUMN = "File_Description";
JSONArray jarray = null;
JSONObject jsonObj = null;
String upload_type;
String upl_id;
File f;
String imgurl;
ProgressDialog pDialog;
String upl_ID, type_of_upload, file_description, amount;
String file_path = null;
String file_type, related_to, country, state, city, Number_of_user,
type_illegal;
GetData task;
ViewHolder holder;
public ListAdapter adapter;
String text;
public List<EAdvertActivityData> listData = new ArrayList<EAdvertActivityData>();
public void onViewCreated(View view, Bundle savedInstanceState) {
lvAdSurvey = (ListView) view.findViewById(R.id.lvAdSurvey);
new GetList().execute();
lvAdSurvey.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// String text =
// lvAdSurvey.getItemAtPosition(position).toString();
holder = (ViewHolder) view.getTag();
text = holder.txtFirstColumn.getText().toString();
Log.d("text:", text);
task = new GetData();
task.execute();
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_ead, container,
false);
return rootView;
}
private class GetList extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected JSONObject doInBackground(String... args) {
String url = "url";
JSONParser jParser = new JSONParser();
jsonObj = jParser.getJSONFromUrl(url);
try {
jarray = jsonObj.getJSONArray("result");
Log.d("lengtharray:", String.valueOf(jarray.length()));
for (int i = 0; i < jarray.length(); i++) {
EAdvertActivityData data = new EAdvertActivityData();
JSONObject jobject = new JSONObject(jarray.get(i)
.toString());
upload_type = jobject.optString("Upl_ID").toString();
String description = jobject.optString("File_description")
.toString();
/*
* Log.d("upload_type",upload_type);
* Log.d("description",description);
*/data.setUpl_ID(upload_type);
data.setFile_description(description);
listData.add(data);
Log.d("data:", listData.toString());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObj;
}
protected void onPostExecute(JSONObject jsonObject) {
EAdListViewAdapter adapter = new EAdListViewAdapter(getActivity(),
listData);
lvAdSurvey.setAdapter(adapter);
}
}
private class GetData extends AsyncTask<String, String, String> {
int flag=0;
protected void onPreExecute() {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Image ....");
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
SharedPreferences pref = getActivity().getSharedPreferences(
"SoundSettings", Context.MODE_PRIVATE);
String user_id = pref.getString("user_id", LoginActivity.userid);
String url = "url"
+ text;
JSONParser jParser = new JSONParser();
try {
json = jParser.getJSONFromUrl(url);
Log.d("jsonadvert:", json.toString());
String status = json.getString("fetchdata");
if (status.equals("Success")) {
type_of_upload = json.getString("Type_of_Upload");
file_description = json.getString("File_description");
amount = json.getString("Amount");
file_path = json.getString("file_path");
file_type = json.getString("File_type");
related_to = json.getString("Related_to");
country = json.getString("Country");
// state = json.getString("state");
Number_of_user = json.getString("Number_of_usr");
type_illegal = json.getString("Type_llegal");
Log.d("type_illegal:", type_illegal);
Log.d("file_path:", file_path);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String args) {
pDialog.dismiss();
if(file_path==null){
Toast.makeText(getActivity(), "Image does not exists", Toast.LENGTH_LONG).show();
pDialog.cancel();
task.cancel(true);
}else{
imgurl = "http://sharpersofttech.com/sign_up/" + file_path;
Intent in = new Intent(getActivity(), AdvertActivity.class);
in.putExtra("upl_id", text);
in.putExtra("file_description", file_description);
in.putExtra("imgurl", imgurl);
startActivity(in);
((Activity) getActivity()).overridePendingTransition(0, 0);
}
}
}
}
Related
I already try to display image in ListView, but I got an error at this line:
status.setImageResource(R.drawable.inprogress);
*setimageresource undefined for String.
I'm trying to display the image based on the status, if status equals to "Compalint in process" and then the in progress icon will display in the ListView.
This my full code:
public class SenaraiSemuaComplaint extends ListActivity {
String stud_staff_ID;
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> listcomplaint;
final Context context = this;
private static String url_listcomplaint = "...";
private static final String TAG_SUCCESS = "success";
private static final String TAG_REGISTER = "register";
private static final String TAG_PID = "pid";
private static final String TAG_DATE = "date";
private static final String TAG_STATUS = "status";
JSONArray register = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listallcomplaint_layout);
getActionBar().setHomeButtonEnabled(true);
String input = getIntent().getStringExtra("stud_staff_ID");
Toast.makeText(this, input, Toast.LENGTH_SHORT).show();
listcomplaint = new ArrayList<HashMap<String, String>>();
new LoadAllComplaint().execute();
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
String location = ((TextView) view.findViewById(R.id.location)).getText()
.toString();
String picture = ((TextView) view.findViewById(R.id.picture)).getText()
.toString();
String input = getIntent().getStringExtra("stud_staff_ID");
Intent in = new Intent(getApplicationContext(),
ViewPage.class);
in.putExtra("location", location);
in.putExtra("picture", picture);
in.putExtra("stud_staff_ID", input);
in.putExtra("pid", pid);
startActivityForResult(in, 100);
}
});
}
public boolean onOptionsItemSelected(MenuItem item){
if(android.R.id.home == item.getItemId()){
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class LoadAllComplaint extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SenaraiSemuaComplaint.this);
pDialog.setMessage("Please wait, Loading Data...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
String input = getIntent().getStringExtra("stud_staff_ID");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("input", input));
JSONObject json = jParser.makeHttpRequest(url_listcomplaint, "GET", params);
Log.d("List Complaint: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
register = json.getJSONArray(TAG_REGISTER);
for (int i = 0; i < register.length(); i++) {
JSONObject c = register.getJSONObject(i);
// keep to variable
String pid = c.getString(TAG_PID);
String date = c.getString(TAG_DATE);
String status = c.getString(TAG_STATUS);
if (status.equals("Complaint in process."))
{
status.setImageResource(R.drawable.inprogress);
}
String location = c.getString("location");
String picture = c.getString("picture");
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_PID, pid);
map.put(TAG_DATE, date);
map.put(TAG_STATUS, status);
map.put("location", location);
map.put("picutre", picture);
listcomplaint.add(map);
}
} else {
runOnUiThread(new Runnable()
{
public void run(){
String msgs = "No complaint found, please create new complaint.";
Toast.makeText(getApplicationContext(), msgs, Toast.LENGTH_SHORT).show();
}
});
String i = getIntent().getStringExtra("stud_staff_ID");
Intent in12 = new Intent(getApplicationContext(),ComplaintBaru.class);
in12.putExtra("stud_staff_ID", i);
startActivity(in12);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
SenaraiSemuaComplaint.this, listcomplaint,
R.layout.list_pendaftaran, new String[] {TAG_PID,
TAG_DATE, TAG_STATUS, "location", "picture" },
new int[] {R.id.pid, R.id.inputDate, R.id.inputStatus, R.id.location, R.id.picture});
setListAdapter(adapter);
}
});
}
}
}
I suggest judging by what you want to achieve that handle this in your Adapter for the ListView which would be the adapter you supply to the ListActivity.
In the getView() of your adapter check the value of your TextView and then replace it with a ProgressBar either dynamically or by toggling its visibility by letting it reside in the layout for your rows.
it's require to take ImageView than set to Image
Imageview img=(ImageView)findViewById(R.id.yourimageID).setImageResource(R.drawable.inprogress);
So I'm stuck on this... I need to display images in a listview which gets its data from a json file.
I've already setup the connection, parsed the json file and displayed what i need. But somehow I can't find much information about how to turn a string (which has the URL) into an image in a listview.
The string which has the url is called "ImageLink"
Below is my MainActivity.
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get game info JSON
private static String url = "https://dl.dropboxusercontent.com/u/38379784/Upcoming%20Games/DataForUPG.js";
// JSON Node names
private static final String TAG_Games = "games";
private static final String TAG_Title = "Title";
private static final String TAG_Description = "Description";
private static final String TAG_Release = "Release";
private static final String TAG_ImageLink = "ImageLink";
// Gameinfo JSONArray
JSONArray games = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> GamesList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GamesList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String Title = ((TextView) view.findViewById(R.id.Title))
.getText().toString();
String Description = ((TextView) view.findViewById(R.id.Description))
.getText().toString();
String Release = ((TextView) view.findViewById(R.id.Release))
.getText().toString();
String ImageLink = ((TextView) view.findViewById(R.id.ImageLink_label))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleListItem.class);
in.putExtra(TAG_Title, Title);
in.putExtra(TAG_Description, Description);
in.putExtra(TAG_Release, Release);
in.putExtra(TAG_ImageLink, ImageLink);
startActivity(in);
}
});
// Calling async task to get json
new GetGames().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetGames extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading Data...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
games = jsonObj.getJSONArray(TAG_Games);
// looping through All games
for (int i = 0; i < games.length(); i++) {
JSONObject c = games.getJSONObject(i);
String Title = c.getString(TAG_Title);
String Description = c.getString(TAG_Description);
String Release = c.getString(TAG_Release);
String ImageLink = c.getString(TAG_ImageLink);
// tmp hashmap for single game
HashMap<String, String> games = new HashMap<String, String>();
// adding each child node to HashMap key => value
games.put(TAG_Title, Title);
games.put(TAG_Description, Description);
games.put(TAG_Release, Release);
games.put(TAG_ImageLink, ImageLink);
// adding contact to gameinfo list
GamesList.add(games);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, GamesList,
R.layout.list_item, new String[] { TAG_Title, TAG_Release,
TAG_Description, TAG_ImageLink }, new int[] { R.id.Title,
R.id.Release, R.id.Description, R.id.ImageLink_label });
setListAdapter(adapter);
}
}
}
I would appreciate any help
Well, you could probably create another async task to handle downloading the image like this:
private class DownloadImg extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
String TAG_ImageLink = params[0];
Bitmap bm = null;
try {
InputStream in = new java.net.URL(TAG_ImageLink).openStream();
bm = BitmapFactory.decodeStream(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm;
}
#Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
or you could use a 3rd party image loading library like picasso or volley's ImageRequest
i 'm working asynctask.i have two asynctas one activity.In first asynctask i use to parse json and show it in listview and second- to download images by position.
this is a my code
public class MainmoviesList extends Fragment implements
AdapterView.OnItemSelectedListener {
public final static String TAG = MainmoviesList.class.getSimpleName();
String imageurl = "**********";
public static List<ServerItems> arrayOfList;
private ProgressDialog pDialog2;
public static Gallery main_listview;
private AzercellMainPageAdapter objAdapter;
private RelativeLayout mSwitcher;
private CustomerStatistic cs;
private String Eng_Url = "*************"; // eng
public static int mPosition;
public static MainmoviesList newInstance() {
return new MainmoviesList();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.main_movies_list, container,
false);
mSwitcher = (RelativeLayout) rootView.findViewById(R.id.rootNode);
main_listview = (Gallery) rootView
.findViewById(R.id.horizontallistview);
main_listview.setOnItemSelectedListener(this);
main_listview.setSelection(mPosition);
arrayOfList = new ArrayList<ServerItems>();
cs = new CustomerStatistic();
cs.execute(Eng_Url);
return rootView;
}
private class CustomerStatistic extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setCancelable(false);
pDialog.show();
pDialog.setContentView(R.layout.custom_progressdialog);
}
#Override
protected String doInBackground(String... params) {
return Utils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
Globalclass.MovieServer = result;
JSONArray mainJson = new JSONArray(result);
for (int i = 0; i < mainJson.length(); i++) {
JSONObject objJson = mainJson.getJSONObject(i);
JSONObject cinema = objJson.getJSONObject("Cinemas");
JSONArray mainJson1 = cinema.getJSONArray("Cinemaname");
for (int j = 0; j < mainJson1.length(); j++) {
JSONObject objJson1 = mainJson1.getJSONObject(j);
Log.e("cinema name", objJson1.getString("cinemaName"));
}
ServerItems objItem = new ServerItems();
objItem.setImage(imageurl + objJson.getString("ipone_4"));
objItem.setTitle(objJson.getString("title"));
objItem.setYoutube(objJson.getString("youtube"));
objItem.setWritten(objJson.getString("written"));
objItem.setStars(objJson.getString("stars"));
objItem.setBlurimage(imageurl
+ objJson.getString("ipone_4_blur"));
arrayOfList.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
setAdapterToListview();
}
}
public void setAdapterToListview() {
// objAdapter = new AzercellMainPageAdapter(getApplicationContext(),
// R.layout.azercell_main_page_adapter, arrayOfList);
objAdapter = new AzercellMainPageAdapter(getActivity(),
R.layout.azercell_main_page_adapter, arrayOfList);
main_listview.setAdapter(objAdapter);
}
public void loadimagePosition(int pos) {
}
private void SendFlagIdToServer1(final int position) {
class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog2 = new ProgressDialog(getActivity());
pDialog2.setCancelable(false);
pDialog2.show();
pDialog2.setContentView(R.layout.custom_progressdialog);
}
#Override
protected String doInBackground(String... params) {
URL url;
try {
url = new URL(arrayOfList.get(position).getBlurimage());
Bitmap bmp = BitmapFactory.decodeStream(url
.openConnection().getInputStream());
Drawable drawable = new BitmapDrawable(bmp);
mSwitcher.setBackgroundDrawable(drawable);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pDialog2 != null) {
pDialog2.dismiss();
pDialog2 = null;
}
}
}
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
httpGetAsyncTask.execute();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
mPosition = position;
SendFlagIdToServer1(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
}
i have runtime exception.both asynctas classes runing same time?
it is a possible to run same asynctass in same time one activity?
if anyone knows solution please help me
thanks
I have a API which responds in JSON. When I clicked a button I am comfortably parse the JSON and implement it in the listview. The problem is When I go back to the previous activity and clicked the button once again I am getting the values repeat. i.e. previous values also, even I had called finish(); in on pause state of the listview activity. Following is my code.
Invoice Class
public class Invoice extends Activity{
public static ArrayList<HashMap<String, String>> ModuleName = new ArrayList<HashMap<String, String>>();
boolean tree = true;
ArrayList<String> KEY = new ArrayList<String>();
ListView mListView;
ProgressBar mProgress;
JSONObject json;
JSONArray Module_list = null;
Invoice_adapter adapter;
public static String KEY_SUCCESS = "success";
public static String KEY_ERROR = "error";
public static String KEY_ERROR_MSG = "error_msg";
public static String KEY_MODULELIST_MODULEHEADER = "moduleHeader";
public static String KEY_MODULELIST_MODULELIST = "moduleList";
public static String KEY_MODULELIST_DATAFOUND = "datafound";
public static String KEY_INVOICE_INVOICENO = "";
public static String KEY_INVOICE_SUBJECT = "";
public static String KEY_INVOICE_SALESORDER = "";
public static String KEY_INVOICE_STATUS = "";
public static String KEY_INVOICE_TOTAL = "";
public static String KEY_INVOICE_ASSIGNEDTO = "";
public static String KEY_INVOICE_RECORDID = "";
public static String KEY_INVOICE_ACTION = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_module_data);
mListView = (ListView) findViewById(R.id.module_list);
mProgress = (ProgressBar) findViewById(R.id.progressBar1);
try {
json = new ParseDATA().execute().get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
String data_found = json.getString(KEY_MODULELIST_DATAFOUND);
if (data_found.equals("Data Found!")){
JSONArray array = json.getJSONArray(KEY_MODULELIST_MODULELIST);
int count1 = array.length();
String Count1 = Integer.toString(count1);
Log.d("Count_array", Count1);
JSONObject keyarray = array.getJSONObject(0);
#SuppressWarnings("rawtypes")
Iterator temp = keyarray.keys();
while (temp.hasNext()) {
String curentkey = (String) temp.next();
KEY.add(curentkey);
}
Collections.sort(KEY, String.CASE_INSENSITIVE_ORDER);
KEY_INVOICE_ACTION = KEY.get(0);
KEY_INVOICE_ASSIGNEDTO = KEY.get(1);
KEY_INVOICE_INVOICENO = KEY.get(2);
KEY_INVOICE_RECORDID = KEY.get(3);
KEY_INVOICE_SALESORDER = KEY.get(4);
KEY_INVOICE_STATUS = KEY.get(5);
KEY_INVOICE_SUBJECT = KEY.get(6);
KEY_INVOICE_TOTAL = KEY.get(7);
Log.d("Parsing Json class", " ---- KEYS---- " + KEY);
Module_list = json.getJSONArray(KEY_MODULELIST_MODULELIST);
int count = Module_list.length();
String Count = Integer.toString(count);
Log.d("Count_Module_LIST", Count);
// looping through All Contacts
for(int i = 0; i < Module_list.length(); i++){
JSONObject c = Module_list.getJSONObject(i);
// Storing each json item in variable
String mAction = c.getString(KEY_INVOICE_ACTION);
String mAssignedTo = c.getString(KEY_INVOICE_ASSIGNEDTO);
String mInvoice = c.getString(KEY_INVOICE_INVOICENO);
String mRecordid = c.getString(KEY_INVOICE_RECORDID);
String mSalesorder = c.getString(KEY_INVOICE_SALESORDER);
String mStatus = c.getString(KEY_INVOICE_STATUS);
String mSubject = c.getString(KEY_INVOICE_SUBJECT);
String mTotal = c.getString(KEY_INVOICE_TOTAL);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_INVOICE_ACTION, mAction);
map.put(KEY_INVOICE_ASSIGNEDTO, mAssignedTo);
map.put(KEY_INVOICE_INVOICENO, mInvoice);
map.put(KEY_INVOICE_RECORDID, mRecordid);
map.put(KEY_INVOICE_SALESORDER, mSalesorder);
map.put(KEY_INVOICE_STATUS, mStatus);
map.put(KEY_INVOICE_SUBJECT, mSubject);
map.put(KEY_INVOICE_TOTAL, mTotal);
// adding HashList to ArrayList
ModuleName.add(map);
}
}else
{
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
return;
}
}
mProgress.setVisibility(View.INVISIBLE);
adapter = new Invoice_adapter(Invoice.this, ModuleName);
mListView.setAdapter(adapter);
mListView.setVisibility(View.VISIBLE);
//mListView.invalidateViews();
}
else
{
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ERROR, "Error");
ModuleName.add(map);
//JSONObject json_user = json.getJSONObject("user");
//error_message = json_user.getString(KEY_ERROR_MSG);
}
}catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Something went wrong.Please try again.!!", Toast.LENGTH_LONG).show();
}
}
class ParseDATA extends AsyncTask<Void, String,JSONObject >
{
ProgressDialog dialog = new ProgressDialog(Invoice.this);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setTitle("Loading");
dialog.setIndeterminate(true);
dialog.setMessage("Please wait");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected JSONObject doInBackground(
Void... params) {
// TODO Auto-generated method stub
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.getModuleList("1", "20", "Invoice");
return json;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
dialog.dismiss();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
Toast.makeText(getApplicationContext(), "PAUSE STATE", Toast.LENGTH_LONG).show();
finish();
}}
Adapter class
public class Invoice_adapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public Invoice_adapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return data.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.activity_module_data_detail, null);
TextView title = (TextView)vi.findViewById(R.id.textView1); // category title name
//ImageView moduleImage = (ImageView) vi.findViewById(R.id.recipe_image);
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
Log.i("list", ""+data.get(position));
//Log.i("list", data);
String ff = song.get(Invoice.KEY_INVOICE_SUBJECT);
title.setText(ff);
//moduleImage.setImageResource(mModuleImages[position]);
return vi;
}}
Please Help.. !! I dnt know what Is I am doing wrong.
Thanks in advance.
The problem is with the "static" key word for the ArrayList
public static ArrayList<HashMap<String, String>> ModuleName = new ArrayList<HashMap<String, String>>();
static variables are initialized only when the class is loaded, that means the value will be persisted till the end of the application process.
Either remove static keyword for array list or clear the array list before you load new data.
ModuleName.clear();
I am trying to learn populating data from the server to Listview.
I am new to android
MainActivity.java
public class MainActivity extends Activity {
// url to make request
private static String url = "http://URL:7002/";
private static String url1 = "http://URL:7002/XXX";
//private HashMap<Integer, String> TimeMap = new HashMap<Integer, String>();
List<Item> yourData = new ArrayList<Item>();
List<Item> yourData1 = new ArrayList<Item>();
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Instantiating ProgressDialog with onCreate method
progressDialog=new ProgressDialog(MainActivity.this);
new ParsingAsync().execute();
}
private class ParsingAsync extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog=ProgressDialog.show(MainActivity.this, "", "Please Wait", true, false);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Creating JSON Parser instance
JSONObjParser jParser = new JSONObjParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
// getting JSON string from URL
JSONArray json1 = jParser.getJSONFromUrl(url1);
try {
for (int i = 0; i < json1.length(); i++) {
JSONObject c = json1.getJSONObject(i);
// Storing each json item in variable
int id = c.getInt("_id");
String TIME = c.getString("RestaurantTime");
yourData1.add(new Item(TIME));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
for (int i = 0; i < json.length(); i++) {
JSONObject c = json.getJSONObject(i);
// Storing each json item in variable
String NAME=c.getString("restaurantNAME");
yourData.add(new Item(NAME));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressDialog.dismiss();
//TextView timedisplay=(TextView) findViewById(R.id.RestaurantTimeID);
ListView yourListView = (ListView) findViewById(R.id.listViewID);
ListAdapter customAdapter = new ListAdapter(MainActivity.this, R.layout.itemlistrow, yourData);
yourListView.setAdapter(customAdapter);
// remaining code
ListAdapter.java
public class ListAdapter extends ArrayAdapter<Item> {
private List<Item> items;
public ListAdapter(Context context, int resource, List<Item> items) {
super(context, resource, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
TextView tt = null;
TextView time=null;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.itemlistrow, null);
tt = (TextView) v.findViewById(R.id.RestaurantNameID);
time = (TextView) v.findViewById(R.id.RestaurantTimeID);
}
Item p = items.get(position);
if (p != null) {
if (tt != null) {
tt.setText(""+p.getName());
}
if (time != null) {
time.setText(""+p.getTime());
}
}
return v;
}
}
Item.java
public class Item{
private String Name;
private String Time;
public Item(String name){
this.Name = name;
}
public String getName(){
return Name;
}
public void Time(String time){
this.Time = time;
}
public String getTime(){
return Time;
}
}
How can i resolve this
I have posted required classes above
Using List for populating the data is i am looking at
Any ideas,
Thanks.
You set TIME to yourdata1 and NAME to yourdata. The objects of yourdata1 only contains TIME and the NAME is null. The objects of yourdata only contains NAME and the TIME is null.
Please set NAME and TIME in one object and store it in one List which will be passed to ListAdapter.
I hope you can understand me.
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Creating JSON Parser instance
JSONObjParser jParser = new JSONObjParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
// getting JSON string from URL
JSONArray json1 = jParser.getJSONFromUrl(url1);
// assume json's length is the same as json1's
try {
for (int i = 0; i < json1.length(); i++) {
JSONObject c = json1.getJSONObject(i);
Item item = new Item();
// Storing each json item in variable
int id = c.getInt("_id");
String TIME = c.getString("RestaurantTime");
item.setTime(TIME);
c = json.getJSONObject(i);
// Storing each json item in variable
String NAME=c.getString("restaurantNAME");
item.setName(NAME);
yourData.add(item);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
and
public class Item{
private String Name;
private String Time;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getTime() {
return Time;
}
public void setTime(String time) {
Time = time;
}
}