In the following code the setonitemclicklistener of listView not working. I don't know what is missing.
public class OffersActivity extends ListActivity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> offersList;
OfferAdapter offerAdapter;
JSONArray offers = null;
private static final String OFFER_URL = "My URL of PHP file";
static final String OFFER_ID = "offer_id";
static final String OFFER_CONTENT = "offer_content";
static final String OFFER_PHOTO = "offer_photo";
static final String OFFER_PHOTO_THUMB = "offer_photo_thumb";
static final String OFFER_INTERNAL_PHOTO = "offer_internal_photo";
static final String OFFER_INTERNAL_PHOTO_THUMB = "offer_internal_photo_thumb";
static final String OFFER_CREATED_DATE = "offer_created_date";
static final String OFFER_ORD = "offer_ord";
static final String OFFER_STATE = "offer_state";
static final String OFFER_LAST_UPDATE = "offer_last-update";
static final String OFFER_TITLE = "offer_title";
static final String OFFER_OLD_PRICE = "offer_old_price";
static final String OFFER_CURRENT_PRICE = "offer_current_price";
static final String OFFER_OCAZION = "offer_ocazion";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.offers_list);
offersList = new ArrayList<HashMap<String, String>>();
new LoadOffer().execute();
}
class LoadOffer extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(OffersActivity.this);
pDialog.setMessage(getResources().getString(R.string.loadOffers));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONArray jsonArray = jsonParser.makeHttpRequest(OFFER_URL, "GET",params);
JSONObject jsonObject = null;
Log.d("Offer JSON: ", jsonArray.toString());
try {
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
String offer_id = jsonObject.getString(OFFER_ID);
String offer_content = jsonObject.getString(OFFER_CONTENT);
String offer_photo = jsonObject.getString(OFFER_PHOTO);
String offer_photo_thumb = jsonObject.getString(OFFER_PHOTO_THUMB);
String offer_internal_photo = jsonObject.getString(OFFER_INTERNAL_PHOTO);
String offer_internal_photo_thumb = jsonObject.getString(OFFER_INTERNAL_PHOTO_THUMB);
String offer_created_date = jsonObject.getString(OFFER_CREATED_DATE);
String offer_ord = jsonObject.getString(OFFER_ORD);
String offer_state = jsonObject.getString(OFFER_STATE);
String offer_last_update = jsonObject.getString(OFFER_LAST_UPDATE);
String offer_title = jsonObject.getString(OFFER_TITLE);
String offer_old_price = jsonObject.getString(OFFER_OLD_PRICE);
String offer_current_price = jsonObject.getString(OFFER_CURRENT_PRICE);
String offer_ocazion = jsonObject.getString(OFFER_OCAZION);
HashMap<String, String> map = new HashMap<String, String>();
map.put(OFFER_ID, offer_id);
map.put(OFFER_CONTENT, offer_content);
map.put(OFFER_PHOTO, offer_photo);
map.put(OFFER_PHOTO_THUMB, offer_photo_thumb);
map.put(OFFER_INTERNAL_PHOTO, offer_internal_photo);
map.put(OFFER_INTERNAL_PHOTO_THUMB, offer_internal_photo_thumb);
map.put(OFFER_CREATED_DATE, offer_created_date);
map.put(OFFER_ORD, offer_ord);
map.put(OFFER_STATE, offer_state);
map.put(OFFER_LAST_UPDATE, offer_last_update);
map.put(OFFER_TITLE, offer_title);
map.put(OFFER_OLD_PRICE, offer_old_price);
map.put(OFFER_CURRENT_PRICE, offer_current_price);
map.put(OFFER_OCAZION, offer_ocazion);
offersList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
offerAdapter = new OfferAdapter(OffersActivity.this, offersList);
setListAdapter(offerAdapter);
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// not work..
Toast.makeText(OffersActivity.this, "Hello", Toast.LENGTH_SHORT).show();
// not work too..
System.out.println("Hello");
}
});
}
});
}
}
}
remove run thread .. crate one listview in xml
write below code
listView.setOnItemClickListener(this);
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
Related
I have two AsyncTasks (FetchDataFromApi , FetchDataFromDb) ,they both have an implementation for "onPostExecute" method each one of them starts DetailActivity by calling the passDataToDetailedActivity method .
whenever i start the DetailedActivity from the FetchFromApi onPostExecute method it works well ,
but the Whole problem is when i try to start the DetailedActivity from FetchFromDb onPostExecute method cuz some components of the DetailedActivity UI just doesn't appear and others do .
Please Help ,, thanks in advance :)
public class MainFragment extends Fragment {
public final static String API_KEY = "b932ba435fc93a5944938fe9d44cd198";
public final String BASE_URL = "http://api.themoviedb.org/3/discover/movie?sort_by=&api_key=";
ArrayList<Movie> movies = new ArrayList<>();
movieAdapter adapter;
GridView gridview;
DbOpenHelper dbOpenHelper;
ArrayList<Movie> FavList = new ArrayList<>();
public MainFragment() {
}
public MainFragment(String SortBy) {
if (SortBy == "fav") {
new FetchDataFromDb().execute();
} else {
new FetchDataFromApi(SortBy).execute();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
gridview = (GridView) getActivity().findViewById(R.id.gridView);
adapter = new movieAdapter(getActivity(), R.layout.movie_item, movies);
return view;
}
class FetchDataFromApi extends AsyncTask<String, Void, Boolean> {
String SORT_CATEGORY;
FetchDataFromApi(String paramUrl) {
SORT_CATEGORY = paramUrl;
}
#Override
protected Boolean doInBackground(String... params) {
HttpURLConnection urlConnection = null;
try {
Uri uriBuilder = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter("sort_by", SORT_CATEGORY)
.appendQueryParameter("api_key", API_KEY)
.build();
URL url = new URL(uriBuilder.toString());
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
String response = sb.toString();
ParseJsonData(response);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
gridview.setAdapter(adapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
PassDataToDetailedActivity(position);
}
});
}
private void ParseJsonData(String response) throws JSONException {
String PosterBaseUrl = "http://image.tmdb.org/t/p/";
String LargePoster = "w185";
String SmallPoster = "";
final String RESULTS = "results";
final String ORIGINAL_TITLE = "original_title";
final String OVERVIEW = "overview";
final String RELEASE_DATE = "release_date";
final String POSTER_PATH = "poster_path";
final String VOTE_AVERAGE = "vote_average";
final String POPULARITY = "popularity";
final String ID = "id";
JSONObject jsono = new JSONObject(response);
Log.v("Json", response);
JSONArray jarray = jsono.getJSONArray(RESULTS);
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
String id = object.getString(ID);
String title = object.getString(ORIGINAL_TITLE);
String releaseDate = object.getString(RELEASE_DATE);
String overView = object.getString(OVERVIEW);
String voteAverage = object.getString(VOTE_AVERAGE);
String popularity = object.getString(POPULARITY);
String posterPath = object.getString(POSTER_PATH);
String BigPoster = PosterBaseUrl + LargePoster + posterPath;
String MinPoster = PosterBaseUrl + SmallPoster + posterPath;
Movie m = new Movie();
m.setId(id);
m.setTitle(title);
m.setReleaseDate(releaseDate);
m.setOverView(overView);
m.setVoteAverage(voteAverage);
m.setPopularity(popularity);
m.setLargePoster(BigPoster);
m.setMinPoster(MinPoster);
movies.add(m);
}
}
}
private void PassDataToDetailedActivity(int position) {
String id = movies.get(position).getId();
String title = movies.get(position).getTitle();
String releaseDate = movies.get(position).getReleaseDate();
String overView = movies.get(position).getOverView();
String voteAverage = movies.get(position).getVoteAverage();
String popularity = movies.get(position).getPopularity();
String BigPoster = movies.get(position).getLargePoster();
String MinPoster = movies.get(position).getMinPoster();
Intent intent = new Intent(MainActivity.context, DetailedActivity.class);
intent.putExtra("id", id);
intent.putExtra("title", title);
intent.putExtra("releaseDate", releaseDate);
intent.putExtra("overView", overView);
intent.putExtra("voteAverage", voteAverage);
intent.putExtra("popularity", popularity);
intent.putExtra("MaxPoster", BigPoster);
intent.putExtra("MinPoster", MinPoster);
startActivity(intent);
}
public class FetchDataFromDb extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
dbOpenHelper = new DbOpenHelper(MainActivity.context);
movies.clear();
movies = dbOpenHelper.getAllFavoritePosters();
Log.v("database count", Integer.toString(FavList.size()));
return null;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
Log.v("database status", "Finished From Db");
adapter.notifyDataSetChanged();
gridview.setAdapter(adapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
PassDataToDetailedActivity(position);
}
});
}
}
}
Try this code:
Intent in = new Intent(getActivity(), Opening_Activtiy_Name().class);
getActivity().startActivity(in);
Note: Bring your gridListener out of that post execute method
I want to display the genre of the movie using tmdb api in android, but the thing is in tmdb api first we have to find out the genre id then we can display the genre name & I'm able to display the genre id but not the genre name. Please help me
Here is the MovieFragment.java file
public class MovieFragment extends Fragment {
public static final String LOG_TAG = MovieFragment.class.getSimpleName();
public static final int MOVIE_LOADER = 0;
private ImageAdapter imageAdapter;
public MovieFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
menuInflater.inflate(R.menu.menu_movie_list, menu);
super.onCreateOptionsMenu(menu, menuInflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
updateMovie();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
private void updateMovie() {
FetchMoviesTask moviesTask = new FetchMoviesTask(getActivity());
moviesTask.execute();
}
public void onStart() {
super.onStart();
updateMovie();
}
public class FetchMoviesTask extends AsyncTask<Void, Void, JSONObject[]> {
private final String LOG_TAG = FetchMoviesTask.class.getSimpleName();
private final String MESSAGE = "MovieDetails";
private final String GENRE_MESSAGE = "GenreDetails";
private final Context mContext;
public FetchMoviesTask(Context context) {
mContext = context;
}
private boolean DEBUG = true;
private ProgressDialog progress;
protected void onPreExecute() {
progress=new ProgressDialog(getActivity());
progress.show();
super.onPreExecute();
}
#Override
protected JSONObject[] doInBackground(Void... params) {
// URL for calling the API is needed
final String MOVIE_BASE_URL = "http://api.themoviedb.org/3/discover/movie?";
final String MOVIE_BASE_GENRE_URL = "http://api.themoviedb.org/3/genre/movie/list?";
//final String API_KEY = getString(R.string.API_KEY);
final String API_KEY = getString(R.string.API_KEY);
final String OWM_APIKEY = "api_key";
final String OWM_SORT_BY = "sort_by";
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String sort_by = prefs.getString(getString(R.string.pref_movie_key), getString(R.string.pref_sort_default_value));
//Built the uri
Uri builtUri = Uri.parse(MOVIE_BASE_URL).buildUpon()
.appendQueryParameter(OWM_APIKEY, API_KEY)
.appendQueryParameter(OWM_SORT_BY, sort_by)
.build();
//Built the genre url
Uri builtGenreUri = Uri.parse(MOVIE_BASE_GENRE_URL).buildUpon()
.appendQueryParameter(OWM_APIKEY, API_KEY)
.build();
String url = builtUri.toString();
String genreUrl = builtGenreUri.toString();
JSONParser jParser = new JSONParser();
JSONObject[] json = new JSONObject[2];
json[0] = jParser.getJSONFromUrl(url);
json[1] = jParser.getJSONFromUrl(genreUrl);
//JSONObject json = jParser.getJSONFromUrl(url);
return json; //the return value will be used by onPostExecute to update UI
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(final JSONObject[] json) {
progress.dismiss();
//JSON objects that need to be extracted
final String OWM_RESULT = "results";
final String OWM_ID = "id";
final String OWM_TITLE = "original_title";
final String OWM_SYNOPSIS = "overview";
final String OWM_POSTER_PATH = "poster_path";
final String OWM_RATING = "vote_average";
final String OWM_RELEASE_DATE = "release_date";
final String OWM_POPULARITY = "popularity";
final String OWM_GENRE = "genre_ids";
final String OWM_GENRES = "genres";
List<String> poster_paths = new ArrayList<String>();
List<String> genreIds = new ArrayList<String>();
List<String> genreNames = new ArrayList<String>();
JSONArray movies_list_array;
JSONArray genres_list_array;
if(json != null) {
try {
movies_list_array = json[0].getJSONArray(OWM_RESULT);
genres_list_array = json[1].getJSONArray(OWM_GENRES);
for (int i = 0; i < movies_list_array.length(); i++) {
JSONObject movie = movies_list_array.getJSONObject(i);
poster_paths.add(movie.getString(OWM_POSTER_PATH));
}
for (int j = 0; j < genres_list_array.length(); j++) {
JSONObject genre = genres_list_array.getJSONObject(j);
genreIds.add(genre.getString(OWM_ID));
genreNames.add(genre.getString("name"));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Error parsing JSON:", e);
}
GridView gridview = (GridView) getActivity().findViewById(R.id.movies_list_grid);
gridview.setAdapter(new ImageAdapter(getActivity(), poster_paths));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
try {
JSONObject movieDetails = json[0].getJSONArray(OWM_RESULT).getJSONObject(position);
JSONObject genreDetails = json[1].getJSONArray(OWM_GENRES).getJSONObject(position);
Intent intent = new Intent(getActivity(), DetailActivity.class)
.putExtra(MESSAGE, movieDetails.toString())
.putExtra(GENRE_MESSAGE, genreDetails.toString());
startActivity(intent);
} catch (JSONException e) {
Log.e(LOG_TAG, "Error parsing json", e);
}
}
});
} else {
try {
AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
alertDialog.setTitle("Info");
alertDialog.setMessage("Internet not available, Cross check your internet connectivity and try again");
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
catch(Exception e)
{
Log.d(LOG_TAG, "Show Dialog: "+e.getMessage());
}
}
}
}
}
And here is the DetailFragment file
public class DetailFragment extends Fragment {
private static final String LOG_TAG = DetailFragment.class.getSimpleName();
private static final int DETAIL_LOADER = 0;
private static final String MESSAGE = "MovieDetails";
private static final String GENRE_MESSAGE = "GenreDetails";
static final String DETAIL_URI = "URI";
private Uri mUri;
//SharedPreference sharedPreference;
final String OWM_TITLE = "original_title";
final String OWM_POSTER = "poster_path";
final String OWM_RELEASE_DATE = "release_date";
final String OWM_SYNOPSIS = "overview";
final String OWM_RATING = "vote_average";
final String OWM_ID = "id";
final String OWM_GENRE_ID = "genre_ids";
final String OWM_GENRES = "genres";
//final String API_KEY = getString(R.string.API_KEY);
public DetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
Intent intent = getActivity().getIntent();
String jsonString = intent.getStringExtra(MESSAGE);
String genreString = intent.getStringExtra(GENRE_MESSAGE);
try {
final JSONObject jObj = new JSONObject(jsonString);
final JSONObject genreObj = new JSONObject(genreString);
TextView movieTitle = (TextView) rootView.findViewById(R.id.movie_title);
movieTitle.setText(jObj.getString(OWM_TITLE));
ImageView moviePoster = (ImageView) rootView.findViewById(R.id.movie_poster);
String basepath = "http://image.tmdb.org/t/p/w185/";
String relativePath = jObj.getString(OWM_POSTER);
Glide.with(getActivity()).load(basepath+relativePath).into(moviePoster);
TextView movieRating = (TextView) rootView.findViewById(R.id.movie_rating);
Float rating = Float.valueOf(jObj.getString(OWM_RATING));
movieRating.setText("Rating: " + rating + "/10");
RatingBar ratingBar = (RatingBar) rootView.findViewById(R.id.rating_bar);
ratingBar.setRating(rating);
TextView movieSynopsis = (TextView) rootView.findViewById(R.id.movie_synopsis);
movieSynopsis.setText(jObj.getString(OWM_SYNOPSIS));
TextView movieReleaseDate = (TextView) rootView.findViewById(R.id.movie_release_date);
movieReleaseDate.setText(jObj.getString(OWM_RELEASE_DATE));
TextView movieGenres = (TextView) rootView.findViewById(R.id.genres);
JSONArray jArray = jObj.getJSONArray(OWM_GENRE_ID);
StringBuilder builder = new StringBuilder();
//List<String> returnList = new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++) {
String val = jArray.getString(i);
builder.append(val + " ");
//returnList.add(val);
movieGenres.setText(builder.toString());
}
String date = (String) movieReleaseDate.getText().toString();
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date convertedDate = formatter.parse(date);
SimpleDateFormat postFormatter = new SimpleDateFormat("yyyy MMM dd");
String finalDate = postFormatter.format(convertedDate);
movieReleaseDate.setText(finalDate);
//String finalDate = formatter("YYYY MMM DD").format(convertedDate);
} catch(ParseException e) {
Log.e(LOG_TAG, "Error Parsing Date: ", e);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Error Parsing JSON: ", e);
}
return rootView;
}
}
So, how to solve this problem as I got stuck & not able to find any ways. So, how to fetch the genre names using tmdb api as I am using this api. Please help
You have to map your genre_ids with the Genres List you can get from here: https://developers.themoviedb.org/3/genres/get-movie-list. I hope i could help you :)
(data["results"][0]["genre_ids"] is my List of genres in this example)
Here is my Code:
const genresRes = await fetch("https://api.themoviedb.org/3/genre/" + data["results"][0]["media_type"] + "/list?api_key=de51817441f3aca4f2ec89ee99f6c68c&language=en-US");
const genresData = await genresRes.json();
let genresThing = genresData["genres"]
let genresHash = {};
for (let i in genresThing){
genresHash[genresThing[i]["id"]] = genresThing[i]["name"]
}
let genres = ""
for (let i in data["results"][0]["genre_ids"]){
genres += genresHash[data["results"][0]["genre_ids"][i]] + ", ";
}
this.dataNow.genres = genres
console.log(this.dataNow.genres)
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);
I want to display the loading process when moving activity
This is my java file, where I have to put the function to process my application loading while loading data
public class tehni extends ListActivity {
TextView txt1;
private static String link_url = "http://192.168.32.1/pln/android/berita/tehnik1.php?kode=";
private static final String AR_ID = "id";
private static final String AR_JUDUL = "judul";
private static final String AR_CONTENT = "content";
JSONArray artikel = null;
ArrayList<HashMap<String, String>> daftar_artikel = new ArrayList<HashMap<String, String>>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tehni);
JSONParserberita jParser = new JSONParserberita();
JSONObject json = jParser.AmbilJson(link_url + user_name);
try {
artikel = json.getJSONArray("artikel");
for (int i = 0; i < artikel.length(); i++) {
JSONObject ar = artikel.getJSONObject(i);
String id = ar.getString(AR_ID);
String judul = "ID LAPORAN =" + ar.getString(AR_JUDUL);
String content = "STATUS="
+ ar.getString(AR_CONTENT).substring(0, 6);
HashMap<String, String> map = new HashMap<String, String>();
map.put(AR_ID, id);
map.put(AR_JUDUL, judul);
map.put(AR_CONTENT, content);
daftar_artikel.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
this.adapter_listview();
}
}
AsyncTask is an abstract class provided by Android which helps us to use the UI thread properly. This class allows us to perform long/background operations and show its result on the UI thread without having to manipulate threads.
Try to use AsynchTask
public class tehni extends ListActivity {
TextView txt1;
private static String link_url = "http://192.168.32.1/pln/android/berita/tehnik1.php?kode=";
private static final String AR_ID = "id";
private static final String AR_JUDUL = "judul";
private static final String AR_CONTENT = "content";
JSONArray artikel = null;
ArrayList<HashMap<String, String>> daftar_artikel = new ArrayList<HashMap<String, String>>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tehni);
new task ().execute();
}
class task extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDlg.setMessage("Loading...");
pDlg.setCancelable(false);
pDlg.setTitle(getResources().getString(R.string.app_name));
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected String doInBackground(String... params) {
JSONParserberita jParser = new JSONParserberita();
JSONObject json = jParser.AmbilJson(link_url + user_name);
try {
artikel = json.getJSONArray("artikel");
for (int i = 0; i < artikel.length(); i++) {
JSONObject ar = artikel.getJSONObject(i);
String id = ar.getString(AR_ID);
String judul = "ID LAPORAN =" + ar.getString(AR_JUDUL);
String content = "STATUS="
+ ar.getString(AR_CONTENT).substring(0, 6);
HashMap<String, String> map = new HashMap<String, String>();
map.put(AR_ID, id);
map.put(AR_JUDUL, judul);
map.put(AR_CONTENT, content);
daftar_artikel.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDlg.dismiss();
this.adapter_listview();
}
}
Try to use AsyncTask for web service calls. Refer it fore more details developer.android.com/reference/android/os/AsyncTask.html
public class tehni extends ListActivity {
TextView txt1;
private static String link_url = "http://192.168.32.1/pln/android/berita/tehnik1.php?kode=";
private static final String AR_ID = "id";
private static final String AR_JUDUL = "judul";
private static final String AR_CONTENT = "content";
JSONArray artikel = null;
ArrayList<HashMap<String, String>> daftar_artikel = new ArrayList<HashMap<String, String>>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tehni);
new ServiceCallTask().execute();
this.adapter_listview();
}
class ServiceCallTask extends AsyncTask<String, String, String>
{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog=new ProgressDialog(tehni.this, android.R.style.Theme_Translucent_NoTitleBar);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
JSONParserberita jParser = new JSONParserberita();
JSONObject json = jParser.AmbilJson(link_url + user_name);
artikel = json.getJSONArray("artikel");
for (int i = 0; i < artikel.length(); i++) {
JSONObject ar = artikel.getJSONObject(i);
String id = ar.getString(AR_ID);
String judul = "ID LAPORAN =" + ar.getString(AR_JUDUL);
String content = "STATUS="
+ ar.getString(AR_CONTENT).substring(0, 6);
HashMap<String, String> map = new HashMap<String, String>();
map.put(AR_ID, id);
map.put(AR_JUDUL, judul);
map.put(AR_CONTENT, content);
daftar_artikel.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(progressDialog!=null)
progressDialog.dismiss();
this.adapter_listview();
}
}
}
Given that you will receive a NetworkOnMainTheadException if running a HTTP request on the UI thread, I will assume that your request is within jParser.AmbilJson().
So, the best approach is to use the methods of AsyncTask like onPreExecute and onPostExecute to display the result in a ProgressBar.
I am fetching JSON from URL using AsycTask, parsing it and displaying the data onto the listView. I also click the refresh button to once again fetch the JSON from URL for some updating. When i click the refresh button the following takes place;
1) adapter.clear() : clearing the listView's adapter to populate the new data.
2) Fetch JSON from url, parse and display the newly fetched data onto the listView.
3) Meanwhile when fetching the data, I show a progress dialog.
But when i click on the refresh button, the main UI thread freezes during the execution of AsynTask. I mean the refresh button looks pressed until the AsynTask finishes the job as shown below.
Here is my code:
public class AndroidJSONParsingActivity extends SherlockActivity {
// JSON Node names
ArrayList<HashMap<String, String>> placeList = new ArrayList<HashMap<String, String>>();
private static final String TAG_PLACES = "places";
private static final String TAG_PLACE_NAME = "name";
private static final String TAG_PLACE_CATEGORY = "category";
private static final String TAG_PLACE_DISTANCE = "distance";
private static final String TAG_TRAVEL_TIME = "travel_time";
ListAdapter adapter;
public static Context con;
JSONArray places = null;
ListView list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
con = this;
list = (ListView) findViewById(R.id.listView1);
parseJSON();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
MenuItem menu_item1 = menu.findItem(R.id.menu_item1);
menu_item1.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplicationContext(), "refresh",
Toast.LENGTH_LONG).show();
placeList.clear();
parseJSON();
return false;
}
});
return true;
}
public void parseJSON() {
try {
placeList = new JSONParsingTask().execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
adapter = new SimpleAdapter(this, placeList, R.layout.list_item,
new String[] { TAG_PLACE_NAME, TAG_PLACE_CATEGORY,
TAG_PLACE_DISTANCE, TAG_TRAVEL_TIME }, new int[] {
R.id.name, R.id.category, R.id.distance,
R.id.travel_time });
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String category = ((TextView) view.findViewById(R.id.category))
.getText().toString();
String distance = ((TextView) view.findViewById(R.id.distance))
.getText().toString();
String travel_time = ((TextView) view
.findViewById(R.id.travel_time)).getText().toString();
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(TAG_PLACE_NAME, name);
in.putExtra(TAG_PLACE_CATEGORY, category);
in.putExtra(TAG_PLACE_DISTANCE, distance);
in.putExtra(TAG_TRAVEL_TIME, travel_time);
startActivity(in);
}
});
}
}
class JSONParsingTask extends
AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
public Boolean flag = false;
private static String url = "http://some - url";
// JSON Node names
private static final String TAG_PLACES = "places";
private static final String TAG_PLACE_NAME = "name";
private static final String TAG_PLACE_CATEGORY = "category";
private static final String TAG_PLACE_DISTANCE = "distance";
private static final String TAG_TRAVEL_TIME = "travel_time";
ListAdapter adapter;
JSONParser jParser;
ListView list;
static ArrayList<HashMap<String, String>> placeList = new ArrayList<HashMap<String, String>>();
JSONArray places = null;
ProgressDialog JSONParsingDialog = new ProgressDialog(
AndroidJSONParsingActivity.con);
#Override
protected void onPreExecute() {
JSONParsingDialog.setMessage("Preparing data...");
JSONParsingDialog.setCanceledOnTouchOutside(false);
JSONParsingDialog.setCancelable(false);
JSONParsingDialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
final JSONObject json = jParser.getJSONFromUrl(url);
try {
places = json.getJSONArray(TAG_PLACES);
for (int i = 0; i < places.length(); i++) {
JSONObject c = places.getJSONObject(i);
String name = c.getString(TAG_PLACE_NAME);
String category = c.getString(TAG_PLACE_CATEGORY);
String distance = c.getString(TAG_PLACE_DISTANCE);
String travel_time = c.getString(TAG_TRAVEL_TIME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_PLACE_NAME, name);
map.put(TAG_PLACE_CATEGORY, category);
map.put(TAG_PLACE_DISTANCE, distance);
map.put(TAG_TRAVEL_TIME, travel_time);
placeList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return placeList;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
JSONParsingDialog.dismiss();
}
}
All i need is, when i click on the refresh button, it should be smooth and should not freeze until the AsynTask is completed. Any idea how can i do this?
use
new JSONParsingTask().execute();
.get() blocks the caller thread.
more info: Looking for good example of using get() with an AsyncTask in android
Try it like this:
public class AndroidJSONParsingActivity extends SherlockActivity {
// JSON Node names
ArrayList<HashMap<String, String>> placeList = new ArrayList<HashMap<String, String>>();
private static final String TAG_PLACES = "places";
private static final String TAG_PLACE_NAME = "name";
private static final String TAG_PLACE_CATEGORY = "category";
private static final String TAG_PLACE_DISTANCE = "distance";
private static final String TAG_TRAVEL_TIME = "travel_time";
ListAdapter adapter;
public static Context con;
JSONArray places = null;
ListView list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
con = this;
list = (ListView) findViewById(R.id.listView1);
fetchJSON();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
MenuItem menu_item1 = menu.findItem(R.id.menu_item1);
menu_item1.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(getApplicationContext(), "refresh",
Toast.LENGTH_LONG).show();
placeList.clear();
parseJSON();
return false;
}
});
return true;
}
public void fecthJson(){
new JSONParsingTask().execute();
}
public void parseJSON(ArrayList<Hashmap<String, String>> dataList) {
adapter = new SimpleAdapter(this, dataList, R.layout.list_item,
new String[] { TAG_PLACE_NAME, TAG_PLACE_CATEGORY,
TAG_PLACE_DISTANCE, TAG_TRAVEL_TIME }, new int[] {
R.id.name, R.id.category, R.id.distance,
R.id.travel_time });
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String category = ((TextView) view.findViewById(R.id.category))
.getText().toString();
String distance = ((TextView) view.findViewById(R.id.distance))
.getText().toString();
String travel_time = ((TextView) view
.findViewById(R.id.travel_time)).getText().toString();
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(TAG_PLACE_NAME, name);
in.putExtra(TAG_PLACE_CATEGORY, category);
in.putExtra(TAG_PLACE_DISTANCE, distance);
in.putExtra(TAG_TRAVEL_TIME, travel_time);
startActivity(in);
}
});
}
}
class JSONParsingTask extends
AsyncTask<Void, Void, ArrayList<HashMap<String, String>>> {
public Boolean flag = false;
private static String url = "http://some - url";
// JSON Node names
private static final String TAG_PLACES = "places";
private static final String TAG_PLACE_NAME = "name";
private static final String TAG_PLACE_CATEGORY = "category";
private static final String TAG_PLACE_DISTANCE = "distance";
private static final String TAG_TRAVEL_TIME = "travel_time";
ListAdapter adapter;
JSONParser jParser;
ListView list;
static ArrayList<HashMap<String, String>> placeList = new ArrayList<HashMap<String, String>>();
JSONArray places = null;
ProgressDialog JSONParsingDialog = new ProgressDialog(
AndroidJSONParsingActivity.con);
#Override
protected void onPreExecute() {
JSONParsingDialog.setMessage("Preparing data...");
JSONParsingDialog.setCanceledOnTouchOutside(false);
JSONParsingDialog.setCancelable(false);
JSONParsingDialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
final JSONObject json = jParser.getJSONFromUrl(url);
try {
places = json.getJSONArray(TAG_PLACES);
for (int i = 0; i < places.length(); i++) {
JSONObject c = places.getJSONObject(i);
String name = c.getString(TAG_PLACE_NAME);
String category = c.getString(TAG_PLACE_CATEGORY);
String distance = c.getString(TAG_PLACE_DISTANCE);
String travel_time = c.getString(TAG_TRAVEL_TIME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_PLACE_NAME, name);
map.put(TAG_PLACE_CATEGORY, category);
map.put(TAG_PLACE_DISTANCE, distance);
map.put(TAG_TRAVEL_TIME, travel_time);
placeList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return placeList;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
JSONParsingDialog.dismiss();
placeList = result;
parseJson(result);
}
}