Android Fragment - SlidingMenu - ListActivity - android

So I have the slidingmenu(jfeinstein10) library added to my project and the menu working. The problem I have run into is based on my app extends ListActivity.
I have seen a couple questions about this and most suggest extending to Fragment to get Fragments working for the menu. I wanted to know if there was a way to not use Fragments to get the menu list to work.
Every time I move to SlidingFragmentActivity or any other Fragment Activity, onListItemClick and other methods start breaking.
Below is my code:
public class MainListActivity extends ListActivity {
public static final int NUMBER_OF_POSTS = 20;
public static final String TAG = MainListActivity.class.getSimpleName();
protected JSONObject mBlogData;
protected ProgressBar mProgressBar;
private SlidingMenu menu;
static final String KEY_TITLE = "title";
static final String KEY_AUTHOR = "author";
static final String KEY_IMAGE = "image";
ListView list;
LazyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//setBehindContentView(R.layout.menu_frame);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
menu = new SlidingMenu(this);
menu.setMode(SlidingMenu.LEFT);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
menu.setShadowWidth(5);
menu.setFadeDegree(0.35f);
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
menu.setBehindWidth(R.dimen.shadow_width);
menu.setShadowDrawable(R.drawable.shadow);
menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
menu.setMenu(R.layout.menu_frame);
//getFragmentManager().beginTransaction().replace(R.id.menu_frame, new MenuFragment()).commit();
if(isNetworkAvailable()){
GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask();
mProgressBar.setVisibility(View.VISIBLE);
getBlogPostsTask.execute();
}else{
Toast.makeText(this, "Network is unavailable", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
try{
JSONArray jsonPosts = mBlogData.getJSONArray("items");
JSONObject jsonPost = jsonPosts.getJSONObject(position);
String blogSummary = jsonPost.getString("summary");
String blogUrl = jsonPost.getString("bitly");
Intent intent = new Intent(this, BlogWebViewActivity.class);
intent.setData(Uri.parse(blogSummary));
intent.putExtra("mUrl",blogUrl);
startActivity(intent);
}catch(JSONException e){
logException(e);
}
}
private void logException(Exception e) {
Log.e(TAG, "Exception caught!", e);
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if(networkInfo != null && networkInfo.isConnected()){
isAvailable = true;
}
return isAvailable;
}
public void handleBlogResponse() {
mProgressBar.setVisibility(View.INVISIBLE);
if(mBlogData == null){
updateDisplayForError();
}else{
try {
JSONArray jsonPosts = mBlogData.getJSONArray("items");
ArrayList<HashMap<String,String>> blogPosts = new ArrayList<HashMap<String,String>>();
for (int i=0;i<jsonPosts.length();i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString(KEY_TITLE);
title = Html.fromHtml(title).toString();
String tag = post.getString(KEY_AUTHOR);
tag = Html.fromHtml(tag).toString();
String image = post.getString(KEY_IMAGE);
image = Html.fromHtml(image).toString();
HashMap<String, String> blogPost = new HashMap<String,String>();
blogPost.put(KEY_TITLE, title);
blogPost.put(KEY_AUTHOR, tag);;
blogPost.put(KEY_IMAGE, image);
blogPosts.add(blogPost);
}
list=getListView();
LazyAdapter adapter = new LazyAdapter(this, blogPosts);
list.setAdapter(adapter);
} catch (JSONException e) {
logException(e);
}
}
}
private void updateDisplayForError() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.error_title));
builder.setMessage(getString(R.string.error_message));
builder.setPositiveButton(android.R.string.ok,null);
AlertDialog dialog = builder.create();
dialog.show();
TextView emptyTextView = (TextView) getListView().getEmptyView();
emptyTextView.setText(getString(R.string.no_items));
}
private class GetBlogPostsTask extends AsyncTask<Object, Void, JSONObject>{
#Override
protected JSONObject doInBackground(Object... params) {
int responseCode = -1;
JSONObject jsonResponse = null;
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.domain.com/app_json.js");
try {
HttpResponse response = client.execute(httpget);
StatusLine statusLine = response.getStatusLine();
responseCode = statusLine.getStatusCode();
if(responseCode == HttpURLConnection.HTTP_OK){
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while((line = reader.readLine()) != null){
builder.append(line);
}
jsonResponse = new JSONObject(builder.toString());
}else{
Log.i(TAG, "HTTP Failed: "+responseCode);
}
} catch (MalformedURLException e) {
logException(e);
} catch (IOException e) {
logException(e);
}
catch(Exception e){
logException(e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject result){
mBlogData = result;
handleBlogResponse();
}
}
#Override
public void onBackPressed() {
if (menu.isMenuShowing()) {
menu.showContent();
} else {
super.onBackPressed();
}
}
}
I have the menu items stored in /values/array.xml as a string-array.
I have setup a fragment as well, but dont know how to access it without extending to Fragment from ListActivity.
Below is my Fragment based on the example fragments from github:
public class MenuFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.menu_list, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] colors = getResources().getStringArray(R.array.menu_items);
ArrayAdapter<String> colorAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, colors);
setListAdapter(colorAdapter);
}
#Override
public void onListItemClick(ListView lv, View v, int position, long id) {
Fragment newContent = null;
switch (position) {
case 0:
//newContent = new ColorFragment(R.color.red);
break;
case 1:
//newContent = new ColorFragment(R.color.green);
break;
case 2:
//newContent = new ColorFragment(R.color.blue);
break;
case 3:
//newContent = new ColorFragment(android.R.color.white);
break;
case 4:
//newContent = new ColorFragment(android.R.color.black);
break;
}
if (newContent != null)
switchFragment(newContent);
}
// the meat of switching the above fragment
private void switchFragment(Fragment fragment) {
if (getActivity() == null)
return;
}
}
Thanks

