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
Related
After Clicking an Item in my List view, my Single Item View should appear. Unfortunately every time i click on one of the two items just the same content appears. How can i fix the problem and the right content will be shown?
First i get parse data in my Main Activity:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<productforloc> arrayList;
ListView lv;
private String TAG = MainActivity.class.getSimpleName();
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
int i = 1;
private ProgressDialog pDialog;
String name;
String image;
String street;
String postalcode;
String musicstyle;
String musicsecond;
String entry;
String opening;
String agegroup;
String urlbtn;
String Fsk;
String city;
// URL to get contacts JSON
private static String url = "http://partypeople.bplaced.net/maptest.json";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener((AdapterView.OnItemClickListener) this);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
final Button popbutton = (Button) findViewById(R.id.popbutton);
popbutton.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View v) {
if (i == 1) {
if (popbutton.isPressed()) {
popbutton.setBackground(getResources().getDrawable(R.drawable.secondbg));
arrayList.clear();
url = "http://partypeople.bplaced.net/justpop.json";
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
i = i + 1;
}
} else {
if (popbutton.isPressed()) {
popbutton.setBackground(getResources().getDrawable(R.drawable.bg_popbutton));
arrayList.clear();
url = "http://partypeople.bplaced.net/maptest.json";
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
i = i - 1;
}
}
}
});
}
class ReadJSON extends AsyncTask<String,Integer,String>{
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
if (pDialog.isShowing())
pDialog.dismiss();
try{
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
arrayList.add(new productforloc(
image= po.getString("imageurl"),
name = po.getString("name"),
street = po.getString("street"),
postalcode = po.getString("postalcode"),
musicstyle = po.getString("musicstyle"),
musicsecond = po.getString("musicsecond"),
entry = po.getString("entry"),
opening = po.getString("opening"),
agegroup = po.getString("agegroup"),
urlbtn = po.getString("urlbtn"),
Fsk = po.getString("Fsk"),
city = po.getString("city")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
CustomListAdapterforloc adapter = new CustomListAdapterforloc(getApplicationContext(),R.layout.model,arrayList);
lv.setAdapter(adapter);
}
}
private String readURL(String url){
StringBuilder content = new StringBuilder();
try{
URL uri = new URL(url);
URLConnection urlConnection = uri.openConnection();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) !=null){
content.append(line+"\n");
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",name);
intent.putExtra("imageurl",image);
intent.putExtra("street",street);
intent.putExtra("postalcode",postalcode);
intent.putExtra("musicstyle",musicstyle);
intent.putExtra("musicsecond",musicsecond);
intent.putExtra("entry",entry);
intent.putExtra("opening",opening);
intent.putExtra("agegroup",agegroup);
intent.putExtra("urlbtn",urlbtn);
intent.putExtra("Fsk",Fsk);
intent.putExtra("city",city);
startActivity(intent);
Toast.makeText(getApplicationContext(),street,Toast.LENGTH_LONG).show();
}
/**
* Async task class to get json by making HTTP call
}
*/
}
Then as you can see in the bottom the content will be sent to the detailactivity, but i always get the content from the second item in my json even if i click on the first item.
Change your onItemClick method to get the right object from your list.
Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productforloc pForloc = arrayList.get(positon);
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",pForloc.getName());
intent.putExtra("imageurl",pForloc.getImage());
intent.putExtra("street",pForloc.getStreet());
intent.putExtra("postalcode",pForloc.getPostalcode());
intent.putExtra("urlbtn",pForloc.getUrlbtn());
intent.putExtra("Fsk",pForloc.getFsk());
intent.putExtra("city",pForloc.getCity());
startActivity(intent);
Toast.makeText(getApplicationContext(),street,Toast.LENGTH_LONG).show();
}
I am displaying hotels in listview with checkbox,image and text. when user click on checkbox then put that checked hotel_id into bundle. And pass to it's super class.
When i am selected hotels and click on button on main activity my logcat shows NullPointerException. I will check my code with debugger. I can find getting Bundle=null. So please help to find the hotel_id when click's on checkbox and send that all selected hotel_id to its main Activity.
Here is my ListViewAdapter class.
public class ListViewAdapter extends BaseAdapter {
Context context;
LayoutInflater inflater;
ArrayList<Product> AllMenu = new ArrayList<>();
ImageLoader imageLoader;
int checkCounter = 0;
public ListViewAdapter(Context context, ArrayList<Product> itemlist) {
this.context = context;
AllMenu = itemlist;
imageLoader = new ImageLoader(context);
checkCounter = 0;
}
public int getCount() {
return AllMenu.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position, final View convertView, final ViewGroup parent) {
// Declare Variables
final Product tempMenu = AllMenu.get(position);
final CheckBox c;
final ImageView image_path;
final TextView name, location, desc;
final Bundle b = new Bundle();
final Intent intent = new Intent(context.getApplicationContext(),Hotels.class);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = inflater.inflate(R.layout.viewpage, parent, false);
// Get the position
c = (CheckBox) view.findViewById(R.id.mycheckbox);
name = (TextView) view.findViewById(R.id.fh_name);
location = (TextView) view.findViewById(R.id.fh_loc);
desc = (TextView) view.findViewById(R.id.fh_desc);
image_path = (ImageView) view.findViewById(R.id.image_all_main);
c.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (c.isChecked() && checkCounter >= 3) {
AllMenu.get(position).setSelected(false);
c.setChecked(false);
Toast.makeText(context, "You can select max 3 hotels!!", Toast.LENGTH_SHORT).show();
} else {
Product p = (AllMenu).get(position);
p.setSelected(c.isChecked());
if (c.isChecked()) {
checkCounter++;
} else {
checkCounter--;
}
}
StringBuffer responseText = new StringBuffer();
responseText.append("The following were selected...");
ArrayList<Product> p = AllMenu;
for (int i = 0; i < p.size(); i++) {
Product pp = p.get(i);
if (pp.isSelected()) {
//here is i want hotel id when i am cliked on hotel.
//and save it into bundle and i am get bundle into it's super class
String[] h = new String[0];
b.putStringArray(String.valueOf(pp.getId()),hid);
intent.putExtras(b);
//Here is how i can pass custom object to string
responseText.append("\n" + pp.getName() + "\t");
responseText.append("\t" + pp.getLocation());
}
}
Toast.makeText(context, responseText, Toast.LENGTH_SHORT).show();
}
});
c.setTag(tempMenu);
c.setChecked(tempMenu.isSelected());
name.setText(tempMenu.getName());
location.setText(tempMenu.getLocation());
desc.setText(tempMenu.getDescription().trim());
imageLoader.DisplayImage(tempMenu.getImage_path(), image_path);
return view;
}
}
And i will get that bundle into this Hotels.class
Here is my Hotels.class
public class Hotels extends Activity
{
// Declare Variables
JSONArray jsonarray = null;
private static final String TAG_ID= "id";
public static final String TAG_NAME = "name";
public static final String TAG_LOCATION = "location";
public static final String TAG_DESC = "description";
String f_date,l_date;
int[] hotel_id = new int[0];
ProgressDialog loading;
ListView list;
Button booknow;
ListViewAdapter adapter;
private ArrayList<Product> itemlist;
Product product;
static String Array = "MyHotels";
View view;
CheckBox click;
String hotel = "http://app.goholidays.info/getHotelData.php";
String booking = "http://app.goholidays.info/insertIntoBooking.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_item_layout);
product = new Product();
itemlist = new ArrayList<Product>();
new ReadJSON().execute();
click = (CheckBox) findViewById(R.id.mycheckbox);
booknow = (Button) findViewById(R.id.bookhotel);
product = new Product();
list = (ListView) findViewById(R.id.myimagelist);
Calendar c = Calendar.getInstance();
System.out.println("Current time => "+c.getTime());
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Hotels.this);
SharedPreferences.Editor editor = sp.edit();
final String user_id = sp.getString("id", TAG_ID);
final String start_date = sp.getString("start_date", f_date);
final String end_date = sp.getString("end_date", l_date );
final String chk_status = df.format(c.getTime());
booknow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//here i want get all selected hotel_id into bundle.
//And i want pass that hotel_id to my database.
Bundle bundle = getIntent().getExtras();
String[] hotel_id = bundle.getStringArray(String.valueOf(product.getId()));
Submit(start_date,end_date,hotel_id,chk_status,user_id);
}
});
}
class ReadJSON extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Hotels.this,"Fetching Data","Please wait...",false,false);
}
#Override
protected String doInBackground(String... args) {
Product tempMenu;
try {
JSONObject jsonobject = JSONfunctions.getJSONfromURL(hotel);
jsonarray = jsonobject.optJSONArray(Array);
//parse date for dateList
for (int i = 0; i < jsonarray.length(); i++) {
tempMenu = new Product();
jsonobject = jsonarray.getJSONObject(i);
tempMenu.setId(jsonobject.getInt("hotel_id"));
tempMenu.setName(jsonobject.getString("name"));
tempMenu.setLocation(jsonobject.getString("location"));
tempMenu.setImage_path(jsonobject.getString("image_name"));
tempMenu.setDescription(jsonobject.getString("description"));
tempMenu.setFacility1(jsonobject.getString("facility1"));
tempMenu.setFacility2(jsonobject.getString("facility2"));
tempMenu.setFacility3(jsonobject.getString("facility3"));
tempMenu.setFacility4(jsonobject.getString("facility4"));
tempMenu.setStar(jsonobject.getString("star"));
itemlist.add(tempMenu);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
adapter = new ListViewAdapter(Hotels.this, itemlist);
list.setAdapter(adapter);
loading.dismiss();
}
}
private void Submit(final String start_date, final String end_date, final String[] hotel_id, final String chk_status, final String user_id) {
class BackTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String start_dtae = params[0];
String end_date = params[1];
String hotel_id = params[2];
String user_id = params[3];
String chk_status = params[4];
try {
URL url = new URL(booking);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
String data = URLEncoder.encode("start_date", "UTF-8") +"="+URLEncoder.encode(start_dtae, "UTF-8") + "&" +
URLEncoder.encode("end_date", "UTF-8") +"="+URLEncoder.encode(end_date, "UTF-8") + "&" +
URLEncoder.encode("hotel_id", "UTF-8") +"="+URLEncoder.encode(hotel_id, "UTF-8") + "&" +
URLEncoder.encode("user_id", "UTF-8") +"="+URLEncoder.encode(user_id, "UTF-8") + "&" +
URLEncoder.encode("chk_status", "UTF-8") +"="+URLEncoder.encode(chk_status, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
os.close();
InputStream is = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
String responce = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
responce += line;
}
bufferedReader.close();
is.close();
httpURLConnection.disconnect();
return responce;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(),"Book Success"+result,Toast.LENGTH_SHORT).show();
}
}
BackTask lg=new BackTask();
lg.execute(start_date, end_date, chk_status, String.valueOf(hotel_id), user_id);
}
}
My custom object class is here.
public class Product extends HashMap<String, String> {
private String name;
private int hotel_id;
private String description;
private String location;
private String image_path;
boolean selected;
public boolean isSelected(){
return selected;
}
public void setSelected(boolean selected){
this.selected = selected;
}
public void setId (int hotel_id) { this.hotel_id = hotel_id;}
public int getId() {
return hotel_id;
}
public void setName (String name) { this.name = name;}
public String getName() {
return name;
}
public void setLocation(String location) {
this.location = location;
}
public String getLocation() {
return location;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setImage_path(String image_path) {
this.image_path = image_path;
}
public String getImage_path() {
return image_path;
}
}
The problem is you are only putting data to intent. It is just worth if You put bundle or data inside intent object with using startActivity.
If you want to get selected Hotel id's just make a public array like:-
public class Hotels extends Activity
{
public ArrayList<Integer> hotel_ids=new ArrayList<>();
}
and inside adapter while selecting check box put id in arrayList with the use of context as below and if unchecked remove hotel_id from that array list :-
c.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (c.isChecked() && checkCounter >= 3) {
AllMenu.get(position).setSelected(false);
c.setChecked(false);
Toast.makeText(context, "You can select max 3 hotels!!", Toast.LENGTH_SHORT).show();
} else {
Product p = (AllMenu).get(position);
p.setSelected(c.isChecked());
if (c.isChecked()) {
if(context instanceof Hotels){
((Hotels)context).hotel_ids.add(p.getId());
}
checkCounter++;
} else {
if(context instanceof Hotels){
((Hotels)context).hotel_ids.remove(p.getId());
}
checkCounter--;
}
}
}
}
It may help you out. With the above one you will always find selected Hotel_ids.
you can do something like this.
1> in getview method you can do checked listener like below
viewHolder.chkbox.setOnCheckedChangeListener(new CheckUpdateListener(itemList.get(position));
2> make new class for CheckUpdatelistener with argument constructor of model class
private final class CheckUpdateListener implements CompoundButton.OnCheckedChangeListener {
private final Product product;
private CheckUpdateListener(Product product) {
this.product = product;
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.i("onCheckedChanged", "isChecked: " + isChecked);
product.setChecked(isChecked);
notifyDataSetChanged();
}
}
3> in main activity on button click listener you can do code like this
Arraylist<Product> selectedProduct = new ArrayList<>();
if (itemList.size() > 0) {
for (int i = 0; i < itemList.size(); i++) {
if (itemList.get(i).isChecked()) {
try {
selectedProduct.add(itemList.get(i));
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
I am building this movie app that displays movies in a gridview on the main panel, then I can click them and display some information about that movie, also I have some settings to change the criteria of the movies displayed: popular, top rated or favorites. The favorites are a local collection saved in sharedPreferences chosen by the user.
Here is where it all happens:
public class MovieFragment extends Fragment{
public String[][] matrixMoviesInfo;
public GridView gridView;
public String[] mArrayImages;
private String baseUrl;
private String apiKey;
public MovieFragment(){
matrixMoviesInfo = new String[20][10];
mArrayImages = new String[20];
baseUrl = "http://api.themoviedb.org/3/movie/";
apiKey = "?api_key=37068e0a72b2cc1751b4246899923ba7";
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
gridView = (GridView) rootView.findViewById(R.id.gridview);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent intent = new Intent(getActivity(), DetailActivity.class)
.putExtra(Intent.EXTRA_TEXT, matrixMoviesInfo[position]);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
return rootView;
}
private void setImages() {
for(int i=0;i<mArrayImages.length;i++){
if(matrixMoviesInfo[i][0]!=null) {
mArrayImages[i] = matrixMoviesInfo[i][0];
}
}
gridView.setAdapter(null);
gridView.setAdapter(new ImageAdapter(getActivity(), mArrayImages));
Log.v(null, "SETIMAGESCALLED");
}
private void updateMovies() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String preference = prefs.getString(getString(R.string.pref_sortby_key), getString(R.string.pref_sortby_default));
if(preference.toLowerCase().equals("favorites")){
SharedPreferences preferences = getContext().getSharedPreferences("favorites_list", Context.MODE_PRIVATE);
Map<String, ?> allEntries = preferences.getAll();
String[] keyNames = new String[allEntries.size()];
Log.v(null,"SIZE: "+allEntries.size());
String[] keyValues;
int iterator=0;
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Log.v("KEY: " +entry.getKey(), "VALUE: "+entry.getValue().toString());
}
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
if(entry.getKey()!=null) {
keyNames[iterator] = entry.getKey();
keyValues = entry.getValue().toString().split("#");
for (int i = 0; i < 10; i++) {
Log.v("INDEX: " + i, " VALUES: " + keyValues[i]);
matrixMoviesInfo[iterator][i] = keyValues[i];
}
iterator++;
}
}
setImages();
}else{
Log.v(null,"EXECUTETASK");
new FetchMoviesTask().execute(baseUrl+preference.toLowerCase()+apiKey, "i");
}
}
#Override
public void onStart() {
super.onStart();
updateMovies();
}
public class FetchMoviesTask extends AsyncTask<String, String, Void> {
private final String LOG_TAG = FetchMoviesTask.class.getSimpleName();
private Void getMovieDetailsFromJson(String movieJSONstr) throws JSONException {
final String OWM_RESULTS = "results";
final String OWM_ID = "id";
final String OWM_POSTERPATH = "poster_path";
final String OWM_TITLE = "original_title";
final String OWM_OVERVIEW = "overview";
final String OWM_USERRATING = "vote_average";
final String OWM_RELEASEDATE = "release_date";
JSONObject movieJson = new JSONObject(movieJSONstr);
JSONArray movieArray = movieJson.getJSONArray(OWM_RESULTS);
for(int i = 0; i < movieArray.length(); i++) {
JSONObject movieObj = movieArray.getJSONObject(i);
matrixMoviesInfo[i][0] = movieObj.getString(OWM_POSTERPATH);
matrixMoviesInfo[i][1] = movieObj.getString(OWM_ID);
matrixMoviesInfo[i][2] = movieObj.getString(OWM_TITLE);
matrixMoviesInfo[i][3] = movieObj.getString(OWM_OVERVIEW);
matrixMoviesInfo[i][4] = movieObj.getString(OWM_USERRATING);
matrixMoviesInfo[i][5] = movieObj.getString(OWM_RELEASEDATE);
}
for(int i=0;i<20;i++) {
new FetchMoviesTask().execute(baseUrl + matrixMoviesInfo[i][1] + "/reviews" + apiKey, Integer.toString(i));
new FetchMoviesTask().execute(baseUrl + matrixMoviesInfo[i][1] + "/videos" + apiKey, "v");
}
Log.v(null,"GETMOVIEDETAILS");
return null;
}
private Void getMovieReviewsFromJson(String movieJSONstr, String position) throws JSONException{
int pos = Integer.parseInt(position);
final String OWM_RESULTS = "results";
final String OWM_AUTHOR = "author";
final String OWM_CONTENT = "content";
final String OWM_TOTALRESULTS = "total_results";
JSONObject movieJson = new JSONObject(movieJSONstr);
JSONArray movieArray = movieJson.getJSONArray(OWM_RESULTS);
int numberOfResults = Integer.parseInt(movieJson.getString(OWM_TOTALRESULTS));
if(numberOfResults >= 1) {
matrixMoviesInfo[pos][6] = movieArray.getJSONObject(0).getString(OWM_AUTHOR);
matrixMoviesInfo[pos][7] = movieArray.getJSONObject(0).getString(OWM_CONTENT);
}
if(numberOfResults > 1) {
matrixMoviesInfo[pos][8] = movieArray.getJSONObject(1).getString(OWM_AUTHOR);
matrixMoviesInfo[pos][9] = movieArray.getJSONObject(1).getString(OWM_CONTENT);
}
return null;
}
private Void getMovieVideosFromJson(String movieJSONstr){
return null;
}
#Override
protected Void doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String movieJSONstr = null;
try{
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if(inputStream == null){
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while((line = reader.readLine()) != null){
buffer.append(line + "\n");
}
if(buffer.length() == 0){
movieJSONstr = null;
}
movieJSONstr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
return null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MovieFragment", "Error closing stream", e);
}
}
}
try{
if(params[1].equals("i")){
Log.v(null,"EXECUTEGETMOVIEDETAILS");
return getMovieDetailsFromJson(movieJSONstr);
}
else {
if (params[1].equals("v")){
return getMovieVideosFromJson(movieJSONstr);}
else{
return getMovieReviewsFromJson(movieJSONstr, params[1]);}
}
}catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
String[] mArrayImages = new String[20];
for(int i=0;i<20;i++){
mArrayImages[i] = matrixMoviesInfo[i][0];
}
gridView.setAdapter(new ImageAdapter(getActivity(), mArrayImages));
Log.v(null, "IMAGES SET GRIDVIEW REFRESHED");
}
}
Class Explanation:
There is 2 paths:
Popular or TopRated: starts on method UpdateMovies, then executes the asynctask to fetch data from the api, followed by the execution of the getMoviesFromJson that extracts all the information related to all movies. Then it ends on onPostExecute that populates the gridview with the ImageAdapter.
Favorites: starts on method UpdateMovies, here it fetchs the data from sharedpreferences and populates the array with that data, then it calls the method setImages to populate the gridView with the ImageAdapter.
Here is my problem: when I am displaying the popular movies and change the setting to favorites, it displays the right movies on the sharedpreferences but it is not "cleaning" the remaining ones from the gridview.
Also how can I adjust the scroll of the gridview to match the cells it has (when there is no movie to populate a cell, I hide it like this:
imageView.setVisibility(View.GONE);
Make an Adapter for the gridview that extends from BaseAdapter, or use an Adapter that extends from BaseAdapter.
then call notifyDataSetChanged on that adapter when the contents of your collection has changed.
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 have an app that connects to server sends sql request and get JSON answer as JsonArray.
Its Asynktask in seperate class (HTTPRequest.java is my AsyncTask class, Responce.java its my callback interface class) and it works correct.
when I use it in OrderActivity.java like below
#Override //my interface class function
public void onPostExecute(JSONArray Result) {
load(Result);
}
private void load(JSONArray json) {
for(int i=0;i<json.length();i++){
try {
JSONObject jo = json.getJSONObject(i);
Product p = new Product(
jo.getInt("ID"),
jo.getInt("parent"),
jo.getInt("category"),
jo.getString("Item"),
jo.getDouble("Price")
);
products.add(p);
} catch (JSONException e) {
e.printStackTrace();
}
}
it does work and fills product with data, but when I assign to my class variable JSONArray json
JSONArray json = new JSONArray;
.
.
.
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
json is null
//HTTPRequest.java
public class HTTPRequest extends AsyncTask<String, Void, Integer> {
private Context context;
private Responce responce;
JSONArray json;
public HTTPRequest(Context context){
this.context = context;
responce = (Responce)context;
}
#Override
protected Integer doInBackground(String... params) {
OutputStream output;
InputStream inputStream = null;
HttpURLConnection connection = null;
String charset = "UTF-8";
Integer result = 0;
try {
URL uri = new URL(params[0]);
connection = (HttpURLConnection) uri.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "text/plain; charset=" + charset);
output = connection.getOutputStream();
output.write(params[1].getBytes(charset));
output.close();
int statusCode = connection.getResponseCode();
if (statusCode == 200) {
inputStream = new BufferedInputStream(connection.getInputStream());
json = new JSONArray(getJSON(inputStream));
result = 1;
}
} catch (Exception e) {
e.getLocalizedMessage();
}
return result;
}
#Override
protected void onPostExecute(Integer i) {
super.onPostExecute(i);
if(i == 1) {
responce.onPostExecute(json);
} else {
responce.onPostExecute(null);
}
}
private String getJSON(InputStream inputStream) throws IOException, JSONException {
StringBuffer stringBuffer = new StringBuffer();
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = null;
while((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line.toString());
}
result = stringBuffer.toString();
if(null!=inputStream){
inputStream.close();
}
return result;
}
}
//Responce.java
public interface Responce {
public void onPostExecute(JSONArray Result);
}
//OrderActivity.java
public class OrderActivity extends Activity implements Responce{
ArrayList<Product> products = new ArrayList<Product>();
ProductAdapter productAdapter;
OrderItemAdapter orderItemAdapter;
ListView orderlist;
JSONArray ja;
Button btnBack;
Button btnTakeOrder;
ListView picklist;
HTTPRequest httpRequest;
String url = "http://192.168.3.125:8888/data/";
String query = "select * from vwitems order by category desc";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
orderlist =(ListView)findViewById(R.id.orderlist);
orderItemAdapter = new OrderItemAdapter(OrderActivity.this);
btnBack = (Button)findViewById(R.id.btnBack);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productAdapter.filter(0);
}
});
btnTakeOrder = (Button)findViewById(R.id.btnTakeOrder);
btnTakeOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer oid = 0;
Order order = new Order(OrderActivity.this);
oid = order.NewOrder(1, 2, 3);
Toast.makeText(OrderActivity.this," " + order.getCount(), LENGTH_SHORT).show();
}
});
orderlist.setAdapter(orderItemAdapter);
picklist = (ListView) findViewById(R.id.picklist);
picklist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int pid = 0;
if (productAdapter.getItem(position).isCategory()) {
pid = productAdapter.getItem(position).getId();
productAdapter.filter(pid);
} else {
OrderItem oi = new OrderItem();
oi.setItemId(productAdapter.getItem(position).getId());
oi.setItem(productAdapter.getItem(position).getItem());
oi.setPrice(productAdapter.getItem(position).getPrice());
search(oi);
}
}
});
httpRequest = new HTTPRequest(this);
httpRequest.execute(url, query);
}
private boolean search(OrderItem oi){
int size = orderItemAdapter.getCount();
int i = 0;
if(size != 0)
for(OrderItem o : orderItemAdapter.getAll()){
if(o.getItemId() == oi.getItemId()){
orderItemAdapter.getItem(i).setQuantity(orderItemAdapter.getItem(i).getQuantity() + 1);
orderItemAdapter.notifyDataSetChanged();
return true;
}
i++;
}
orderItemAdapter.addItem(oi);
orderItemAdapter.notifyDataSetChanged();
return false;
}
private void load(JSONArray json) {
for(int i=0;i<json.length();i++){
try {
JSONObject jo = json.getJSONObject(i);
Product p = new Product(
jo.getInt("ID"),
jo.getInt("parent"),
jo.getInt("category"),
jo.getString("Item"),
jo.getDouble("Price")
);
products.add(p);
} catch (JSONException e) {
e.printStackTrace();
}
}
productAdapter = new ProductAdapter(OrderActivity.this, products);
picklist.setAdapter(productAdapter);
productAdapter.filter(0);
}
#Override
public void onPostExecute(JSONArray Result) {
load(Result);
}
/*
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
**/
}
sorry i forgot include this one
//Order.java
public class Order implements Responce{
private Context context;
private JSONArray json = new JSONArray();
private HTTPRequest httpRequest;
private int OrderID;
private Date OrderDate;
private int OrderTable;
private int Waiter;
private byte OrderStatus;
private List<OrderItem> orderItems;
public Order(Context context){
this.context = context;
}
//some code here...
public Integer NewOrder(Integer guests, Integer waiter, Integer ordertable){
String query = "insert into orders(orderdate, guests, waiter, ordertable) VALUES(NOW()," + guests + ", " + waiter + ", " + ordertable + "); SELECT LAST_INSERT_ID() as ID;";
Integer result = 0;
Connect(query);
try {
JSONObject jo = json.getJSONObject(0);
result = jo.getInt("ID");
} catch (JSONException e) {
e.printStackTrace();
}
return result; //here i got 0 if i init result to 0, null or what ever i init my
}
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
private void Connect (String query){
httpRequest = new HTTPRequest(context);
httpRequest.execute("http://192.168.3.125:8888/data/", query);
}
}