This is simple Android project that I did. I get no warnings or errors while running. But the ListView doesn't get populated. I don't understand what's going wrong.
Since I dont' understand where is the exact problem and copy-pasting all the code won't help, here is my project code repository: https://bitbucket.org/geejo/msk-v2
Any kind of help will be appreciated
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_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);
}
}
FetchServices.java (AsyncTasks)
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));
}
}
change the method newView() in ServiceAdapter.java to :
public View newView(Context context, Cursor cursor, ViewGroup parent){
View view = LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, parent, false);
return view;}
Related
Hi I am working on the Udacity Popular movies project. I have to store the movies user chooses in a content provider as his favorites. I have created a content provider and I am fetching the data from it using a cursor loader and displaying it a recycler view when the user chooses the favorites option. My issue is that the data is not being persisted in my app. After I remove the app from my stack and reopen the app the favorites screen is empty. What am I doing wrong?
This is my Main Activity:
public class MainActivity extends AppCompatActivity implements CustomCursorAdapter.CustomCursorAdapterOnClickHandler,ImagesAdapter.ImagesAdapterOnClickHandler,LoaderManager.LoaderCallbacks<Cursor> {
private final String POPULAR_WEBSITE = "https://api.themoviedb.org/3/movie/popular?API_KEY";
private final String RATED_WEBSITE = "https://api.themoviedb.org/3/movie/top_rated?API_KEY";
// private final String RATED_WEBSITE = "https://api.themoviedb.org/3/movie/top_rated?API_KEY";
private ArrayList<String> list = new ArrayList<>();
ImagesAdapter adapter;
TextView errorTextView ;
ProgressBar progressBar;
RecyclerView recyclerView;
Bundle savedState = null;
ArrayList<MoviesClass> moviesClassList = new ArrayList<>();
final String TAG = MainActivity.class.getSimpleName();
CustomCursorAdapter simpleCursorAdapter;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
errorTextView = (TextView)findViewById(R.id.tv_error_message);
progressBar=(ProgressBar)findViewById(R.id.progressBar);
recyclerView = (RecyclerView)findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
getLoaderManager().initLoader(1,null,this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),2);
simpleCursorAdapter = new CustomCursorAdapter(this,null,this);
recyclerView.setLayoutManager(layoutManager);
adapter = new ImagesAdapter(this);
recyclerView.setAdapter(adapter);
this.runOnUiThread(new Runnable() {
public void run() {
try {
if (NetworkUtility.isOnline()) {
loadData(POPULAR_WEBSITE);
} else {
// Toast.makeText(MainActivity.this, "No internet connection", Toast.LENGTH_LONG).show();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this,android.R.style.Theme_Material_Light_Dialog_Alert);
// Setting Dialog Title
alertDialog.setTitle(R.string.no_internet_connection);
// Setting Dialog Message
alertDialog.setMessage(R.string.exit);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton(R.string.positive_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
Toast.makeText(getApplicationContext(), R.string.exit_activity, Toast.LENGTH_SHORT).show();
finish();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton(R.string.negative_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
Toast.makeText(getApplicationContext(),R.string.connection_check, Toast.LENGTH_SHORT).show();
dialog.cancel();
MainActivity.this.recreate();
}
});
// Showing Alert Message
alertDialog.show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void loadData(String data) {
showDataView();
new DownloadTask().execute(data);
}
#Override
public void mClick(int position) {
Intent intent = new Intent(this, MovieDetails.class);
MoviesClass currentMovie = moviesClassList.get(position);
intent.putExtra("current movie", currentMovie);
startActivity(intent);
}
private void showDataView() {
errorTextView.setVisibility(View.INVISIBLE);
recyclerView.setVisibility(View.VISIBLE);
}
public void showError() {
errorTextView.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.INVISIBLE);
}
#Override
public CursorLoader onCreateLoader(int i, Bundle bundle) {
CursorLoader cursorLoader = new CursorLoader(this,FavouritesContractClass.FavouriteMovies.CONTENT_URI,null,null,null,null);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader loader, Cursor o) {
// simpleCursorAdapter = new CustomCursorAdapter(this,o,this);
simpleCursorAdapter.swapCursor(o);
}
#Override
public void onLoaderReset(Loader loader) {
simpleCursorAdapter.swapCursor(null);
}
#Override
public void click(int position) {
}
public class DownloadTask extends AsyncTask<String,Void,ArrayList<String>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(ArrayList<String> s) {
progressBar.setVisibility(View.INVISIBLE);
showDataView();
adapter.setAdapterData(s);
// onSaveInstanceState(savedState);
}
#Override
protected ArrayList<String> doInBackground(String... strings) {
String response = null;
ArrayList<String> imagesList = new ArrayList<>();
ArrayList<String> uriList = new ArrayList<>();
if (strings.length == 0)
return null;
try {
response = NetworkUtility.makeHttpRequest(strings[0]);
if (response == null)
Toast.makeText(MainActivity.this, R.string.error_message, Toast.LENGTH_SHORT).show();
moviesClassList = ParseData.getMoviesObject(response);
for(int i =0; i< moviesClassList.size();i++)
Log.i(TAG, moviesClassList.get(0).getmId());
MoviesClass moviesClass = null;
for (int i = 0; i < moviesClassList.size(); i++) {
moviesClass = moviesClassList.get(i);
Log.i("movie name is",moviesClass.getmTitle());
imagesList.add(moviesClass.getmPosterPath());
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.appendEncodedPath("/image.tmdb.org/t/p/w185")
.appendEncodedPath(imagesList.get(i)).build();
uriList.add(builder.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
return uriList;
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.popular_sort:
loadData(POPULAR_WEBSITE);
return true;
case R.id.rated_sort:
loadData(RATED_WEBSITE);
return true;
case R.id.fav_sort:
/*try {
while (cursor.moveToNext()) {
Log.i("url is ", cursor.getString(cursor.getColumnIndex("url")));
list.add(cursor.getString(cursor.getColumnIndex("url")));
}
}finally {
cursor.close();
}*/
recyclerView.setAdapter(simpleCursorAdapter);
simpleCursorAdapter.notifyDataSetChanged();
return true;
default:
return false;
}
}
This my content provider class ;
public class FavouritesContentProvider extends ContentProvider {
public static final int MOVIES = 100;
public static final int MOVIE_ID = 101;
private MovieDbOpenHelper dbOpenHelper;
Cursor cursor;
#Override
public boolean onCreate() {
Context context = getContext();
dbOpenHelper = new MovieDbOpenHelper(context,null,null,1);
return true;
}
public UriMatcher sUriMatcher = buildUriMatcher();
private UriMatcher buildUriMatcher() {
UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(FavouritesContractClass.AUTHORITY,FavouritesContractClass.PATH_FAVOURITES,MOVIES);
uriMatcher.addURI(FavouritesContractClass.AUTHORITY,FavouritesContractClass.PATH_FAVOURITES + "/#",MOVIE_ID);
return uriMatcher;
}
#Nullable
#Override
public Cursor query(#NonNull Uri uri, #Nullable String[] strings, #Nullable String s, #Nullable String[] strings1, #Nullable String s1) {
SQLiteDatabase sqLiteDatabase = dbOpenHelper.getReadableDatabase();
int match = sUriMatcher.match(uri);
switch (match) {
case MOVIES:
cursor = sqLiteDatabase.query(FavouritesContractClass.FavouriteMovies.TABLE_NAME, strings, s, strings1, null, null, s1);
break;
case MOVIE_ID:
cursor = sqLiteDatabase.query(FavouritesContractClass.FavouriteMovies.TABLE_NAME, strings, s, strings1, null, null, s1);
break;
default:
throw new UnsupportedOperationException("Unknown uri:" + uri);
}
cursor.setNotificationUri(getContext().getContentResolver(),uri);
return cursor;
}
#Nullable
#Override
public String getType(#NonNull Uri uri) {
int match = sUriMatcher.match(uri);
switch (match) {
case MOVIES:
// directory
return "vnd.android.cursor.dir" + "/" + FavouritesContractClass.AUTHORITY + "/" + FavouritesContractClass.FavouriteMovies.CONTENT_URI;
case MOVIE_ID:
// single item type
return "vnd.android.cursor.item" + "/" + FavouritesContractClass.AUTHORITY + "/" + FavouritesContractClass.FavouriteMovies.CONTENT_URI;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
#Nullable
#Override
public Uri insert(#NonNull Uri uri, #Nullable ContentValues contentValues) {
SQLiteDatabase sqLiteDatabase = dbOpenHelper.getWritableDatabase();
int match = sUriMatcher.match(uri);
Uri returnUri = null;
switch (match) {
case MOVIES:
long id = sqLiteDatabase.insertWithOnConflict(FavouritesContractClass.FavouriteMovies.TABLE_NAME, null, contentValues,SQLiteDatabase.CONFLICT_IGNORE);
if (id > 0)
returnUri = ContentUris.withAppendedId(FavouritesContractClass.FavouriteMovies.CONTENT_URI, id);
else
Toast.makeText(getContext(), "Already exists.", Toast.LENGTH_SHORT).show();
break;
default:
throw new UnsupportedOperationException("Unknown uri" + uri);
}
getContext().getContentResolver().notifyChange(uri,null);
return returnUri;
}
#Override
public int delete(#NonNull Uri uri, #Nullable String s, #Nullable String[] strings) {
return 0;
}
#Override
public int update(#NonNull Uri uri, #Nullable ContentValues contentValues, #Nullable String s, #Nullable String[] strings) {
return 0;
}
}
This is the movie details class:
public class MovieDetails extends AppCompatActivity implements View.OnClickListener {
public final String trailerBaseUri = "https://api.themoviedb.org/3/movie/";
String movieId;
Uri movieFinalUri, movieReviewUri;
ArrayList<MovieTrailerClass> movieTrailersList;
String movieReviewsList;
Uri.Builder builder;
MoviesClass currentMovie;
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_details);
TextView title = (TextView) findViewById(R.id.title_tv);
TextView synopsis = (TextView) findViewById(R.id.synopsis_tv);
TextView userRating = (TextView) findViewById(R.id.rating_tv);
TextView date = (TextView) findViewById(R.id.date_tv);
ImageView imageView = (ImageView) findViewById(R.id.poster_thumbnail);
Intent intent = getIntent();
ImageView trailer1 = (ImageView) findViewById(R.id.trailer1);
ImageView trailer2 = (ImageView) findViewById(R.id.trailer2);
trailer1.setOnClickListener(this);
trailer2.setOnClickListener(this);
if (intent.hasExtra("current movie")) {
currentMovie = intent.getParcelableExtra("current movie");
builder = new Uri.Builder();
builder.scheme("http")
.appendEncodedPath("/image.tmdb.org/t/p/w185")
.appendEncodedPath(currentMovie.getmPosterPath()).build();
movieId = currentMovie.getmId();
title.setText(currentMovie.getmTitle());
synopsis.setText(currentMovie.getmSynopsis());
userRating.setText(currentMovie.getmRating() + "/10");
date.setText(currentMovie.getmReleaseDate());
movieFinalUri = Uri.parse(trailerBaseUri).buildUpon().appendPath(movieId).appendPath("videos").appendQueryParameter("api_key", "ebd331efd1f9bec67a9aa215b256ebe1")
.appendQueryParameter("language", "en").build();
Picasso.with(getApplicationContext())
.load(builder.toString())
.placeholder(R.drawable.popcorn_placeholder)
.error(R.drawable.error)
.resize(800, 1000)
.into(imageView);
movieTrailersList = new ArrayList<>();
DownloadTask task = new DownloadTask();
task.execute(movieFinalUri.toString());
movieReviewUri = Uri.parse(trailerBaseUri).buildUpon().appendPath(movieId).appendPath("reviews").appendQueryParameter("api_key", "ebd331efd1f9bec67a9aa215b256ebe1")
.appendQueryParameter("language", "en").build();
ReviewDownloadTask task1 = new ReviewDownloadTask();
task1.execute(movieReviewUri.toString());
// String movieReviewsExtra = getIntent().getStringExtra("movieReviewList");
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.trailer1:
openTrailer(movieTrailersList.get(0).getKey());
break;
case R.id.rating_tv:
Intent intent = new Intent(MovieDetails.this, ReviewActivity.class);
intent.putExtra("movieReviewList", movieReviewsList);
startActivity(intent);
/* case R.id.trailer3:
openTrailer(movieTrailersList.get(2).getKey());
break;*/
}
}
public void openTrailer(String key) {
Uri uri = Uri.parse("https://www.youtube.com/watch?").buildUpon().appendQueryParameter("v", key).build();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(uri);
startActivity(intent);
}
public void openReview(String url) {
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW);
if(intent.resolveActivity(getPackageManager())!=null) {
intent.setData(uri);
startActivity(intent);
}else
Toast.makeText(this, "Unable to find browser to launch movie trailer!", Toast.LENGTH_SHORT).show();
}
public void markAsFavourite(View view) {
ContentValues contentValues = new ContentValues();
contentValues.put(FavouritesContractClass.FavouriteMovies.MOVIE_URL, builder.toString());
contentValues.put(FavouritesContractClass.FavouriteMovies.MOVIE_ID, movieId);
/*if(checkAlreadyExist()){
Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
} else {*/
Uri uri = getContentResolver().insert(FavouritesContractClass.FavouriteMovies.CONTENT_URI, contentValues);
if (uri != null) {
Toast.makeText(this, R.string.movie_saved_toast, Toast.LENGTH_SHORT).show();
Log.i("insert successsful", uri.toString());
} else
Log.i("insert not successsful", "suc");
}
class DownloadTask extends AsyncTask<String, Void, ArrayList<MovieTrailerClass>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
#Override
protected ArrayList<MovieTrailerClass> doInBackground(String... strings) {
try {
String response = NetworkUtility.makeHttpRequest(movieFinalUri.toString());
if (response != null) {
JSONObject baseObj = new JSONObject(response);
JSONArray resObject = baseObj.getJSONArray("results");
Gson gson = new Gson();
movieTrailersList = gson.fromJson(resObject.toString(), new TypeToken<List<MovieTrailerClass>>() {
}.getType());
} else {
Toast.makeText(MovieDetails.this, R.string.error_message, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return movieTrailersList;
}
}
public class ReviewDownloadTask extends AsyncTask<String, Void, String> {
String response = null;
#Override
protected void onPostExecute(String s) {
Gson gson = new Gson();
ArrayList<MovieReviewResults> movieReviewResults = gson.fromJson(movieReviewsList, new TypeToken<List<MovieReviewResults>>() {
}.getType());
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
for (MovieReviewResults movieReviewObject : movieReviewResults) {
TextView textView = new TextView(getApplicationContext());
textView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setGravity((Gravity.CENTER));
linearLayout.addView(textView);
textView.setText(movieReviewObject.getContent());
TextView textView1 = new TextView(getApplicationContext());
textView1.setGravity((Gravity.CENTER));
textView1.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
linearLayout.addView(textView1);
textView1.setText(movieReviewObject.getAuthor());
}
}
#Override
protected String doInBackground(String... strings) {
try {
response = NetworkUtility.makeHttpRequest(strings[0]);
if (response != null) {
JSONObject baseObj = new JSONObject(response);
JSONArray resObject = baseObj.getJSONArray("results");
movieReviewsList = resObject.toString();
} else {
Toast.makeText(MovieDetails.this, R.string.error_message, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return movieReviewsList;
}
}
public boolean checkAlreadyExist()
{
String query = "SELECT " + FavouritesContractClass.FavouriteMovies.MOVIE_ID + " FROM " + FavouritesContractClass.FavouriteMovies.TABLE_NAME + " WHERE " + FavouritesContractClass.FavouriteMovies.MOVIE_ID + " = " + movieId;;
MovieDbOpenHelper dbOpenHelper = new MovieDbOpenHelper(getApplicationContext(),null,null,1);
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
Log.i(" ai mger","here");
if (cursor.getCount() > 0)
{
Log.i("fpund","funf");
return true;
}
else
return false;
}
}
You might want to try calling beginTransaction before inserting/updating/deleting, setTransactionSuccessful when you want the changes to be committed and endTransaction to commit the changes. Please see code below (NOTE: I didn't test this code as I'm writing this on a tablet)
You should also take a look at the docs for more information.
#Nullable
#Override
public Uri insert(#NonNull Uri uri, #Nullable ContentValues contentValues) {
SQLiteDatabase sqLiteDatabase = dbOpenHelper.getWritableDatabase();
int match = sUriMatcher.match(uri);
Uri returnUri = null;
switch (match) {
case MOVIES:
sqLiteDatabase.beginTransaction();
try {
long id = sqLiteDatabase.insertWithOnConflict(FavouritesContractClass.FavouriteMovies.TABLE_NAME, null, contentValues, SQLiteDatabase.CONFLICT_IGNORE);
if (id > 0)
returnUri = ContentUris.withAppendedId(FavouritesContractClass.FavouriteMovies.CONTENT_URI, id);
sqLiteDatabase.setTransactionSuccessful();
} finally {
sqLiteDatabase.endTransaction();
}
break;
default:
throw new UnsupportedOperationException("Unknown uri" + uri);
}
getContext().getContentResolver().notifyChange(uri,null);
return returnUri;
}
How to do the Filter concept from Below design? I here by attached two screen designs.
DashBoard Fragment -> Having Listview with Base adapter.
The above ListView code is given Below
DashBoardRefactor
public class DashBoardRefactor extends Fragment {
public static ProgressDialog progress;
public static List<DashListModel> dashRowList1 = new ArrayList<DashListModel>();
public static View footerView;
// #Bind(R.id.dashListView)
public static ListView dashListView;
int preCount = 2, scroll_Inc = 10, lastCount;
boolean flag = true;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dashboard_fragment, container, false);
ButterKnife.bind(this, v);
setHasOptionsMenu(true);
progress = new ProgressDialog(getActivity());
dashListView = (ListView) v.findViewById(R.id.dashListView);
footerView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.dashboard_list_footer, null, false);
dashListView.addFooterView(footerView);
footerView.setVisibility(View.GONE);
dashRowList1.clear();
dashboardViewTask();
dashListView.setOnScrollListener(new EndlessScrollListener(getActivity(), dashListView, footerView));
return v;
}
public void dashboardViewTask() {
progress.setMessage("Loading...");
progress.setCanceledOnTouchOutside(false);
progress.setCancelable(false);
progress.show();
// footerView.setVisibility(View.VISIBLE);
Map<String, String> params = new HashMap<String, String>();
Log.e("candidate_id", "candidate_id---->" + SessionStores.getBullHornId(getActivity()));
params.put("candidate_id", SessionStores.getBullHornId(getActivity()));
params.put("employmentPreference", SessionStores.getEmploymentPreference(getActivity()));
params.put("page", "1");
new DashBoardTask(getActivity(), params, dashListView, footerView);
}
#Override
public void onCreateOptionsMenu(
Menu menu, MenuInflater inflater) {
if (menu != null) {
menu.removeItem(R.id.menu_notify);
}
inflater.inflate(R.menu.menu_options, menu);
MenuItem item = menu.findItem(R.id.menu_filter);
item.setVisible(true);
getActivity().invalidateOptionsMenu();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.his__menu_accept:
Toast.makeText(getActivity(), "clicked dashboard menu accept", Toast.LENGTH_LONG).show();
return true;
case R.id.menu_filter:
// click evnt for filter
Toast.makeText(getActivity(), "clicked dashboard filter", Toast.LENGTH_LONG).show();
Intent filter_intent = new Intent(getActivity(), DashBoardFilterScreen.class);
startActivity(filter_intent);
getActivity().overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onPause() {
super.onPause();
// dashboardViewTask();
}
}
DashBoardTask:
public class DashBoardTask {
public static String candidateIdNo;
public static Integer isBookmarked;
public ListAdapter dashListAdapter;
ListView dashListView;
View footerView;
String fromdate_formated = "";
String todate_formated = "";
private Context context;
private JSONObject jObject = null;
private String result, authorizationKey;
private Map<String, String> params;
public DashBoardTask(Context context, Map<String, String> params, ListView dashListView, View footerView) {
this.context = context;
Log.e("context ", "DashBoardTask: " + context);
this.dashListView = dashListView;
Dashboard.dashRowList.clear();
this.params = params;
this.footerView = footerView;
ResponseTask();
}
private void ResponseTask() {
authorizationKey = Constants.ACCESS_TOKEN;
new ServerResponse(ApiClass.getApiUrl(Constants.DASHBOARD_VIEW)).getJSONObjectfromURL(ServerResponse.RequestType.POST, params, authorizationKey, context, "", new VolleyResponseListener() {
#Override
public void onError(String message) {
if (DashBoardRefactor.progress.isShowing()) {
DashBoardRefactor.progress.dismiss();
}
}
#Override
public void onResponse(String response) {
String dateEnd = "", startDate = "";
result = response.toString();
try {
jObject = new JSONObject(result);
if (jObject != null) {
Integer totalJobList = jObject.getInt("page_count");
Integer total = jObject.getInt("total");
Integer count = jObject.getInt("count");
Integer start = jObject.getInt("start");
if (footerView.isShown() && count == 0) {
footerView.setVisibility(View.GONE);
}
Integer Status = jObject.getInt("status");
if (Status == 1) {
SessionStores.savetotalJobList(totalJobList, context);
JSONArray dataObject = jObject.getJSONArray("data");
Dashboard.dashRowList.clear();
for (int i = 0; i < dataObject.length(); i++) {
Log.e("length", "lenght----->" + dataObject.length());
JSONObject jobDetail = dataObject.getJSONObject(i);
Log.e("jobDetail", "jobDetail----->" + jobDetail);
Integer goalsName = jobDetail.getInt("id");
String compnyTitle = jobDetail.getString("title");
String description = jobDetail.getString("description");
Integer salary = jobDetail.getInt("salary");
String dateAdded = jobDetail.getString("dateAdded");
if (jobDetail.getString("startDate") != null && !jobDetail.getString("startDate").isEmpty() && !jobDetail.getString("startDate").equals("null")) {
startDate = jobDetail.getString("startDate");
} else {
Log.e("Task Null", "Task Null----startDate->");
}
if (jobDetail.getString("dateEnd") != null && !jobDetail.getString("dateEnd").isEmpty() && !jobDetail.getString("dateEnd").equals("null")) {
dateEnd = jobDetail.getString("dateEnd");
} else {
Log.e("Task Null", "Task Null----->");
}
isBookmarked = jobDetail.getInt("isBookmarked");
Integer startSalary = jobDetail.getInt("customFloat1");
Integer endSalary = jobDetail.getInt("customFloat2");
JSONObject cmpanyName = jobDetail.getJSONObject("clientCorporation");
String compnyNamede = cmpanyName.getString("name");
String city = jobDetail.getString("customText1");
JSONObject candidateId = jobDetail.getJSONObject("clientContact");
candidateIdNo = candidateId.getString("id");
DashListModel dashListItem = new DashListModel();
dashListItem.setDashCompanyName(compnyNamede);
dashListItem.setDashJobDescription(description);
dashListItem.setDashJobPosition(compnyTitle);
dashListItem.setDashJobCity(city);
// dashListItem.setDashJobState(state);
dashListItem.setDashSalary(startSalary.toString());
dashListItem.setDashJobAvailableDate(dateAdded);
dashListItem.setDashId(goalsName.toString());
dashListItem.setDashIsBookMarked(isBookmarked.toString());
dashListItem.setDashEndSalary(endSalary.toString());
dashListItem.setToDate(dateEnd);
////////////////////////////////////
String fromDate = null, toDate = null, postedDate = null;
if (startDate.length() > 11) {
Log.e("11", "11---->");
fromDate = Utils.convertFromUnixDateAdded(startDate);
} else if (startDate.length() == 10) {
Log.e("10", "10----->");
fromDate = Utils.convertFromUnix(startDate);
}
if (dateEnd.length() > 11) {
Log.e("11", "11---->");
toDate = Utils.convertFromUnixDateAdded(dateEnd);
} else if (dateEnd.length() == 10) {
Log.e("10", "10----->");
toDate = Utils.convertFromUnix(dateEnd);
}
if (dateAdded.length() > 11) {
Log.e("11", "11---->");
postedDate = Utils.convertFromUnixDateAdded(dateAdded);
} else if (dateAdded.length() == 10) {
Log.e("10", "10----->");
postedDate = Utils.convertFromUnix(dateAdded);
}
try {
if (!fromDate.isEmpty() || !fromDate.equalsIgnoreCase("null")) {
String[] fromDateSplit = fromDate.split("/");
String fromMonth = fromDateSplit[0];
String fromDat = fromDateSplit[1];
String fromYear = fromDateSplit[2];
String fromMonthName = new DateFormatSymbols().getMonths()[Integer.parseInt(fromMonth) - 1];
fromdate_formated = fromMonthName.substring(0, 3) + " " + fromDat + getDayOfMonthSuffix(Integer.parseInt(fromDat));
Log.e("fromdate", "fromdate---->" + fromDate);
Log.e("toDate", "toDate---->" + toDate);
Log.e("fromMonth", "fromMonth---->" + fromMonth);
Log.e("fromDat", "fromDat---->" + fromDat);
Log.e("fromYear", "fromYear---->" + fromYear);
}
if (!toDate.isEmpty() || !toDate.equalsIgnoreCase("null")) {
String[] toDateSplit = toDate.split("/");
String toMonth = toDateSplit[0];
String toDat = toDateSplit[1];
String toYear = toDateSplit[2];
String toMonthName = new DateFormatSymbols().getMonths()[Integer.parseInt(toMonth) - 1];
todate_formated = toMonthName.substring(0, 3) + " " + toDat + getDayOfMonthSuffix(Integer.parseInt(toDat)) + " " + toYear;
Log.e("________________", "-------------------->");
Log.e("toMonth", "toMonth---->" + toMonth);
Log.e("toDat", "toDat---->" + toDat);
Log.e("toYear", "toYear---->" + toYear);
Log.e("________________", "-------------------->");
Log.e("toMonthName", "toMonthName---->" + toMonthName);
}
} catch (Exception e) {
e.printStackTrace();
}
dashListItem.setPostedDate(postedDate);
dashListItem.setFromDate(fromdate_formated);
dashListItem.setEndDate(todate_formated);
/////////////////////////////////////////
// Dashboard.dashRowList.add(dashListItem);
DashBoardRefactor.dashRowList1.add(dashListItem);
}
// get listview current position - used to maintain scroll position
int currentPosition = dashListView.getFirstVisiblePosition();
dashListAdapter = new DashListAdapter(context, DashBoardRefactor.dashRowList1, dashListView);
dashListView.setAdapter(dashListAdapter);
((BaseAdapter) dashListAdapter).notifyDataSetChanged();
if (currentPosition != 0) {
// Setting new scroll position
dashListView.setSelectionFromTop(currentPosition + 1, 0);
}
} else if (Status==0 && count==0 && start==0){
String Message = jObject.getString("message");
Utils.ShowAlert(context, Message);
}
if (footerView.isShown()) {
footerView.setVisibility(View.GONE);
}
//progress.dismiss();
if (DashBoardRefactor.progress.isShowing()) {
try {
DashBoardRefactor.progress.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
}
DashListModel:
public class DashListModel {
private String dashCompanyName;
private String dashJobPosition;
private String dashJobPostedDate;
private String dashJobDescription;
private String dashSalary;
private String dashJobCity;
private String dashJobState;
private String dashJobAvailableDate;
private String dashId, dashIsBookmarked;
private String dashEndSalary;
private String toDate;
private String postedDate, fromdate, enddate;
public String getDashCompanyName() {
return dashCompanyName;
}
public void setDashCompanyName(String dashCompanyName) {
this.dashCompanyName = dashCompanyName;
}
public String getDashJobPosition() {
return dashJobPosition;
}
public void setDashJobPosition(String dashJobPosition) {
this.dashJobPosition = dashJobPosition;
}
public String getDashJobDescription() {
return dashJobDescription;
}
public void setDashJobDescription(String dashJobDescription) {
this.dashJobDescription = dashJobDescription;
}
public String getDashJobPostedDate() {
return dashJobPostedDate;
}
public void setDashJobPostedDate(String dashJobPostedDate) {
this.dashJobPostedDate = dashJobPostedDate;
}
public String getDashSalary() {
return dashSalary;
}
public void setDashSalary(String dashSalary) {
this.dashSalary = dashSalary;
}
public String getDashJobCity() {
return dashJobCity;
}
public void setDashJobCity(String dashJobCity) {
this.dashJobCity = dashJobCity;
}
/* public String getDashJobState() {
return dashJobState;
}
public void setDashJobState(String dashJobState) {
this.dashJobState = dashJobState;
}*/
public String getDashJobAvailableDate() {
return dashJobAvailableDate;
}
public void setDashJobAvailableDate(String dashJobAvailableDate) {
this.dashJobAvailableDate = dashJobAvailableDate;
}
public String getDashId() {
return dashId;
}
public void setDashId(String dashId) {
this.dashId = dashId;
}
public String getDashIsBookmarked() {
return dashIsBookmarked;
}
public void setDashIsBookMarked(String dashIsBookmarked) {
this.dashIsBookmarked = dashIsBookmarked;
}
public String getDashEndSalary() {
return dashEndSalary;
}
public void setDashEndSalary(String dashEndSalary) {
this.dashEndSalary = dashEndSalary;
}
public String getToDate() {
return toDate;
}
public void setToDate(String toDate) {
this.toDate = toDate;
}
public String getPostedDate() {
return postedDate;
}
public void setPostedDate(String postedDate) {
this.postedDate = postedDate;
}
public String getFromDate() {
return fromdate;
}
public void setFromDate(String fromdate) {
this.fromdate = fromdate;
}
public String getEndDate() {
return enddate;
}
public void setEndDate(String enddate) {
this.enddate = enddate;
}
DashListAdapter:
package com.peoplecaddie.adapter;
public class DashListAdapter extends BaseAdapter {
public static ListView dashListView;
Context c;
private LayoutInflater inflater;
private List<DashListModel> dashRowList;
public DashListAdapter(Context c, List<DashListModel> dashRowList, ListView dashListView) {
this.c = c;
this.dashListView = dashListView;
this.dashRowList = dashRowList;
}
#Override
public int getCount() {
return this.dashRowList.size();
}
#Override
public Object getItem(int position) {
return dashRowList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder dashHolder;
if (inflater == null)
inflater = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.dashboard_jobdetails_list, null);
final DashListModel dashModel = dashRowList.get(position);
dashHolder = new ViewHolder(convertView);
dashHolder.dash_company_name.setText(dashModel.getDashCompanyName());
dashHolder.dash_position_name.setText(dashModel.getDashJobPosition());
dashHolder.dash_posted_date.setText(dashModel.getPostedDate());
dashHolder.dash_job_description.setText(Utils.stripHtml(dashModel.getDashJobDescription()));
dashHolder.dash_salary.setText(dashModel.getDashSalary() + " - " + dashModel.getDashEndSalary());
dashHolder.dash_available_date.setText(dashModel.getFromDate() + " - " + dashModel.getEndDate());
dashHolder.book_jobCity.setText(dashModel.getDashJobCity());
if (dashModel.getDashIsBookmarked().equalsIgnoreCase("1")) {
dashHolder.bookmark_img.setImageResource(R.drawable.bookmark);
} else if (dashModel.getDashIsBookmarked().equalsIgnoreCase("0")) {
dashHolder.bookmark_img.setImageResource(R.drawable.blue_tag_img);
}
dashHolder.bookmark_img.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (dashModel.getDashIsBookmarked().equalsIgnoreCase("0")) {
dashModel.setDashIsBookMarked("1");
Map<String, String> params = new HashMap<String, String>();
params.put("candidate_id", SessionStores.getBullHornId(c));
params.put("joborder_id", dashModel.getDashId());
BackGroundTasks bookmark_add_bg_tasks = new BackGroundTasks(c, new JSONObject(params), Constants.BOOKMARK_ADD_TAG);
bookmark_add_bg_tasks.ResponseTask(new BackGroundTasks.VolleyCallbackOnEdit() {
#Override
public void onSuccess(String result) {
String resp_resultsd = result;
Log.e("insidecallback", " bookmark_add_bg_tasks----->" + resp_resultsd);
// finish();
dashHolder.bookmark_img.setImageResource(R.drawable.bookmark);
notifyDataSetChanged();
}
});
} else if (dashModel.getDashIsBookmarked().equalsIgnoreCase("1")) {
dashModel.setDashIsBookMarked("0");
Log.e("imgchange", " imgchange");
Map<String, String> params = new HashMap<String, String>();
params.put("candidate_id", SessionStores.getBullHornId(c));
params.put("joborder_id", dashModel.getDashId());
BackGroundTasks bookmark_delete_bg_tasks = new BackGroundTasks(c, new JSONObject(params), Constants.BOOKMARK_DELETE_TAG);
bookmark_delete_bg_tasks.ResponseTask(new BackGroundTasks.VolleyCallbackOnEdit() {
#Override
public void onSuccess(String result) {
String resp_resultsd = result;
Log.e("insidecallback", " bookmark_delete_bg_tasks----->" + resp_resultsd);
// finish();
dashHolder.bookmark_img.setImageResource(R.drawable.blue_tag_img);
notifyDataSetChanged();
}
});
}
}
});
return convertView;
}
static class ViewHolder {
#Bind(R.id.book_company_name)
TextView dash_company_name;
private RelativeLayout.LayoutParams viewLayParams;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
Clarification:
How do to Filter while click the Filter Button On DashBoard Fragment. Please Suggest the way. I here by attached My Filter design also.
Dashboard Fragment--> Filter Button-> Filter screen-> the Filtered results should view on DashBoard Fragment.
Once click the apply Button Based on the input from Filter screen it filters the list view the result comes from back end team. I have to display that result on Dashboard Fragment.
Kindly please clarify this Filter concept.
When i start up the app it loads all the movie posters correctly. When i click on a poster it should start DetailActivity and display the poster i selected. However every poster i click all displays the same one.
MainActivityFragment
/**
* A placeholder fragment containing a simple view.
*/
public class MainActivityFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{
private static final int MOVIE_LOADER = 0;
private final String LOG_TAG = MainActivityFragment.class.getSimpleName();
private static final String[] MOVIE_COLUMNS = {
MovieContract.MovieEntry.TABLE_NAME + "." + MovieContract.MovieEntry._ID,
MovieContract.MovieEntry.COLUMN_MOVIE_POSTER
};
static final int COL_MOVIE_ID = 0;
static final int COL_MOVIE_URL = 1;
private MovieAdapter mMovieAdapter;
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMovieAdapter = new MovieAdapter(getActivity(),null,0);
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
GridView gridView = (GridView) rootView.findViewById(R.id.movieposter_image_gridview);
gridView.setAdapter(mMovieAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l){
Cursor cursor = (Cursor)adapterView.getItemAtPosition(position);
if(cursor != null){
Intent intent = new Intent(getActivity(), DetailActivity.class)
.setData(MovieContract.MovieEntry.CONTENT_URI);
startActivity(intent);
Log.d("DEBUG", "Selected item position " + position + ", with id: " + l);
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
getLoaderManager().initLoader(MOVIE_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
private void updateApplication() {
FetchMovieTask movieTask = new FetchMovieTask(getActivity());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String sortBy = prefs.getString(getString(R.string.pref_sort_by_key),
getString(R.string.pref_popular_default));
movieTask.execute(sortBy);
}
#Override
public void onStart() {
super.onStart();
updateApplication();
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle){
Uri movieUri = MovieContract.MovieEntry.CONTENT_URI;
return new CursorLoader(getActivity(),
movieUri,
MOVIE_COLUMNS,
null,
null,
null);
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor){
mMovieAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader){
mMovieAdapter.swapCursor(null);
}
}
DetailActivity
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new DetailFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.detail, 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) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public static class DetailFragment extends Fragment implements LoaderCallbacks<Cursor> {
private final String LOG_TAG = DetailFragment.class.getSimpleName();
private static final String Movie_SHARE_HASHTAG = " #MovieApp";
private ShareActionProvider mShareActionProvider;
private String mMovie;
ImageView poster;
private static final int DETAIL_LOADER = 0;
private final String[] DETAIL_COLUMNS = {
MovieContract.MovieEntry.TABLE_NAME + "." + MovieContract.MovieEntry._ID,
MovieContract.MovieEntry.COLUMN_MOVIE_POSTER
};
private static final int COL_MOVIE_ID = 0;
private static final int COL_MOVIE_POSTER = 1;
public DetailFragment() {
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_detail, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(DETAIL_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.v(LOG_TAG, "In onCreateLoader");
Intent intent = getActivity().getIntent();
if (intent == null) {
return null;
}
return new CursorLoader(
getActivity(),
intent.getData(),
DETAIL_COLUMNS,
null,
null,
null
);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Log.v(LOG_TAG, "In onLoadFinished");
if (!data.moveToFirst()) {
return;
}
String posterURL = data.getString(COL_MOVIE_POSTER);
final String POSTERIMAGE_BASE_URL = "http://image.tmdb.org/t/p/";
final String POSTERIMAGE_SIZE = "w500";
poster = (ImageView) getView().findViewById(R.id.detailActivity_image_view);
final String POSTERIMAGE_URL = POSTERIMAGE_BASE_URL + POSTERIMAGE_SIZE + posterURL;
Picasso.with(this.getActivity()).load(POSTERIMAGE_URL).into(poster);
Log.v(LOG_TAG, "Poster Urls: " + POSTERIMAGE_URL);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
}
MovieAdapter
public class MovieAdapter extends CursorAdapter {
private final String LOG_TAG = MovieAdapter.class.getSimpleName();
public MovieAdapter(Context context, Cursor c, int flags){
super(context,c,flags);
}
private String convertCursorRowToUXFormat(Cursor cursor){
String poster = cursor.getString(MainActivityFragment.COL_MOVIE_URL);
return poster;
}
#Override
public View newView(Context context,Cursor cursor,ViewGroup parent){
View view = LayoutInflater.from(context).inflate(R.layout.poster_image, parent, false);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
final String POSTERIMAGE_BASE_URL = "http://image.tmdb.org/t/p/";
final String POSTERIMAGE_SIZE = "w500";
ImageView posterImage = (ImageView)view;
final String POSTERIMAGE_URL = POSTERIMAGE_BASE_URL + POSTERIMAGE_SIZE + convertCursorRowToUXFormat(cursor);
Picasso.with(context).load(POSTERIMAGE_URL).into(posterImage);
Log.v(LOG_TAG, "Poster Urls: " + POSTERIMAGE_URL);
}
}
FetchMovieTask
public class FetchMovieTask extends AsyncTask<String, Void, Void> {
private final String LOG_TAG = FetchMovieTask.class.getSimpleName();
private final Context mContext;
public FetchMovieTask(Context context) {
mContext = context;
}
private boolean DEBUG = true;
private void getMovieDataJSON(String movieJSONStr)
throws JSONException {
final String MDB_RESULT = "results";
final String MDB_POSTER = "poster_path";
final String MDB_MOVIE_TITLE = "original_title";
final String MDB_MOVIE_PLOT = "overview";
final String MDB_MOVIE_RATING = "popularity";
final String MDB_RELEASE_DATE = "release_date";
try {
JSONObject movieJSON = new JSONObject(movieJSONStr);
JSONArray movieArray = movieJSON.getJSONArray(MDB_RESULT);
Vector<ContentValues> cVVector = new Vector<>(movieArray.length());
for (int i = 0; i < movieArray.length(); i++) {
String poster;
String title;
String plot;
String rating;
String releaseDate;
//Get theJSON object representing the movie
JSONObject movieDetail = movieArray.getJSONObject(i);
poster = movieDetail.getString(MDB_POSTER);
title = movieDetail.getString(MDB_MOVIE_TITLE);
plot = movieDetail.getString(MDB_MOVIE_PLOT);
rating = movieDetail.getString(MDB_MOVIE_RATING);
releaseDate = movieDetail.getString(MDB_RELEASE_DATE);
ContentValues movieDetailValues = new ContentValues();
movieDetailValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_NAME, title);
movieDetailValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_POSTER, poster);
movieDetailValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_PLOT, plot);
movieDetailValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_RATING, rating);
movieDetailValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_REDATE, releaseDate);
cVVector.add(movieDetailValues);
}
int inserted = 0;
if (cVVector.size() > 0) {
ContentValues[] cvArray = new ContentValues[cVVector.size()];
cVVector.toArray(cvArray);
inserted = mContext.getContentResolver().bulkInsert(MovieContract.MovieEntry.CONTENT_URI, cvArray);
}
Log.d(LOG_TAG, "FetchMovieTask Complete. " + inserted + " Inserted");
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
}
#Override
protected Void doInBackground (String...params){
if (params.length == 0) {
return null;
}
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String movieJSONStr = null;
try {
final String MOVIE_BASE_URL = "http://api.themoviedb.org/3/movie";
Uri builtUri = Uri.parse(MOVIE_BASE_URL).buildUpon()
.appendPath(params[0])
.appendQueryParameter("api_key", BuildConfig.MOVIE_API_KEY)
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built URI " + builtUri.toString());
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) {
return null;
}
movieJSONStr = buffer.toString();
getMovieDataJSON(movieJSONStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
}
catch(JSONException e){
Log.e(LOG_TAG, e.getMessage(), 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;
}
}
You need to update variable COL_MOVIE_POSTER in DetailActivity according to item clicked in gridview of MainActivityFragment.
I know that the purpose of the AsyncTask is to run asynchronously with other tasks of the app and finish in the background, but apparently I need to do this, I need to start an activity from AsyncTask and since I cant extend an activity in this class I can not use startactivityforresult, so how can I wait till my activity finishes?
Here is my code:
public class ListSpdFiles extends AsyncTask<Void, Void, String[]> {
public AsyncResponse delegate = null;
private static final String TAG = "ListSpdFiles: ";
Context applicationContext;
ContentResolver spdappliationcontext;
public final CountDownLatch setSignal= new CountDownLatch(1);
private final ReentrantLock lock = new ReentrantLock();
String username = "";
/**
* Status code returned by the SPD on operation success.
*/
private static final int SUCCESS = 4;
private boolean createbutt;
private boolean deletebutt;
private String initiator;
private String path;
private String pass;
private String url;
private SecureApp pcas;
private boolean isConnected = false; // connected to PCAS service?
private String CurrentURL = null;
private PcasConnection pcasConnection = new PcasConnection() {
#Override
public void onPcasServiceConnected() {
Log.d(TAG, "pcasServiceConnected");
latch.countDown();
}
#Override
public void onPcasServiceDisconnected() {
Log.d(TAG, "pcasServiceDisconnected");
}
};
private CountDownLatch latch = new CountDownLatch(1);
public ListSpdFiles(boolean createbutt, boolean deletebutt, String url, String pass, Context context, String initiator, String path, AsyncResponse asyncResponse) {
this.initiator = initiator;
this.path = path;
this.pass= pass;
this.url= url;
this.createbutt= createbutt;
this.deletebutt=deletebutt;
applicationContext = context.getApplicationContext();
spdappliationcontext = context.getContentResolver();
delegate = asyncResponse;
}
private void init() {
Log.d(TAG, "starting task");
pcas = new AndroidNode(applicationContext, pcasConnection);
isConnected = pcas.connect();
}
private void term() {
Log.d(TAG, "terminating task");
if (pcas != null) {
pcas.disconnect();
pcas = null;
isConnected = false;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
init();
}
#Override
protected String[] doInBackground(Void... params) {
CurrentURL = getLastAccessedBrowserPage();
// check if connected to PCAS Service
if (!isConnected) {
Log.v(TAG, "not connected, terminating task");
return null;
}
// wait until connection with SPD is up
try {
if (!latch.await(20, TimeUnit.SECONDS)) {
Log.v(TAG, "unable to connected within allotted time, terminating task");
return null;
}
} catch (InterruptedException e) {
Log.v(TAG, "interrupted while waiting for connection in lsdir task");
return null;
}
// perform operation (this is where the actual operation is called)
try {
return lsdir();
} catch (DeadServiceException e) {
Log.i(TAG, "service boom", e);
return null;
} catch (DeadDeviceException e) {
Log.i(TAG, "device boom", e);
return null;
}
}
#Override
protected void onPostExecute(String[] listOfFiles) {
super.onPostExecute(listOfFiles);
if (listOfFiles == null) {
Log.i(TAG, "task concluded with null list of files");
} else {
Log.i(TAG, "task concluded with the following list of files: "
+ Arrays.toString(listOfFiles));
}
term();
delegate.processFinish(username);
}
#Override
protected void onCancelled(String[] listOfFiles) {
super.onCancelled(listOfFiles);
Log.i(TAG, "lsdir was canceled");
term();
}
/**
* Returns an array of strings containing the files available at the given path, or
* {#code null} on failure.
*/
private String[] lsdir() throws DeadDeviceException, DeadServiceException {
Result<List<String>> result = pcas.lsdir(initiator, path); // the lsdir call to the
boolean crtbut = createbutt;
boolean dlbut= deletebutt;
ArrayList<String> mylist = new ArrayList<String>();
final Global globalVariable = (Global) applicationContext;
if (crtbut==false && dlbut == false){
if ( globalVariable.getPasswordButt()==false ) {
final boolean isusername = globalVariable.getIsUsername();
if (isusername == true) {
Log.i(TAG, "current url: " + CurrentURL);
if (Arrays.toString(result.getValue().toArray(new String[0])).contains(CurrentURL)) {
String sharareh = Arrays.toString(result.getValue().toArray(new String[0]));
String[] items = sharareh.split(", ");
for (String item : items) {
String trimmed;
if (item.startsWith("[" + CurrentURL + ".")) {
trimmed = item.replace("[" + CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
} else if (item.startsWith(CurrentURL + ".")) {
trimmed = item.replace(CurrentURL + ".", "");
if (trimmed.endsWith(".txt]")) {
trimmed = trimmed.replace(".txt]", "");
mylist.add(trimmed.replace(".txt]", ""));
} else if (trimmed.endsWith(".txt")) {
trimmed = trimmed.replace(".txt", "");
mylist.add(trimmed.replace(".txt", ""));
}
Log.i(TAG, "list of files sharareh: " + trimmed);
}
}
}
globalVariable.setPopupdone(false);
Intent i = new Intent(applicationContext, PopUp.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("EXTRA_SESSION_ID", mylist);
applicationContext.startActivity(i);
username = globalVariable.getUsername();
}
else if (isusername == false)
Log.i(TAG, "Wrong Input Type For Username.");
}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
//}
if (result.getState() != SUCCESS) {
Log.v(TAG, "operation failed");
return null;
}
if (result.getValue() == null) {
Log.v(TAG, "operation succeeded but operation returned null list");
return null;
}
return result.getValue().toArray(new String[0]);
}
public String getLastAccessedBrowserPage() {
String Domain = null;
Cursor webLinksCursor = spdappliationcontext.query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, Browser.BookmarkColumns.DATE + " DESC");
int row_count = webLinksCursor.getCount();
int title_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.TITLE);
int url_column_index = webLinksCursor.getColumnIndexOrThrow(Browser.BookmarkColumns.URL);
if ((title_column_index > -1) && (url_column_index > -1) && (row_count > 0)) {
webLinksCursor.moveToFirst();
while (webLinksCursor.isAfterLast() == false) {
if (webLinksCursor.getInt(Browser.HISTORY_PROJECTION_BOOKMARK_INDEX) != 1) {
if (!webLinksCursor.isNull(url_column_index)) {
Log.i("History", "Last page browsed " + webLinksCursor.getString(url_column_index));
try {
Domain = getDomainName(webLinksCursor.getString(url_column_index));
Log.i("Domain", "Last page browsed " + Domain);
return Domain;
} catch (URISyntaxException e) {
e.printStackTrace();
}
break;
}
}
webLinksCursor.moveToNext();
}
}
webLinksCursor.close();
return null;
}
public String getDomainName(String url) throws URISyntaxException {
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
}}
My Activity class:
public class PopUp extends Activity {
private static final String TAG = "PopUp";
ArrayList<String> value = null;
ArrayList<String> usernames;
#Override
protected void onCreate(Bundle savedInstanceState) {
final Global globalVariable = (Global) getApplicationContext();
globalVariable.setUsername("");
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getStringArrayList("EXTRA_SESSION_ID");
}
usernames = value;
super.onCreate(savedInstanceState);
setContentView(R.layout.popupactivity);
final Button btnOpenPopup = (Button) findViewById(R.id.openpopup);
btnOpenPopup.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button btnSelect = (Button) popupView.findViewById(R.id.select);
Spinner popupSpinner = (Spinner) popupView.findViewById(R.id.popupspinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(PopUp.this, android.R.layout.simple_spinner_item, usernames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
popupSpinner.setAdapter(adapter);
popupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
globalVariable.setUsername(usernames.get(arg2));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
btnSelect.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
globalVariable.setPopupdone(true);
popupWindow.dismiss();
finish();
}
}
);
popupWindow.showAsDropDown(btnOpenPopup, 50, -30);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.poupup_menu, menu);
return true;
}}
In this code I have a custom adapter, and after I add new data into ArrayList my adapter.notifyDataSetChanged(); doesn't work.
public class ReceiveListFragment extends ListFragment implements AbsListView.OnScrollListener {
public ArrayList<ReceivedItemStructure> items;
private int prevVisibleItem;
private boolean isFirstTime;
private DatabaseHandler db;
private String config_username;
private String config_password;
private ReceivedAdapter adapter;
private Cursor cursor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
db = new DatabaseHandler(G.context);
config_username = Configuration.getInstance()
.getString(getActivity(),
Configuration.SharedPrefsTypes.USERNAME);
config_password = Configuration.getInstance()
.getString(getActivity(),
Configuration.SharedPrefsTypes.PASSWORD);
items = new ArrayList<ReceivedItemStructure>();
getRequestFromServer(0, 10);
adapter = new ReceivedAdapter(G.context, items);
setListAdapter(adapter);
Timer smsThread = new Timer();
GetSMSThread getSMSThread = new GetSMSThread();
smsThread.scheduleAtFixedRate(getSMSThread, 1, 10000); //(timertask,delay,period)
return super.onCreateView(inflater, container, savedInstanceState);
}
private String getRequestFromServer(long lastID, int count) {
String received = "";
try {
received = new JsonService(config_username, config_password, lastID, count, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(received);
String mUserID = config_username;
for (int i = 0; i < data_array.length(); i++) {
JSONObject json_obj = data_array.getJSONObject(i);
String mLastID = json_obj.getString("id_recived_sms");
String mSmsBody = json_obj.getString("sms_body");
String mSmsNumber = json_obj.getString("sms_number");
String mSenderName = json_obj.getString("mobile_number");
String mContactName = json_obj.getString("contact_name");
String mDate = json_obj.getString("recived_date");
ReceivedItemStructure item = new ReceivedItemStructure(
mLastID,
mUserID,
mSmsBody,
mSmsNumber,
mSenderName,
mContactName,
mDate
);
items.add(item);
//Log.e(" ", "" + mLastID);
}
/** Creating array adapter to set data in listview */
} catch (Exception e) {
e.printStackTrace();
}
return received;
}
public long getLastID() {
return Long.parseLong(items.get(items.size() - 1).getmLastID());
}
private void addDataToList(String LastID, String SmsBody, String SmsNumber, String SenderName, String ContactName, String Date) {
String mLastID = LastID;
String mUserID = config_username;
String mSmsBody = SmsBody;
String mSmsNumber = SmsNumber;
String mSenderName = SenderName;
String mContactName = ContactName;
String mDate = Date;
ReceivedItemStructure item = new ReceivedItemStructure(
mLastID,
mUserID,
mSmsBody,
mSmsNumber,
mSenderName,
mContactName,
mDate
);
items.add(item);
adapter.update(items);
adapter.notifyDataSetChanged();
}
public class GetSMSThread extends TimerTask {
private Long lastID;
private SQLiteDatabase dbHelper;
private List<ReceiveListFragment> rows;
#Override
public void run() {
lastID = getLastID();
if (Configuration.getInstance().checkInternetConnection(G.context)) {
try {
Thread threadTask = new Thread() {
#Override
public void run() {
G.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
int countSMS = 0;
String smsReceivedSender = "";
String receive_lastID = "";
String r = new JsonService(config_username, config_password, 0, 1, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(r);
ArrayList<String> items_array = new ArrayList<String>();
JSONObject json_obj = data_array.getJSONObject(0);
receive_lastID = json_obj.getString("id_recived_sms");
smsReceivedSender = json_obj.getString("mobile_number");
for (ReceivedItemStructure rf : items) {
items_array.add(rf.getmLastID());
}
if (items_array.indexOf(receive_lastID) == -1) {
countSMS++;
addDataToList(
json_obj.getString("id_recived_sms"),
json_obj.getString("sms_body"),
json_obj.getString("sms_number"),
json_obj.getString("mobile_number"),
json_obj.getString("contact_name"),
json_obj.getString("recived_date")
);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
threadTask.start();
} catch (Exception e) {
e.printStackTrace();
} // END TRY
}
}
}
}
My custom Adapter code is this:
public class ReceivedAdapter extends ArrayAdapter<ReceivedItemStructure> {
private ArrayList<ReceivedItemStructure> list;
public ReceivedAdapter(Context c, ArrayList<ReceivedItemStructure> items) {
super(c,0,items);
list = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ReceiveItemView itemView = (ReceiveItemView)convertView;
if (null == itemView)
itemView = ReceiveItemView.inflate(parent);
itemView.setItem(getItem(position));
return itemView;
}
public void update(ArrayList<ReceivedItemStructure> items) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
addAll(items);
} else {
for (ReceivedItemStructure item : items) {
add(item);
}
}
}
}
setListAdapter(adapter); works correctly and I don't have any problem, but after I add new data into items notifyDataSetChanged it doesn't work.
My manifest content:
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21"/>
it is the super class that is handling the dataset, since you are not overriding getCount and getItem,
public void update(ArrayList<ReceivedItemStructure> items) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
addAll(items);
} else {
for (ReceivedItemStructure item : items) {
add(item)
}
}
}
addAll was introduced with Honeycomb, so you probably want to check the current supported sdk where you are app is running
You are modifying your original items collection. But you should to modify adapter's data. Use ArrayAdapter.add method to add new items.