Related

API not displaying correct value for food calories

I'm currently developing a Calorie app where the user enter a food and uses an api food database to retrieve the calories. For some reason every time I enter a food it retrieves the same value. I'm not sure why its giving me this value.
Thanks in advance. I'm new to android studio and using API.
AddEntry.java
public class AddEntry extends Fragment implements View.OnClickListener {
EditText FoodET,CalorieET;
ImageButton Savebtn, Cancelbtn;
Button searchbutton;
String foodET,calorieET;
//database
private DatabaseHandler dba;
public AddEntry() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_add_entry, container,
false);
Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
Savebtn.setBackgroundColor(Color.TRANSPARENT);
Savebtn.setOnClickListener(this);
searchbutton = (Button) myView.findViewById(R.id.SearchButton);
searchbutton.setOnClickListener(this);
Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
Cancelbtn.setBackgroundColor(Color.TRANSPARENT);
Cancelbtn.setOnClickListener(this);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
FoodET= (EditText)view.findViewById(R.id.foodEditText);
FoodET.setInputType(InputType.TYPE_CLASS_TEXT);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
CalorieET.setInputType(InputType.TYPE_CLASS_NUMBER);
foodET = ((EditText)
view.findViewById(R.id.foodEditText)).getText().toString();
calorieET = ((EditText)
view.findViewById(R.id.caloriesEditText)).getText().toString();
}
public void saveDataToDB (){
Food food = new Food();
String FoodName = FoodET.getText().toString().trim();
String calString = CalorieET.getText().toString().trim();
//convert the claories numbers to text
if (!calString.equals("")) {
int cal = Integer.parseInt(calString);
food.setFoodName(FoodName);
food.setCalories(cal);
//call addFood method from the DatabaseHandler
dba.addFood(food);
dba.close();
//clear the editTexts
FoodET.setText("");
CalorieET.setText("");
//take the user to the next screen
//
((appMain) getActivity()).loadSelection(0);
;
}
else
{
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SearchButton:
FoodSearch search = new FoodSearch(foodET, CalorieET );
search.execute();
break;
case R.id.SaveBtn:
foodET = FoodET.getText().toString();
calorieET=CalorieET.getText().toString();
if (FoodET.getText().toString().equals(null) ||
CalorieET.getText().toString().equals(null)||
CalorieET.getText().toString().equals("")){
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
((appMain) getActivity()).loadSelection(0);
break;
case R.id.CancelBtn:
// EditText descriptionET=
(EditText)getView().findViewById(R.id.foodEditText);
//descriptionET.setText("");
//EditText calorieET=
(EditText)getView().findViewById(R.id.caloriesEditText);
//calorieET.setText("");
((appMain) getActivity()).loadSelection(0);
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
private class FoodSearch extends AsyncTask<Void, Void, String> {
String food;
EditText calories;
FoodSearch(String food, EditText calories){
this.food = food;
this.calories = calories;
}
#Override
protected String doInBackground(Void... params) {
try {
food = food.replaceAll(" ", "%20");
URL url = new URL("http://api.nal.usda.gov/ndb/search/?
format=JSON&q=" + food +
"&max=1&offset=0&sort=r&api_
key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
String result = stringBuilder.toString();
if(result.contains("zero results")) {
String s = "empty";
return s;
}
JSONObject object = (JSONObject) new
JSONTokener(result).nextValue();
JSONObject list = object.getJSONObject("list");
JSONArray items = list.getJSONArray("item");
String item = items.get(0).toString();
int i = item.indexOf("ndbno\":\"") + 8;
int f = item.indexOf("\"", i);
String ndbno = item.substring(i,f);
Log.d("DEBUG", ndbno);
URL url2 = new URL("http://api.nal.usda.gov/ndb/reports/?
ndbno=" + ndbno +
"&type=b&format=JSON&api_
key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection2 = (HttpURLConnection)
url2.openConnection();
BufferedReader bufferedReader2 = new BufferedReader(new
InputStreamReader(urlConnection2.getInputStream()));
StringBuilder stringBuilder2 = new StringBuilder();
String line2;
while ((line2 = bufferedReader2.readLine()) != null) {
stringBuilder2.append(line2).append("\n");
}
bufferedReader2.close();
String res = stringBuilder2.toString();
int index = res.indexOf("\"unit\": \"kcal\",") + 46;
int index2 = res.indexOf("\"", index);
String calories = res.substring(index,index2);
urlConnection2.disconnect();
return calories;
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
String s = "empty";
return s;
}
}
protected void onPostExecute(String response) {
if(!response.isEmpty() && !response.equals("empty")) {
calories.setText(response);
} else {
AlertDialog foodNotFound = new
AlertDialog.Builder(getContext()).create();
foodNotFound.setTitle("Error");
foodNotFound.setMessage("Food not found :(");
foodNotFound.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.dismiss();
}
});
}
}
}
}

Solve startActivity in fragment

I have a problem in my code. My problem is related to the startActivity(). When the app is running on the emulator, it does not work. The line causing the problem is described in the end.
I tried to open a new activity (this, newactivity.class), however the problem persists.
UpdateAnsList
public class UpdateAnsList extends Fragment{
/**
* #param args
*/
final static String ARG_POSITION_ANSWER = "position";
private String jsonResult;
private ListView listView;
public int selsub;
public Activity activity;
public String tagsub;
private Context mContext;
private Activity mact;
public UpdateAnsList(Activity _activity){
mact = _activity;
this.activity = _activity;
super.onAttach(_activity);
mContext = this.activity.getApplicationContext();
}
public enum SubSectionAnswer {
TagArt,
TagBio
}
public void StartUpdateAnsList(int v, String o){
tagsub = o;
selsub = v;
SubSectionAnswer currentSub = SubSectionAnswer.valueOf(tagsub);
listView = (ListView) this.activity.findViewById(R.id.listView11);
selectItemAns(selsub,currentSub);
accessWebService();
}
private void selectItemAns(int position, SubSectionAnswer currentSub) {
switch(currentSub){
case TagArt:
switch(position){
case R.id.buttonArt001:
url = "myip/newfolder/question_2.php";
tagdb = "info_general";
break;
case R.id.buttonArt002:
url = "http://myip/newfolder/question_1.php";
tagdb = "info_animation";
break;
case 2:
break;
}
break;
case TagBio:
switch(position){
case R.id.ButtonBio001:
url = "http://myip/newfolder/question_4.php";
tagdb = "info_general";
break;
case R.id.buttonBio002:
url = "http://myip/newfolder/question_5.php";
tagdb = "info_evolution";
break;
case 2:
break;
}
break;
}
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
//Toast.makeText(getApplicationContext(),
// "Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray(tagdb);
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("employee name");
String number = jsonChildNode.optString("content_text");
//String outPut = name + "-" + number;
String outPut = name;
String outPut1 = number;
employeeList.add(createEmployee("Question", outPut,"textlong",number));
}
} catch (JSONException e) {
Toast.makeText(this.activity, "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
//new String[] { "employees" }
//new int[] { android.R.id.text1 }
String[] de = {"Question", "textlong"};
int[] para ={R.id.textView1list11, R.id.textView11 };
SimpleAdapter simpleAdapter = new SimpleAdapter(this.activity, employeeList,
R.layout.activity_item_list_answer,
de, para);
listView.setAdapter(simpleAdapter);
listView.setOnItemClickListener(new ListClickHandler());
//Toast.makeText(getApplication(), "c", Toast.LENGTH_SHORT).show();
}
public class ListClickHandler implements OnItemClickListener{
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) {
// TODO Auto-generated method stub
int a =1 ;
//Toast.makeText(mContext, "c", Toast.LENGTH_SHORT).show();
//Intent i = new Intent(mact, QuestionActivity.class);
//mContext.startActivity(i);
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, "test");
// catch event that there's no activity to handle intent
mContext.startActivity(intent);
}
}
private HashMap<String, String> createEmployee(String s1, String s2, String s3,String s4) {
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(s1, s2);
employeeNameNo.put(s3, s4);
return employeeNameNo;
}
}
This is the line causing the problem:
mContext.startActivity(intent);
Screen of debug:
Screen when I use getActivity():
You should start new Activity using Activity context:
getActivity.startActivity(intent);
This is a Fragment class, so you are not able to pass an Intentby simply writing this.startActivity();
What you need to do is to get the Activity of this Fragment class.
So instead of mContext.startActivity(intent); you should write :
getActivity().startActivity(intent);
Basically you are working with Fragment:
How to Start Activity from Fragment:
mContext.startActivity(intent);
Edit 1:
private Context mContext;
public void StartUpdateAnsList(Context ctx, int v, String o){
mContext = ctx;
tagsub = o;
selsub = v;
SubSectionAnswer currentSub = SubSectionAnswer.valueOf(tagsub);
listView = (ListView) this.activity.findViewById(R.id.listView11);
selectItemAns(selsub,currentSub);
accessWebService();
}
Now you can use: mContext.startActivity(intent);
Hope this will help you.

