No errors or crashes whatsoever on running, just a blank output for ListView. Re-read the code multiple times no idea as to the cause why the ListView doesn't populate.
MSKFragment.java
public class MSKFragment extends android.support.v4.app.Fragment implements android.support.v4.app.LoaderManager.LoaderCallbacks<Cursor>
{
private ServiceAdapter mServiceAdapter;
public static final int SERVICE_LOADER = 0;
private static final String[] SERVICE_COLUMNS =
{
ServiceContract.ServiceEntry.TABLE_NAME,
ServiceContract.ServiceEntry._ID,
ServiceContract.ServiceEntry.COLUMN_NAME,
ServiceContract.ServiceEntry.COLUMN_ORGANIZATION_NAME,
ServiceContract.ServiceEntry.COLUMN_PRICE
};
/*public static final int COL_TABLE_NAME = 0;*/
public static final int COL_ID = 0;
public static final int COL_NAME = 1;
public static final int COL_ORG_NAME = 2;
public static final int COL_PRICE = 3;
public MSKFragment()
{
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getLoaderManager().initLoader(SERVICE_LOADER, null, this);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
inflater.inflate(R.menu.menu_fragment_msk, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_refresh)
{
//Moving functions to a helper class, so that when Activity starts the data can be displayed
updateServices();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
mServiceAdapter = new ServiceAdapter(getActivity(), null, 0);
View rootView = inflater.inflate(R.layout.fragment_msk, container, false);
ListView listView = (ListView) rootView.findViewById(R.id.listViewMainService);
listView.setAdapter(mServiceAdapter);
return rootView;
}
#Override
public void onStart()
{
super.onStart();
//Refresh called and service updated when activity starts
updateServices();
}
//Calling FetchServiceTask and executing it.
private void updateServices()
{
FetchServicesTask serviceTask = new FetchServicesTask(getActivity());
serviceTask.execute();
}
#Override
public android.support.v4.content.Loader<Cursor> onCreateLoader(int i, Bundle args)
{
Uri serviceUri = ServiceContract.ServiceEntry.buildServiceUri(i);
return new android.support.v4.content.CursorLoader(getActivity(), serviceUri, null, null, null, null);
}
#Override
public void onLoadFinished(android.support.v4.content.Loader<Cursor> loader, Cursor data)
{
mServiceAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(android.support.v4.content.Loader<Cursor> loader)
{
mServiceAdapter.swapCursor(null);
}
}
FetchServicesTask.java (Async operations)
public class FetchServicesTask extends AsyncTask<String, Void, Void>
{
private final String LOG_TAG = FetchServicesTask.class.getSimpleName();
private final Context mContext;
private boolean DEBUG = true;
public FetchServicesTask(Context context )
{
mContext = context;
}
private String[] getServicesDatafromJson(String serviceJsonStr) throws JSONException
{
final String MSK_NAME = "name";
final String MSK_PRICE = "price";
final String MSK_ORG_NAME = "organizationName";
final String MSK_POSTED_USER = "postedUser";
final String MSK_PROFILE = "profile";
int totalResults = 25;
String resultStrs[] = new String[totalResults];
try
{
JSONArray serviceArray = new JSONArray(serviceJsonStr);
Vector<ContentValues> cVVector = new Vector<ContentValues>(serviceArray.length());
for(int i=0;i<serviceArray.length();i++)
{
String name, organizationName;
int price;
JSONObject serviceObject = serviceArray.getJSONObject(i);
name = serviceObject.getString(MSK_NAME);
price = serviceObject.getInt(MSK_PRICE);
JSONObject postedUserObject = serviceObject.getJSONObject(MSK_POSTED_USER);
JSONObject profileObject = postedUserObject.getJSONObject(MSK_PROFILE);
organizationName = profileObject.getString(MSK_ORG_NAME);
ContentValues serviceValues = new ContentValues();
serviceValues.put(ServiceContract.ServiceEntry.COLUMN_NAME, name);
serviceValues.put(ServiceContract.ServiceEntry.COLUMN_ORGANIZATION_NAME, organizationName);
serviceValues.put(ServiceContract.ServiceEntry.COLUMN_PRICE, price);
cVVector.add(serviceValues);
}
int inserted = 0;
if(cVVector.size()>0)
{
ContentValues[] cvArray = new ContentValues[cVVector.size()];
cVVector.toArray(cvArray);
inserted = mContext.getContentResolver().bulkInsert(ServiceContract.ServiceEntry.CONTENT_URI, cvArray);
}
Log.d(LOG_TAG, "FetchServicesTask Complete. " + inserted + " Inserted");
}
catch(JSONException e)
{
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
/////////////////////////////// NETWORKING BOILER PLATE ///////////////////////////
#Override
protected Void doInBackground(String... params)
{
if (params.length == 0)
{
return null;
}
HttpURLConnection urlConnection = null; //Streaming data using HTTP
String serviceJsonStr = null; //raw JSON response
BufferedReader reader = null; //read text from character i/p stream
int pageNo = 1;
int numResults = 5;
try
{
//-------------------------CONNECTION--------------------//
final String SERVICE_BASE_URL = "http://myservicekart.com/public/";
final String SEARCH_BASE_URL = "http://myservicekart.com/public/search?";
final String SEARCH_PARAM = "search";
final String PAGE_PARAM = "pageno";
/*Using a helper class UriBuilder for building and manipulating URI references*/
Uri builtServiceUri = Uri.parse(SERVICE_BASE_URL);
Uri builtSearchUri = Uri.parse(SEARCH_BASE_URL).buildUpon().
appendQueryParameter(SEARCH_PARAM, "").
appendQueryParameter(PAGE_PARAM, Integer.toString(pageNo)).
build();
URL searchUrl = new URL(builtSearchUri.toString());
Log.v(LOG_TAG, "Built SearchUri" +builtSearchUri.toString());
urlConnection = (HttpURLConnection) searchUrl.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
//------------------------BUFFERING---------------------//
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if(inputStream==null)
{
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line = reader.readLine()) != null)
{
buffer.append(line + "\n");
}
if(buffer.length()==0)
{
return null;
}
serviceJsonStr = buffer.toString();
getServicesDatafromJson(serviceJsonStr);
Log.v(LOG_TAG, "Services JSON String: " +serviceJsonStr);
}
catch(IOException e)
{
Log.e(LOG_TAG, "Error cannot connect to URL", e);
return null;
}
catch (JSONException e)
{
e.printStackTrace();
}
finally
{
if(urlConnection!=null)
{
urlConnection.disconnect();
}
if(reader!=null)
{
try
{
reader.close();
}
catch (final IOException e)
{
Log.e(LOG_TAG,"Error closing stream",e);
}
}
}
return null;
}
}
ServiceAdapter.java
public class ServiceAdapter extends CursorAdapter
{
public ServiceAdapter(Context context, Cursor c, int flags)
{
super(context, c, flags);
}
private String convertCursorRowToUXFormat(Cursor cursor)
{
return cursor.getString(MSKFragment.COL_NAME) + "-" + cursor.getString(MSKFragment.COL_ORG_NAME) +
" - " + cursor.getInt(MSKFragment.COL_PRICE);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
View view = LayoutInflater.from(context).inflate(R.layout.list_item_main, parent, false);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor)
{
TextView tv = (TextView)view;
tv.setText(convertCursorRowToUXFormat(cursor));
}
}
Related
I am trying to get JSON data to app, but getting JSON Exception
MainActivity
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private List<Project> projects = new ArrayList<>();
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listView);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading....");
progressDialog.setCancelable(false);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
}
});
Button mFilterButton = (Button) findViewById(R.id.filter_button);
mFilterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(MainActivity.this,v);
popupMenu.inflate(R.menu.filter_menu);
popupMenu.show();
}
});
Button mSortButton = (Button) findViewById(R.id.sort_button);
mSortButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(MainActivity.this,v);
popupMenu.inflate(R.menu.sort_menu);
popupMenu.show();
}
});
new GSONExecution().execute();
}
private class GSONExecution extends AsyncTask<Void, Void, Boolean>{
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
String urlString = "http://starlord.hackerearth.com/kickstarter";
try {
URL url = new URL(urlString);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("GET");
int res = httpURLConnection.getResponseCode();
if (res == 200){
InputStream inputStream = httpURLConnection.getInputStream();
String s = convertStreamToString(inputStream);
Log.v("Response :" , " is "+ s);
JSONObject rootObject = new JSONObject(s);
JSONArray jsonArray = rootObject.getJSONArray("");
for (int i=0; i<=jsonArray.length(); i++){
JSONObject contactObject = jsonArray.getJSONObject(i);
String titleValue = contactObject.getString("title");
Integer pledgedValue = contactObject.getInt("amt.pledged");
Integer backersValue = contactObject.getInt("num.backers");
Project project = new Project();
project.setPleadges(pledgedValue);
project.setBackers(backersValue);
project.settitle(titleValue);
projects.add(project);
Log.v("Object details : " , " : " + pledgedValue + " : " + backersValue);
}
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean isOperationCompleted) {
super.onPostExecute(isOperationCompleted);
if (isOperationCompleted){
if (progressDialog.isShowing()){
progressDialog.dismiss();
}
ProjectAdapter adapter = new ProjectAdapter(MainActivity.this, projects);
mListView.setAdapter(adapter);
}
}
#NonNull
private String convertStreamToString(InputStream inputStream) {
StringBuilder stringBuilder = new StringBuilder();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"),8);
String line;
while ((line = bufferedReader.readLine()) != null)
stringBuilder.append(line).append("\n");
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
}
}
Project
public class Project {
String mtitle;
Integer mPleadges;
Integer mBackers;
String mNoDays;
public String gettitle() {
return mtitle;
}
public void settitle(String mtitle) {
this.mtitle = mtitle;
}
public Integer getPleadges() {
return mPleadges;
}
public void setPleadges(Integer mPleadges) {
this.mPleadges = mPleadges;
}
public Integer getBackers() {
return mBackers;
}
public void setBackers(Integer mBackers) {
this.mBackers = mBackers;
}
public String getNoDays() {
return mNoDays;
}
public void setNoDays(String mNoDays) {
this.mNoDays = mNoDays;
}
}
ProjectAdapter
class ProjectAdapter extends BaseAdapter{
private List<Project> mList;
private Context mContext;
public ProjectAdapter(MainActivity mainActivity, List<Project> projects) {
this.mList = projects;
this.mContext = mainActivity;
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.project_details,null,false);
final TextView projectName = (TextView) convertView.findViewById(R.id.projectName);
TextView pleadge = (TextView) convertView.findViewById(R.id.pledges);
TextView backers = (TextView) convertView.findViewById(R.id.backers);
projectName.setText(mList.get(position).gettitle());
pleadge.setText(mList.get(position).getPleadges());
backers.setText(mList.get(position).getBackers());
return convertView;
}
}
I am getting org.json.JSONException: Value
at org.json.JSON.typeMismatch(JSON.java:111)
I hope you understand problem, I am still in learning stage so please give brief answer so that i can understand.
You are getting JSONArray from Response and trying to hold on JSONObject which causes org.json.JSONException: Value at org.json.JSON.typeMismatch(JSON.java:111) error
Try this
try {
JSONArray jsonArrayLST = new JSONArray(s);
for (int i = 0; i < jsonArrayLST.length(); i++) {
JSONObject contactObject= jsonArrayLST.getJSONObject(i);
String titleValue = contactObject.getString("title");
Integer pledgedValue = contactObject.getInt("amt.pledged");
Integer backersValue = contactObject.getInt("num.backers");
Project project = new Project();
project.setPleadges(pledgedValue);
project.setBackers(backersValue);
project.settitle(titleValue);
projects.add(project);
Log.v("Object details : " , " : " + pledgedValue + " : " + backersValue);
}
} catch (JSONException e) {
e.printStackTrace();
}
Also, you need to change in your adapter while setting item to textview, because your are setting int value which causes you android.content.res.Resources$NotFoundException: String resource ID error
pleadge.setText(String.valueOf(mList.get(position).getPleadges()));
backers.setText(String.valueOf(mList.get(position).getBackers()));
[EDIT: Was able to solve this by passing a blank image to the list array on fragment load]
I am working on an app where grid views are refreshed dynamically fetching data from API. My gridview is not refrishing on load. The refresh is happening on clicking other options (like sort) or by just changing orientation in the app. How do I get it to refresh on load. I have tried calling the refresh function from onStart(), onCreate() and onCreateView() but it isn't working.
Github: https://github.com/abhrajitmukherjee/PopularMovies
Main code:
public class MainActivityFragment extends Fragment {
private ImageAdapter mImageAdapter;
public ArrayList<String[]> mThumbIds;
private GridView gridview;
public MainActivityFragment() {
}
#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 inflater) {
inflater.inflate(R.menu.menu_fragment_main, menu);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.v("Initiate","Starts here-------------------");
updateMovieThumbs(getString(R.string.base_uri_popular));
gridview = (GridView) getActivity().findViewById(R.id.gridview);
mImageAdapter = new ImageAdapter(getActivity());
gridview.setAdapter(mImageAdapter);
updateMovieThumbs(getString(R.string.base_uri_popular));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent intent = new Intent(getActivity(), MovieDetailsActivity.class)
.putExtra(getString(R.string.intent_poster_path), mThumbIds.get(position)[0])
.putExtra(getString(R.string.intent_title),mThumbIds.get(position)[1])
.putExtra(getString(R.string.intent_overview),mThumbIds.get(position)[2])
.putExtra(getString(R.string.intent_vote_avg),mThumbIds.get(position)[3])
.putExtra(getString(R.string.intent_release_date),mThumbIds.get(position)[4]);
startActivity(intent);
}
});
}
#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();
if (id == R.id.action_toprated) {
updateMovieThumbs(getString(R.string.base_uri_toprated));
} else if (id == R.id.action_popular) {
updateMovieThumbs(getString(R.string.base_uri_popular));
}
return true;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main, container, false);
mThumbIds = new ArrayList<String[]>();
return v;
}
#Override
public void onStart() {
super.onStart();
}
private void updateMovieThumbs(String sortType) {
FetchMovieDatabase movieTask = new FetchMovieDatabase();
movieTask.execute(sortType);
Log.v("getCount", "Get Main count=" + Integer.toString(mThumbIds.size()));
}
public class FetchMovieDatabase extends AsyncTask<String, Void, ArrayList<String[]>> {
private final String LOG_TAG = FetchMovieDatabase.class.getSimpleName();
private ArrayList<String[]> getMovieDataJson(String movieJsonStr)
throws JSONException {
final String RESULTS = "results";
final String ORIGINAL_TITLE="original_title";
final String POSTER="poster_path";
final String OVERVIEW="overview";
final String VOTES="vote_average";
final String RELEASE="release_date";
ArrayList<String[]> newThumbids=new ArrayList<String[]>();
JSONObject movieJson = new JSONObject(movieJsonStr);
JSONArray movieArray = movieJson.getJSONArray(RESULTS);
for (int i = 0; i < movieArray.length(); i++) {
JSONObject results = movieArray.getJSONObject(i);
String posterPath = getString(R.string.api_image_base_path)+results.getString(POSTER);
String title=results.getString(ORIGINAL_TITLE);
String overview=results.getString(OVERVIEW);
String voteAvg=results.getString(VOTES);
String releaseDate=results.getString(RELEASE);
String[] outputAttr={posterPath,title,overview,voteAvg,releaseDate};
Log.v(LOG_TAG, posterPath);
newThumbids.add(outputAttr);
Log.v(LOG_TAG, Integer.toString(newThumbids.size()));
}
return newThumbids;
}
#Override
protected ArrayList<String[]> doInBackground(String... params) {
if (params.length == 0) {
return null;
}
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String movieJsonStr = null;
try {
final String BASE_URL = params[0];
final String API_KEY = "api_key";
Uri builtUri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(API_KEY, BuildConfig.MOVIES_API_KEY)
.build();
URL url = new URL(builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return 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(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getMovieDataJson(movieJsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<String[]> result) {
if (result != null) {
if (mThumbIds.size()>0){
mThumbIds.clear();
}
mThumbIds = (ArrayList<String[]>) result.clone();
Log.v(LOG_TAG, "Postexecute count:"+Integer.toString( mThumbIds.size()));
mImageAdapter.notifyDataSetChanged();
}
}
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
Log.v("getCount", "Get Count=" + Integer.toString(mThumbIds.size()));
// return 5;
return mThumbIds.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setAdjustViewBounds(true);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
} else {
imageView = (ImageView) convertView;
}
Picasso.with(getActivity()).load(mThumbIds.get(position)[0]).into(imageView);
return imageView;
}
}
}
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.
The problem is that, I don't get any error, except that the data doesn't get loaded in the textViews of the customized ListView, all I get is a blank output. I didn't have problems before I started using Loaders.
MSKFragment.java (The Fragment class)
public class MSKFragment extends android.support.v4.app.Fragment implements LoaderManager.LoaderCallbacks<Cursor>
{
private ServiceAdapter mServiceAdapter;
public static final int SERVICE_LOADER = 0;
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle args)
{
Uri serviceUri = ServiceContract.ServiceEntry.buildServiceUri(i);
return new CursorLoader(getActivity(), serviceUri, null, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data)
{
mServiceAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader)
{
mServiceAdapter.swapCursor(null);
}
public MSKFragment()
{
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
inflater.inflate(R.menu.menu_fragment_msk, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_refresh)
{
//Moving functions to a helper class, so that when Activity starts the data can be displayed
updateServices();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
mServiceAdapter = new ServiceAdapter(getActivity(), null, 0);
View rootView = inflater.inflate(R.layout.fragment_msk, container, false);
ListView listView = (ListView) rootView.findViewById(R.id.listViewMainService);
listView.setAdapter(mServiceAdapter);
return rootView;
}
#Override
public void onStart()
{
super.onStart();
//Refresh called and service updated when activity starts
updateServices();
}
private void updateServices()
{
FetchServicesTask serviceTask = new FetchServicesTask(getActivity());
serviceTask.execute();
}
}
ServiceAdapter.java (Custom Adapter class)
public class ServiceAdapter extends CursorAdapter
{
public ServiceAdapter(Context context, Cursor c, int flags)
{
super(context, c, flags);
}
private String convertCursorRowToUXFormat(Cursor cursor) {
// get row indices for our cursor
int idx_name = cursor.getColumnIndex(ServiceContract.ServiceEntry.COLUMN_NAME);
int idx_organizationName = cursor.getColumnIndex(ServiceContract.ServiceEntry.COLUMN_ORGANIZATION_NAME);
int idx_price = cursor.getColumnIndex(ServiceContract.ServiceEntry.COLUMN_PRICE);
return cursor.getString(idx_name) + "-" + cursor.getString(idx_organizationName) +
" - " + cursor.getString(idx_price);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
View view = LayoutInflater.from(context).inflate(R.layout.list_item_main, parent, false);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor)
{
TextView tv = (TextView)view;
tv.setText(convertCursorRowToUXFormat(cursor));
}
}
FetchServicesTask.java (Performing the Async Task)
public class FetchServicesTask extends AsyncTask<String, Void, Void>
{
private final String LOG_TAG = FetchServicesTask.class.getSimpleName();
private final Context mContext;
private boolean DEBUG = true;
public FetchServicesTask(Context context )
{
mContext = context;
}
private String[] getServicesDatafromJson(String serviceJsonStr) throws JSONException
{
final String MSK_NAME = "name";
final String MSK_PRICE = "price";
final String MSK_ORG_NAME = "organizationName";
final String MSK_POSTED_USER = "postedUser";
final String MSK_PROFILE = "profile";
int totalResults = 25;
String resultStrs[] = new String[totalResults];
try
{
JSONArray serviceArray = new JSONArray(serviceJsonStr);
Vector<ContentValues> cVVector = new Vector<ContentValues>(serviceArray.length());
for(int i=0;i<serviceArray.length();i++)
{
String name, organizationName, price;
JSONObject serviceObject = serviceArray.getJSONObject(i);
name = serviceObject.getString(MSK_NAME);
price = serviceObject.getString(MSK_PRICE);
JSONObject postedUserObject = serviceObject.getJSONObject(MSK_POSTED_USER);
JSONObject profileObject = postedUserObject.getJSONObject(MSK_PROFILE);
organizationName = profileObject.getString(MSK_ORG_NAME);
ContentValues serviceValues = new ContentValues();
serviceValues.put(ServiceContract.ServiceEntry.COLUMN_NAME, name);
serviceValues.put(ServiceContract.ServiceEntry.COLUMN_ORGANIZATION_NAME, organizationName);
serviceValues.put(ServiceContract.ServiceEntry.COLUMN_PRICE, price);
cVVector.add(serviceValues);
}
int inserted = 0;
if(cVVector.size()>0)
{
ContentValues[] cvArray = new ContentValues[cVVector.size()];
cVVector.toArray(cvArray);
inserted = mContext.getContentResolver().bulkInsert(ServiceContract.ServiceEntry.CONTENT_URI, cvArray);
}
Log.d(LOG_TAG, "FetchServicesTask Complete. " + inserted + " Inserted");
}
catch(JSONException e)
{
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
/////////////////////////////// NETWORKING BOILER PLATE ///////////////////////////
#Override
protected Void doInBackground(String... params)
{
if (params.length == 0)
{
return null;
}
HttpURLConnection urlConnection = null; //Streaming data using HTTP
String serviceJsonStr = null; //raw JSON response
BufferedReader reader = null; //read text from character i/p stream
int pageNo = 1;
int numResults = 5;
try
{
//-------------------------CONNECTION--------------------//
final String SERVICE_BASE_URL = "http://myservicekart.com/public/";
final String SEARCH_BASE_URL = "http://myservicekart.com/public/search?";
final String SEARCH_PARAM = "search";
final String PAGE_PARAM = "pageno";
/*Using a helper class UriBuilder for building and manipulating URI references*/
Uri builtServiceUri = Uri.parse(SERVICE_BASE_URL);
Uri builtSearchUri = Uri.parse(SEARCH_BASE_URL).buildUpon().
appendQueryParameter(SEARCH_PARAM, "").
appendQueryParameter(PAGE_PARAM, Integer.toString(pageNo)).
build();
URL searchUrl = new URL(builtSearchUri.toString());
Log.v(LOG_TAG, "Built SearchUri" +builtSearchUri.toString());
urlConnection = (HttpURLConnection) searchUrl.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
//------------------------BUFFERING---------------------//
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if(inputStream==null)
{
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line = reader.readLine()) != null)
{
buffer.append(line + "\n");
}
if(buffer.length()==0)
{
return null;
}
serviceJsonStr = buffer.toString();
getServicesDatafromJson(serviceJsonStr);
Log.v(LOG_TAG, "Services JSON String: " +serviceJsonStr);
}
catch(IOException e)
{
Log.e(LOG_TAG, "Error cannot connect to URL", e);
return null;
}
catch (JSONException e)
{
e.printStackTrace();
}
finally
{
if(urlConnection!=null)
{
urlConnection.disconnect();
}
if(reader!=null)
{
try
{
reader.close();
}
catch (final IOException e)
{
Log.e(LOG_TAG,"Error closing stream",e);
}
}
}
return null;
}
}
In onCreate, you need to init your loader:
getLoaderManager().initLoader(SERVICE_LOADER , null, this);
// Or if you are using the support library, use this:
// getSupportLoaderManager().initLoader(SERVICE_LOADER , null, this);
I want to list my mssql records in android listview. Here is my codes;
activity;
public class YoneticiMenuActivity extends Activity {
JSONObject jsonObject = null;
//JSONArray jsonArray = null;
//public Is isler = new Is();
//public ArrayList<Is> arrayIsler = new ArrayList<Is>();
ListView lvTumIsler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yonetici_menu);
Intent iAl = getIntent();
String mesaj = iAl.getStringExtra(LoginActivity.m);
int mode = Activity.MODE_PRIVATE;
SharedPreferences mSP;
mSP = getSharedPreferences(mesaj, mode);
String baslik = mSP.getString("name", "") + " " + mSP.getString("surname", "") + ", Hoşgeldiniz";
setTitle(baslik);
lvTumIsler = (ListView)findViewById(R.id.lvTumIsler);
new AsyncTaskYonetici("Veriler yükleniyor...").execute();
}
private class AsyncTaskYonetici extends AsyncTask<Void, Void, Void> {
String modalMesaj;
ProgressDialog dialog;
JSONArray jsonArray = null;
JSONObject jsonObject = null;
public Is isler = new Is();
public ArrayList<Is> arrayIsler = new ArrayList<Is>();
//private ListView lvTumIsler;
public AsyncTaskYonetici(String mMesaj) {
this.modalMesaj = mMesaj;
this.dialog = new ProgressDialog(YoneticiMenuActivity.this);
}
#Override
protected void onPreExecute() {
dialog.setMessage(modalMesaj);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String url = "http://www.saklambacjeans.com/skbos/webServiceTumIsler.aspx";
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
String line = null;
try {
if ((line = reader.readLine()) != null) {
jsonArray = new JSONArray(line);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (ClientProtocolException e) {
Mesaj(e.getMessage());
} catch (IOException e) {
Mesaj(e.getMessage());
} /*catch (JSONException e) {
Mesaj(e.getMessage());
}*/
return null;
}
#Override
protected void onPostExecute(Void str) {
try {
for (int i = 0; i < jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
isler.setP(Integer.parseInt(jsonObject.getString("urunId").toString()),
Integer.parseInt(jsonObject.getString("modelNo").toString()),
jsonObject.getString("modelAd").toString(),
jsonObject.getString("bedenAd").toString(),
Integer.parseInt(jsonObject.getString("adet").toString()),
jsonObject.getString("aciklama").toString(),
jsonObject.getString("kesmeTalimat").toString(),
jsonObject.getString("atolyeTalimat").toString(),
jsonObject.getString("yıkamaTalimat").toString(),
jsonObject.getString("utuTalimat").toString(),
jsonObject.getString("kesimci").toString(),
jsonObject.getString("atolyeci").toString(),
jsonObject.getString("yıkamacı").toString(),
jsonObject.getString("utucu").toString(), jsonObject.getString("kontrolcu").toString());
arrayIsler.add(isler);
}
} catch (JSONException e) {
e.printStackTrace();
}
IsAdapter adapter = new IsAdapter(YoneticiMenuActivity.this, R.layout.layouttumisler, arrayIsler);
lvTumIsler.setAdapter(adapter);
if (dialog.isShowing())
dialog.dismiss();
}
}
private void Mesaj(String s) {
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
my adapter;
public class IsAdapter extends ArrayAdapter<Is> {
private ArrayList<Is> arrayIsler;
Context context;
public IsAdapter(Context context, int layoutResourceId, ArrayList<Is> a) {
super(context, layoutResourceId, a);
this.arrayIsler = a;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.layouttumisler, null);
}
Is is = arrayIsler.get(position);
if (is != null) {
TextView tvId = (TextView) row.findViewById(R.id.tvId);
TextView tvModel = (TextView) row.findViewById(R.id.tvModel);
TextView tvAtolye = (TextView) row.findViewById(R.id.tvAtolye);
TextView tvUrunId = (TextView) row.findViewById(R.id.tvUrunId);
TextView tvUrunModel = (TextView) row.findViewById(R.id.tvUrunModel);
TextView tvUrunAtolye = (TextView) row.findViewById(R.id.tvUrunAtolye);
if (tvId != null){
tvId.setText("Ürün No: ");
}
if (tvUrunId != null){
tvUrunId.setText(is.getId());
}
if (tvModel != null){
tvModel.setText("Model: ");
}
if (tvUrunModel != null){
tvUrunModel.setText(is.getModel());
}
if (tvAtolye != null){
tvAtolye.setText("Atolye: ");
}
if (tvUrunAtolye != null){
tvUrunAtolye.setText(is.getAtolye());
}
}
return row;
}
}
my Is class;
public class Is {
public int urunId;
public int modelNo;
public String modelAd;
public String bedenAd;
public int adet;
public String aciklama;
public String kesmeTalimat;
public String atolyeTalimat;
public String yikamaTalimat;
public String utuTalimat;
public String kesimci;
public String atolyeci;
public String yikamaci;
public String utucu;
public String kontrolcu;
public int getId() {return urunId;}
public String getModel() {return modelAd;}
public String getAtolye() {return atolyeci;}
public void setP(int u, int mN, String mA, String bA, int a, String ac, String kT, String aT, String yT, String uT,
String k, String at, String y, String utu, String ko)
{
urunId = u;
modelNo = mN;
modelAd = mA;
bedenAd = bA;
adet = a;
aciklama = ac;
kesmeTalimat = kT;
atolyeTalimat = aT;
yikamaTalimat = yT;
utuTalimat = uT;
kesimci = k;
atolyeci = at;
yikamaci = y;
utucu = utu;
kontrolcu = ko;
}
}
I use listview in main layout and there is 6 textview in layouttumısler. I use IsAdapter in onPostExecute in myAsyncTask but when I execute the app it is stopped.
The mssql records come from web service truely, But I can not list. I take error in IsAdapter getView, in
tvUrunId.setText(is.getId());
please help me...
I made a bad mistake, when I change
public int getId() {return urunId;}
as
public String getId()
{
String s = Integer.toString(urunId);
return s;
}
the code works.