GridView not refreshing after changing setting

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.

Android - get photos from database with AsyncTask - doInBackGround not starting

I'm having a problem with my program. I'm calling my getImages() function in onCreate() but when I tried debugging it, I discovered that doInBackground() function doesn't actually start. I've seen many people had the same problem but none of the solutions provided were of any help.
Here is how my main activity looks like:
public class poi_photos extends ActionBarActivity {
public static ArrayList<String> image_urls = new ArrayList<>();
public static GridView gridView;
// Retrieve PHOTOS from database
String myJSON;
private static final String TAG_RESULTS = "result";
private static final String TAG_EMAIL_USER = "email_user";
private static final String TAG_POI_NAME = "poi_name";
private static final String TAG_PHOTO_URL = "photo_url";
JSONArray photos = null;
ArrayList<HashMap<String, String>> photoList;
ArrayList<HashMap<String, Integer>> numsList;
// GALLERY
private FeatureCoverFlow mCoverFlow;
private CoverFlowAdapter Adapter;
private ArrayList<GameEntity> mData = new ArrayList<>(0);
private TextSwitcher mTitle;
String photo_url2;
// Camera Activity
Button btpic, btnup;
private Uri fileUri;
String picturePath;
Uri selectedImage;
Bitmap photo;
String ba1;
static int TAKE_PICTURE = 1;
// MENU
String TITLES[] = {"Home", "Profile", "Travel", "POIs Map", "Find your friends!", "Take Picture"};
int ICONS[] = {R.drawable.ic_home, R.drawable.ic_prof, R.drawable.ic_travel, R.drawable.ic_poi, R.drawable.ic_friends_map, R.drawable.ic_photo};
String NAME = MainActivity.username;
String EMAIL = MainActivity.user_email;
private Toolbar toolbar; // Declaring the Toolbar Object
RecyclerView mRecyclerView; // Declaring RecyclerView
RecyclerView.Adapter mAdapter; // Declaring Adapter For Recycler View
RecyclerView.LayoutManager mLayoutManager; // Declaring Layout Manager as a linear layout manager
DrawerLayout Drawer; // Declaring DrawerLayout
ActionBarDrawerToggle mDrawerToggle; // Declaring Action Bar Drawer Toggle
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poi_photos);
FloatingActionButton add_comment = (FloatingActionButton) findViewById(R.id.button_poi_comments);
add_comment.setBackgroundTintList(getResources().getColorStateList(R.color.Blonde));
add_comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(poi_photos.this, MarkerActivity.class));
}
});
FloatingActionButton see_photos = (FloatingActionButton) findViewById(R.id.button_add_photo);
see_photos.setBackgroundTintList(getResources().getColorStateList(R.color.Blonde));
see_photos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takepic();
}
});
image_urls.clear();
if (image_urls.isEmpty())
{
getImages();
}
gridView = (GridView) findViewById(R.id.gridview);
final ImageAdapter adapter = new ImageAdapter(this);
// adapter.notifyDataSetChanged();
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(poi_photos.this, ImageActivity.class);
intent.putExtra("url", adapter.imageUrls.get(position));
startActivity(intent);
}
});
// MENU
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); // Assigning the RecyclerView Object to the xml View
mRecyclerView.setHasFixedSize(true); // Letting the system know that the list objects are of fixed size
mAdapter = new MyAdapter(TITLES, ICONS, NAME, EMAIL, this); // Creating the Adapter of MyAdapter class(which we are going to see in a bit)
// And passing the titles,icons,header view name, header view email,
// and header view profile picture
mRecyclerView.setAdapter(mAdapter); // Setting the adapter to RecyclerView
mLayoutManager = new LinearLayoutManager(this); // Creating a layout Manager
mRecyclerView.setLayoutManager(mLayoutManager); // Setting the layout Manager
final GestureDetector mGestureDetector = new GestureDetector(poi_photos.this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child = recyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (child != null && mGestureDetector.onTouchEvent(motionEvent)) {
Drawer.closeDrawers();
// Toast.makeText(map.this,"The Item Clicked is: "+recyclerView.getChildPosition(child),Toast.LENGTH_SHORT).show();
switch (recyclerView.getChildPosition(child)) {
case 1:
Intent a = new Intent(poi_photos.this, myprofile.class);
startActivity(a);
break;
case 2:
Intent b = new Intent(poi_photos.this, profile.class);
startActivity(b);
break;
case 3:
Intent c = new Intent(poi_photos.this, ShortPath.class);
startActivity(c);
break;
case 5:
Intent e = new Intent(poi_photos.this, FriendsMap.class);
startActivity(e);
break;
case 6:
//Camera Activity
if (hasCamera()) {
// create intent with ACTION_IMAGE_CAPTURE action
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// start camera activity
startActivityForResult(intent, TAKE_PICTURE);
}
break;
}
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
mLayoutManager = new LinearLayoutManager(this); // Creating a layout Manager
mRecyclerView.setLayoutManager(mLayoutManager); // Setting the layout Manager
Drawer = (DrawerLayout) findViewById(R.id.DrawerLayout); // Drawer object Assigned to the view
mDrawerToggle = new ActionBarDrawerToggle(this, Drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
// code here will execute once the drawer is opened( As I dont want anything happened whe drawer is
// open I am not going to put anything here)
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
// Code here will execute once drawer is closed
}
}; // Drawer Toggle Object Made
Drawer.setDrawerListener(mDrawerToggle); // Drawer Listener set to the Drawer toggle
mDrawerToggle.syncState(); // Finally we set the drawer toggle sync State
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_poi_photos, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// method to check if you have a Camera
private boolean hasCamera() {
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
// CAMERA ACTIVITY
private void takepic() {
// Check Camera
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// Open default camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, 100);
} else {
Toast.makeText(getApplication(), "Camera not supported", Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100 && resultCode == RESULT_OK) {
selectedImage = data.getData();
photo = (Bitmap) data.getExtras().get("data");
// Cursor to get image uri to display
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap photo = (Bitmap) data.getExtras().get("data");
// Show pop up window
LayoutInflater layoutInflater = LayoutInflater.from(poi_photos.this);
View promptView = layoutInflater.inflate(R.layout.input_photo, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(poi_photos.this);
alertDialogBuilder.setView(promptView);
ImageView imageView = (ImageView) promptView.findViewById(R.id.imageView_photo);
imageView.setImageBitmap(photo);
alertDialogBuilder.setCancelable(false)
.setPositiveButton("Keep the photo!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
upload(); // upload photo to folder
upload2(); // upload photo to database
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
// upload photo to database
private void upload() {
// Image location URL
Log.e("path", "----------------" + picturePath);
// Image
Bitmap bm = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
ba1 = Base64.encodeToString(ba, Base64.DEFAULT);
Log.e("base64", "-----" + ba1);
// Upload image to server
new uploadToServer().execute();
}
public class uploadToServer extends AsyncTask<Void, Void, String> {
private ProgressDialog pd = new ProgressDialog(poi_photos.this);
protected void onPreExecute() {
super.onPreExecute();
pd.setMessage("Wait uploading image!");
pd.show();
}
// insert photo
#Override
protected String doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
photo_url2 = map.markername + "_" + System.currentTimeMillis() + ".jpg";
nameValuePairs.add(new BasicNameValuePair("base64", ba1));
nameValuePairs.add(new BasicNameValuePair("ImageName", photo_url2));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxxx/photo.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String st = EntityUtils.toString(response.getEntity());
Log.v("log_tag", "In the try Loop " + st);
} catch (Exception e) {
Log.v("log_tag", "Error in http connection " + e.toString());
}
return "Success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
pd.hide();
pd.dismiss();
}
}
// insert photo
private void upload2() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("email_user", MainActivity.user_email));
nameValuePairs.add(new BasicNameValuePair("poi_name", map.markername));
nameValuePairs.add(new BasicNameValuePair("photo_url", photo_url2));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http:xxxxx/photo_out.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
String msg = "Data has been sent successfully";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
Log.e("ClientProtocol", "Log_Tag");
e.printStackTrace();
String msg2 = "Log_Tag";
Toast.makeText(getApplicationContext(), msg2, Toast.LENGTH_LONG).show();
} catch (IOException e) {
Log.e("Log_Tag", "IOException");
e.printStackTrace();
String msg3 = "IOException";
Toast.makeText(getApplicationContext(), msg3, Toast.LENGTH_LONG).show();
}
}
// GETTING PHOTOS FROM DATABASE
protected void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON);
photos = jsonObj.getJSONArray(TAG_RESULTS);
for (int i = 0; i < photos.length(); i++) {
JSONObject c = photos.getJSONObject(i);
String email_user = c.getString(TAG_EMAIL_USER);
String poi_name = c.getString(TAG_POI_NAME);
String photo_url = c.getString(TAG_PHOTO_URL);
if ((poi_name.substring(0, 4)).equals(map.markername) && photo_url!=null) {
// add to the picasso gallery
photo_url="http://romcad.ro/poi/photos/"+photo_url;
image_urls.add(photo_url);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getImages() {
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://xxxxx/table_photo_out.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
}
Any idea/ tip what might be the problem here?
Why do you write the class GetDataJSON into the method getImages()?
Try to delete the method around your class and instead of calling getImages() call
new getDataJSON().execute(yourString);

Android: adapter.notifydatasetchanged()

i want to create a dynamic GridView, and when i click to my options meny, i refresh my asyncTask, then i get all result's from postExecute, and notify my adapter to refresh! But i doesn't work HELP me please!
GridView grid;
ImageAdapter adapter;
ArrayList<String> arrayThumbs = new ArrayList<String>();
ArrayList<String> arrayBig_image = new ArrayList<String>();
ArrayList<String> arrayAuthor = new ArrayList<String>();
ArrayList<String> arrayDescription = new ArrayList<String>();
ArrayList<String> arrayDate = new ArrayList<String>();
String[] arraymThumbs;
String[] arrayBimages;
String[] arrayauthor;
String[] arraydescription;
String[] arraydate;
final static String TAG_ITEM = "img_list";
final static String TAG_THUMBNAILS = "thumbnail";
final static String TAG_BIG_IMAGE = "big_image";
final static String TAG_AUTHOR = "author";
final static String TAG_DESCRIPTION = "description";
final static String TAG_DATE = "event_date";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
backTask();
grid = (GridView) findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, ImageGallery.class);
intent.putExtra("position", position);
intent.putExtra("big_images", arrayBimages);
intent.putExtra("author", arrayauthor);
intent.putExtra("description", arraydescription);
intent.putExtra("date", arraydate);
startActivity(intent);
}
});
}
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.refresh:
backTask();
break;
}
return super.onOptionsItemSelected(item);
}
public void backTask(){
BackTask task = new BackTask();
task.execute();
try {
JSONObject result = task.get();
if(result != null){
JSONArray jarray = result.getJSONArray(TAG_ITEM);
for(int i = 0; i < jarray.length(); i++){
JSONObject jrss = jarray.getJSONObject(i);
arrayThumbs.add(jrss.getString(TAG_THUMBNAILS));
arrayBig_image.add(jrss.getString(TAG_BIG_IMAGE));
arrayAuthor.add(jrss.getString(TAG_AUTHOR));
arrayDescription.add(jrss.getString(TAG_DESCRIPTION));
arrayDate.add(jrss.getString(TAG_DATE));
Log.d("LLLLLOOOOGGGG", jrss.getString("author")+"\n");
}}
else{
AlertDialog.Builder alertNetworkError = new AlertDialog.Builder(this);
alertNetworkError.setMessage("нет подключения к интернету");
alertNetworkError.setNegativeButton("Выйти", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertNetworkError.create();
alertNetworkError.show();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
arraymThumbs = new String[arrayThumbs.size()];
arraymThumbs = arrayThumbs.toArray(arraymThumbs);
arrayBimages = new String[arrayBig_image.size()];
arrayBimages = arrayBig_image.toArray(arrayBimages);
arrayauthor = new String[arrayAuthor.size()];
arrayauthor = arrayAuthor.toArray(arrayauthor);
arraydescription = new String[arrayDescription.size()];
arraydescription = arrayDescription.toArray(arraydescription);
arraydate = new String[arrayDate.size()];
arraydate = arrayDate.toArray(arraydate);
adapter = new ImageAdapter(MainActivity.this, arraymThumbs);
adapter.notifyDataSetChanged();
}
And my image adapter here i get all result's from asyncTask and print thumbs images to my GridView
public class ImageAdapter extends BaseAdapter {
public Context mContext;
String[] mThumbs;
public LayoutInflater inflater;
public DisplayImageOptions options;
public ImageLoader imageLoader;
public ImageAdapter (Context c, String[] arrayhumbss){
mContext = c;
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mThumbs = arrayhumbss;
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.ic_contact_picture_2)
.showImageForEmptyUri(R.drawable.ic_launcher)
.cacheInMemory()
.cacheOnDisc()
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(c));
}
#Override
public int getCount() {
return mThumbs.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) {
imageView = (ImageView) inflater.inflate(R.layout.grid_item, parent, false);
} else {
imageView = (ImageView) convertView;
}
imageLoader.displayImage(mThumbs[position], imageView, options);
return imageView;
}
}
This is my BACKTASK
public class BackTask extends AsyncTask<String, Void, JSONObject>{
#Override
protected JSONObject doInBackground(String... params) {
InputStream ips = null;
JSONObject jsonObj = null;
String json = "";
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(new HttpPost("http://192.168.1.179/lenta/image.js"));
ips = response.getEntity().getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader bufff = new BufferedReader(new InputStreamReader(ips, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = bufff.readLine()) != null){
sb.append(line + "\n");
}
ips.close();
json = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
try {
jsonObj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObj;
}
#Override
protected void onPostExecute(JSONObject result){
super.onPostExecute(result);
}
}
here i handle my json from url, and in MainActivity i get this form task.get()
Add grid.setAdapter(adapter) right after this line
adapter = new ImageAdapter(MainActivity.this, arraymThumbs);
Hope this would solve your problem.
EDIT: P.S. It seems you need to read something, because i think you don't fully understand what adapter is and how to use it.
Use this :
adapter = new ImageAdapter(YourActivity.this, arraymThumbs);
myGridView.setAdapter(adapter);
Hope this helps you.
Thanks.

Categories

Resources