public class MovieDescription extends Activity {
Vibrator vibrator;
TextView tv_title,tv_year,tv_banner,tv_desc;
RatingBar ratingBar;
ImageView iv_watch,iv_poster;
private static final String TAG_CONTACTS = "Demo";
private static final String TAG_ID = "id";
private static final String TAG_TITLE = "title";
private static final String TAG_YEAR = "year";
private static final String TAG_RATING = "rating";
private static final String TAG_BANNER= "category";
private static final String TAG_DESC = "description";
private static final String TAG_URL = "url";
private static final String TAG_POSTER = "poster";
String id,title,year,rating,banner,description,poster, movieUrl;
static JSONArray contacts = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_description);
initialize();
String movieDescUrl = "http://vaibhavtech.com/work/android/movie_description.php?id="+MainActivity.movie_Id;
MovieDescriptionParser jParser = new MovieDescriptionParser();
JSONObject json = jParser.getJSONFromUrl(movieDescUrl);
try {
contacts = json.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < contacts.length(); i++)
{
/**********************************Value Parse FromUrl**********************************/
JSONObject c = contacts.getJSONObject(i);
id = c.getString(TAG_ID);
title = c.getString(TAG_TITLE);
year = c.getString(TAG_YEAR);
rating = c.getString(TAG_RATING);
banner=c.getString(TAG_BANNER);
description = c.getString(TAG_DESC);
movieUrl = c.getString(TAG_URL);
poster = c.getString(TAG_POSTER);
/**********************************Valeu Assing to UI Component**********************************/
Log.i(id, title);
}
} catch (JSONException e) {
e.printStackTrace();
}
tv_title.setText(title);
tv_year.setText(year);
tv_banner.setText(banner);
tv_desc.setText(description);
Float rat=Float.parseFloat(rating);
ratingBar.setRating(rat);
Bitmap bimage= getBitmapFromURL("http://vaibhavtech.com/work/android/admin/upload/"+poster);
iv_poster.setImageBitmap(bimage);
iv_watch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
vibrator.vibrate(40);
LayoutInflater inflater=getLayoutInflater();
View view=inflater.inflate(R.layout.customtoast,(ViewGroup)findViewById(R.id.custom_toast_layout));
Toast toast=new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast.setView(view);
toast.show();
Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(movieUrl));
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Log.i("Device Versoin is", ""+currentapiVersion);
if (currentapiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN){
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
getMenuInflater().inflate(R.menu.main, menu);
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
case R.id.home:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Log.i("Home", "Press");
return true;
}
return super.onOptionsItemSelected(item);
}
public void initialize()
{
tv_banner=(TextView) findViewById(R.id.tv_movie_description_banner);
tv_desc=(TextView) findViewById(R.id.tv_movie_description_decription);
tv_title=(TextView) findViewById(R.id.tv_movie_description_name);
tv_year=(TextView) findViewById(R.id.tv_movie_description_year);
ratingBar=(RatingBar) findViewById(R.id.ratingBar1);
iv_watch=(ImageView) findViewById(R.id.iv_movie_description_watch);
iv_poster=(ImageView) findViewById(R.id.iv_movie_description_poster);
vibrator=(Vibrator)getSystemService(Context.VIBRATOR_SERVICE);;
}
public static Bitmap getBitmapFromURL(String src) {
try {
Log.i("src",src);
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
Log.i("Bitmap","returned");
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("Exception",e.getMessage());
return null;
}
}
}
When I am clicking on "watch now" button it's giving me four options - by mozilz, by Chrome, by YouTube. I want that when I click on watch now button it get redirect on YouTube url link. How can I do this?
Try this :
Intent i = app.getPackageManager().getLaunchIntentForPackage("com.google.android.youtube");
if (i != null)
app.startActivity(i);
Check this link also : Redirect YouTube in Android
Hope this helps.
Related
I have three activities, I capture all data but one from DetailActivity upon button click and save in database using Room; My intention is to insert all these data into the database and start ReviewActivity so as to get the arraylist of reviews and also insert it in the database. Everything seems to work fine until when I want to view review offline because I believe it has been saved, reviews does not get loaded.
This is my DetailActivity,
TextView overview_tv; ImageView image_tv; TextView name_tv; TextView ratings; Context context; TextView release_date; ImageView backdrop_poster; private ExpandableHeightListView trailers; public static ArrayList<Youtube> youtube; public static ArrayList<Review> reviews; TrailerViewAdapter adapter; public static DataObject data; DataObject dataObject; ArrayList<Review> savedReview; private static final String IMAGE_URL = "http://image.tmdb.org/t/p/w185/"; private static final String THE_MOVIEDB_URL2 = "https://api.themoviedb.org/3/movie/"; private static final String MOVIE_QUERY2 = "api_key"; private static final String API_KEY2 = "6cc4f47bd4a64e0117e157b79072ae37"; private static String SEARCH_QUERY2 = "videos"; public static int movieId; Button viewReviews; Button favourite; String movieRating; private static final int YOUTUBE_SEARCH_LOADER = 23; private static final int REVIEW_SEARCH_LOADER = 24; File file; String name; String overview; String releaseDate; int switcher; public static ArrayList<Review> favouriteReviews; TextView trev; AppDatabase mDb; //Navigation arrow on the action bar #Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { NavUtils.navigateUpFromSameTask(this); } return super.onOptionsItemSelected(item); } #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); mDb = AppDatabase.getInstance(getApplicationContext()); youtube = new ArrayList<Youtube>(); reviews = new ArrayList<Review>(); adapter = new TrailerViewAdapter(this, youtube); //Credit to Paolorotolo #github trailers = findViewById(R.id.expandable_list); trailers.setAdapter(adapter); trailers.setExpanded(true); //Navigation arrow on the acton bar; check also override onOptionsItemSelected ActionBar actionBar = this.getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } context = getApplicationContext(); Intent intent = getIntent(); if (intent == null) { closeOnError(); } switcher = getIntent().getIntExtra("switch", 3); overview_tv = findViewById(R.id.overview); image_tv = findViewById(R.id.image); name_tv = findViewById(R.id.name); ratings = findViewById(R.id.ratings); release_date = findViewById(R.id.release_date); backdrop_poster = findViewById(R.id.backdrop_poster); trev = findViewById(R.id.review_show); viewReviews = findViewById(R.id.review_button); favourite = findViewById(R.id.favourite_button); addListenerOnRatingBar(ratings); if (switcher != 2) { favourite.setVisibility(View.INVISIBLE); dataObject = (DataObject) getIntent().getParcelableExtra("array"); final String favouriteName = dataObject.getName(); final String favouriteOverview = dataObject.getOverview(); final String favouriteReleaseDate = dataObject.getReleaseDate(); ArrayList<Youtube> savedTrailer = dataObject.getTrailers(); savedReview = dataObject.getMovieReviews(); movieRating = dataObject.getRating(); name_tv.setText(favouriteName); overview_tv.setText(favouriteOverview); ratings.setText("Rating: " + movieRating); release_date.setText("Release Date: " + favouriteReleaseDate);// Toast.makeText(this, "Testing Reviews " + savedReview.get(0).getAuthor(), Toast.LENGTH_SHORT).show(); String imagePath = name_tv.getText().toString() + "0i"; String backdropPath = name_tv.getText().toString() + "1b"; try { DataObjectAdapter.downloadImage(imagePath, image_tv, this); } catch (Exception e) { e.printStackTrace(); } try { DataObjectAdapter.downloadImage(backdropPath, backdrop_poster, context); } catch (Exception e) { e.printStackTrace(); } if (savedTrailer != null) { TrailerViewAdapter lv = new TrailerViewAdapter(DetailActivity.this, savedTrailer); trailers.setAdapter(lv); switcher = 3; } } else { name = getIntent().getStringExtra("Name"); overview = getIntent().getStringExtra("Overview"); final String image = getIntent().getStringExtra("Image"); movieId = getIntent().getIntExtra("movieId", 1); final String backdrop = getIntent().getStringExtra("backdrop"); releaseDate = getIntent().getStringExtra("releaseDate"); movieRating = getIntent().getStringExtra("rating"); Log.i("this", "switch " + switcher); name_tv.setText(name); overview_tv.setText(overview); ratings.setText("Rating: " + movieRating); release_date.setText("Release Date: " + releaseDate); //load backdrop poster Picasso.with(context) .load(IMAGE_URL + backdrop) .fit() .placeholder(R.drawable.placeholder_image) .error(R.drawable.placeholder_image) .into(backdrop_poster); Picasso.with(context) .load(IMAGE_URL + image) .fit() .placeholder(R.drawable.placeholder_image) .error(R.drawable.placeholder_image) .into(image_tv); getSupportLoaderManager().initLoader(YOUTUBE_SEARCH_LOADER, null, this); //getSupportLoaderManager().initLoader(REVIEW_SEARCH_LOADER, null, this); //loadTrailers(); //loadReviews(); //populateKeys(); } /** * Here manages the views(list) for reviews */ viewReviews.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { if (switcher == 3) { startActivity(new Intent(DetailActivity.this, ReviewActivity.class) .putExtra("switch", 3)); } else { Log.i("this", "I am from initial" + switcher); startActivity(new Intent(DetailActivity.this, ReviewActivity.class).putExtra("id", movieId)); } } } ); favourite.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { data = new DataObject(); data.setName(name); data.setOverview(overview); data.setRating(movieRating); data.setReleaseDate(releaseDate); data.setTrailers(youtube);// data.setMovieReviews(reviews); try { saveImage(name_tv.getText().toString() + "0i", image_tv); saveImage(name_tv.getText().toString() + "1b", backdrop_poster); } catch (IOException e) { e.printStackTrace(); } Toast.makeText(context, "The movie is saved as a favourite", Toast.LENGTH_LONG).show(); AppExecutors.getInstance().diskIO().execute(new Runnable() { #Override public void run() { mDb.dataDao().insertData(data); } }); startActivity(new Intent(DetailActivity.this, ReviewActivity.class).putExtra("id", movieId) .putExtra(ReviewActivity.EXTRA_DATA_ID, 20)); } } ); }
And my ReviewActivity
public class ReviewActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<ArrayList<Review>>{ public static ArrayList<Review> reviews; public static List<DataObject> favouriteReviews; public static RecyclerView reviewList; ArrayList<Review> r; private static final int REVIEW_SEARCH_LOADER = 24; private static final String MOVIE_QUERY3 = "api_key"; private static final String API_KEY3 = "6cc4f47bd4a64e0117e157b79072ae37"; private static String SEARCH_QUERY3 = "reviews"; private static final String THE_MOVIEDB_URL3 = "https://api.themoviedb.org/3/movie/"; private static int movId; public static final String EXTRA_DATA_ID = "extraDataId"; private static final int DEFAULT_TASK_ID = -1; private int mTaskId = DEFAULT_TASK_ID; DataObject data1; AppDatabase mDb; ReviewAdapter revAdapter; int loaderSwitch; #Override protected void onResume() { super.onResume(); } #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_review); mDb = AppDatabase.getInstance(getApplicationContext()); reviews = new ArrayList<Review>(); favouriteReviews = new ArrayList<DataObject>(); reviewList = findViewById(R.id.review_list); LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext()); reviewList.setLayoutManager(layoutManager); reviewList.setHasFixedSize(true); int switcher = getIntent().getIntExtra("switch", 1); Intent intent = getIntent(); if (intent == null) { finish(); } Log.i("this", "swithcer " + switcher); Log.i("this loader", "Loader " + loaderSwitch); if (switcher == 3){ DataObject dataObject = (DataObject) getIntent().getParcelableExtra("ArrayOfReviews"); if (dataObject != null){ ArrayList<Review> movieReviews = dataObject.getMovieReviews(); Toast.makeText(this, "There are reviews saved", Toast.LENGTH_LONG).show(); revAdapter = new ReviewAdapter(this, movieReviews ); reviewList.setAdapter(revAdapter); } } else { movId = getIntent().getIntExtra("id", 20); revAdapter = new ReviewAdapter(this, reviews); reviewList.setAdapter(revAdapter); loadReviews(); //populateReview(); } DividerItemDecoration decoration = new DividerItemDecoration(this, VERTICAL); reviewList.addItemDecoration(decoration); } #Override protected void onStart() { super.onStart(); //loadReviews(); } public static URL buildUrl3(String stringUrl) { Uri uri = Uri.parse(THE_MOVIEDB_URL3).buildUpon() .appendPath(stringUrl) .appendPath(SEARCH_QUERY3) .appendQueryParameter(MOVIE_QUERY3, API_KEY3) .build(); URL url = null; try { url = new URL(uri.toString()); } catch (MalformedURLException exception) { Log.e(TAG, "Error creating URL", exception); } return url; } public void loadReviews(){ // COMPLETED (19) Create a bundle called queryBundle Bundle queryBundle = new Bundle(); // COMPLETED (20) Use putString with SEARCH_QUERY_URL_EXTRA as the key and the String value of the URL as the value// queryBundle.putString(SEARCH_QUERY_URL_EXTRA, url.toString()); // COMPLETED (21) Call getSupportLoaderManager and store it in a LoaderManager variable LoaderManager loaderManager = getSupportLoaderManager(); // COMPLETED (22) Get our Loader by calling getLoader and passing the ID we specified Loader<ArrayList<Review>> movieReviews = loaderManager.getLoader(REVIEW_SEARCH_LOADER); // COMPLETED (23) If the Loader was null, initialize it. Else, restart it. if (movieReviews == null) { loaderManager.initLoader(REVIEW_SEARCH_LOADER, queryBundle, this); } else { loaderManager.restartLoader(REVIEW_SEARCH_LOADER, queryBundle, this); } } #Override public Loader<ArrayList<Review>> onCreateLoader(int id, Bundle args) { return new AsyncTaskLoader<ArrayList<Review>>(this) { #Override protected void onStartLoading() { super.onStartLoading(); forceLoad(); } #Override public ArrayList<Review> loadInBackground() { String g = String.valueOf(movId); // Create URL object URL url = buildUrl3(g); // Perform HTTP request on the URL and receive a JSON response back String jsonResponse = ""; try { jsonResponse = getResponseFromHttpUrl(url); } catch (Exception e) { e.printStackTrace(); } reviews = MovieJsonUtils.parseReview(jsonResponse); return reviews; } }; } #Override public void onLoadFinished(Loader<ArrayList<Review>> loader, ArrayList<Review> dat) { if (reviews != null) { Intent intent = getIntent(); if (intent != null && intent.hasExtra(EXTRA_DATA_ID)) { //mButton.setText(R.string.update_button); if (mTaskId == DEFAULT_TASK_ID) { mTaskId = intent.getIntExtra(EXTRA_DATA_ID, DEFAULT_TASK_ID); AppExecutors.getInstance().diskIO().execute(new Runnable() { #Override public void run() { data.setMovieReviews(reviews); mDb.dataDao().updateData(data); //mDb.dataDao().insertData(data); final List<DataObject> task = mDb.dataDao().loadById(mTaskId); runOnUiThread(new Runnable() { #Override public void run() { populateUI(task); } }); } }); } } else { ReviewAdapter lv = new ReviewAdapter(ReviewActivity.this, reviews); reviewList.setAdapter(lv); } } } #Override public void onLoaderReset(Loader<ArrayList<Review>> loader) { }
Data gets loaded from MainActivity, the saved data is passed on to other activities as a parcellable bundle via intent, the passed data is displayed in DetailActivity but not in ReviewActivity.
Alternatively, if I can load reviews alongside YouTube keys from DetailActivity, I believe I can handle the database issue from there, but two Loaders wouldn't just work together, the app crashes; I am aware two AsyncTasks concurrently run together solved this problem, but I prefer to use Loaders because of performance on configuration change
I created app that takes JSON with AsyncTask from server. When User click a button app starts new Activity and download data from server and show it as a items in ListView. The Problem is when I open new Activity it takes too long to load. When button is pressed app freeze on about one or two seconds and then show black screen for another 2/3 seconds. After that activity is displayed but it is very slow. It freeze every time user is scrolling or pressing button to display more options of custom adapter. Is there any way to make app more smooth? Json data that is downloaded is just simple JSONArray with JSONObjects that has 2 string values and one HTML format. This 3 values is display to user.
Part of Custom Adapter class
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
SuggestionList suggestionList = getItem(position);
int actualPosition = 0;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.sugestion_list, parent, false);
}
final Button suggestionsButton = (Button) convertView.findViewById(R.id.suggestionsMore);
final TextView suggestionNumber = (TextView) convertView.findViewById(R.id.sugestionNumber);
final TextView suggestionDescription = (TextView) convertView.findViewById(R.id.suggestionDescription);
final ImageView bio = convertView.findViewById(R.id.sugestionBio);
final ImageView block = convertView.findViewById(R.id.sugestionBlock);
final ImageView call = convertView.findViewById(R.id.sugestionCall);
...
final Animation slideUp = AnimationUtils.loadAnimation(getContext(), R.anim.slideup);
final Animation slideDown = AnimationUtils.loadAnimation(getContext(), R.anim.slidedown);
final Handler handler = new Handler();
suggestionsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (bioSuggestions.getVisibility() == View.GONE) {
bio.setVisibility(View.VISIBLE);
block.setVisibility(View.VISIBLE);
call.setVisibility(View.VISIBLE);
bioSuggestions.startAnimation(slideUp);
blockSuggestions.startAnimation(slideUp);
callSuggestions.startAnimation(slideUp);
} else if (bioSuggestions.getVisibility() == View.VISIBLE) {
bioSuggestions.startAnimation(slideDown);
blockSuggestions.startAnimation(slideDown);
callSuggestions.startAnimation(slideDown);
handler.postDelayed(new Runnable() {
#Override
public void run() {
bio.setVisibility(View.GONE);
block.setVisibility(View.GONE);
call.setVisibility(View.GONE);
}
}, 300);
}
}
});
if (actualPosition != position) {
if (bio.getVisibility() == View.VISIBLE) {
bio.setVisibility(View.GONE);
block.setVisibility(View.GONE);
call.setVisibility(View.GONE);
}
actualPosition = position;
}
JSONObject jsonValSuggestions = new getSugestions().sugestionsDetails(position, "suggestions");
try {
final String name = jsonValSuggestions.getString("client_name");
final String num = jsonValSuggestions.getString("client_number");
final String description = jsonValSuggestions.getString("client_description");
bio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent suggestionsDetails = new Intent(view.getContext(), SuggestionsDetails.class);
suggestionsDetails.putExtra("client_number", num);
suggestionsDetails.putExtra("client_name", name);
suggestionsDetails.putExtra("client_description", description);
activity.startActivityForResult(suggestionsDetails, position);
}
});
block.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent suggestionBlock = new Intent(view.getContext(), BlockSuggestionsActivity.class);
activity.startActivity(suggestionBlock);
}
});
call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent suggestionCall = new Intent(view.getContext(), CallSuggestionActivity.class);
suggestionCall.putExtra("client_number", num);
suggestionCall.putExtra("client_name", name);
activity.startActivity(suggestionCall);
}
});
} catch (Exception e) {
e.printStackTrace();
}
try {
if (suggestionList.suggestionName.equals("null") || suggestionList.suggestionName.equals("")) {
suggestionNumber.setText(suggestionList.suggestionNumber);
} else {
suggestionNumber.setText(suggestionList.suggestionName);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
suggestionDescription.setText(Html.fromHtml(suggestionList.suggestionDescription, Html.FROM_HTML_MODE_LEGACY));
} else {
suggestionDescription.setText(Html.fromHtml(suggestionList.suggestionDescription));
}
} catch (Exception e) {
Log.i("exception", e.getMessage());
}
return convertView;
}
Part of AsyncTask class
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
#Override
protected String doInBackground(String... params) {
String clientUrl = params[0];
String result;
String inputLine;
JSONObject obj;
String data;
String message;
try {
URL myUrl = new URL(clientUrl);
HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.connect();
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
result = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
result = null;
}
return result;
}
public String[] getSuggestionsList() {
String[] suggestionList = new String[5];
String result;
String status;
JSONObject listObj;
String suggestionsData;
JSONObject suggestionsDataObj;
JSONArray suggestionsDataArr;
String ClientsSugestionsUrl = "https://example.com/token=" + authToken;
getApiClientSugestions getSugestionsFromApi = new getApiClientSugestions();
try {
result = getSugestionsFromApi.execute(ClientsSugestionsUrl).get();
try {
listObj = new JSONObject(result);
status = listObj.getString("result");
suggestionsData = listObj.getString("suggestions");
suggestionsDataArr = new JSONArray(suggestionsData);
} catch (Exception e) {
e.printStackTrace();
suggestionsDataArr = null;
status = null;
}
suggestionList[3] = status;
suggestionList[4] = suggestionsDataArr.toString();
} catch (Exception e) {
e.printStackTrace();
}
return suggestionList;
}
Activity
public class CallsSuggestionsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calls_suggestions);
Slidr.attach(this);
getSupportActionBar().setTitle("Skontaktuj siÄ™");
}
#Override
protected void onResume() {
super.onResume();
CallsSuggestionList();
}
public void CallsSuggestionList() {
final ListView suggestionList = findViewById(R.id.sugestionList);
final ArrayList<SuggestionList> suggestionArray = new ArrayList<SuggestionList>();
SuggestionListAdapter suggestionListAdapter = new SuggestionListAdapter(getContext(), suggestionArray, this);
String[] suggestionListArray = new getSugestions().getSuggestionsList();
String suggStat = suggestionListArray[3];
String arrayList = suggestionListArray[4];
String clientName;
String clientNumber;
String clientDescription;
try {
JSONArray jsonArray = new JSONArray(arrayList);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject explrObject = jsonArray.getJSONObject(i);
clientName = explrObject.getString("client_name");
clientNumber = explrObject.getString("client_number");
clientDescription = explrObject.getString("client_description");
if (suggStat.equals("true")) {
SuggestionList suggestionList1 = new SuggestionList(clientName, clientDescription, clientNumber);
suggestionListAdapter.addAll(suggestionList1);
suggestionListAdapter.notifyDataSetChanged();
suggestionList.setAdapter(suggestionListAdapter);
}
}
} catch (Exception e) {
Log.i("exception", e.getMessage());
e.printStackTrace();
clientName = null;
clientDescription = null;
clientNumber = null;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
SuggestionList
public class SuggestionList {
public String suggestionNumber;
public String suggestionDescription;
public String suggestionCallType;
public String suggestionName;
public SuggestionList(
// String suggestionCallType,
String suggestionName, String suggestionDescription, String suggestionNumber) {
this.suggestionNumber = suggestionNumber;
// this.suggestionCallType = suggestionCallType;
this.suggestionName = suggestionName;
this.suggestionDescription = suggestionDescription;
}
}
Adapter are custom with custom view displayed to user. I use similar custom adapter to show content from sqlite that is on phone and there app isn't so slow. But when I open this activity it slow down dramatically. Also I noticed when I press back button it take very long to back to previous screen.
The problem is in the getSuggestionsList function. in this function, you are calling getSugestionsFromApi.execute(ClientsSugestionsUrl).get(); which make your code sync again. I mean your code is waiting this code to be executed.
One way (not right way, but easy way): you can call new getSugestions().getSuggestionsList(); in a new thread.
Second way, call getSugestionsFromApi.execute(ClientsSugestionsUrl) without get() function. But to get result of the code, you need to give an interface.
To get right usage: https://xelsoft.wordpress.com/2014/11/28/asynctask-implementation-using-callback-interface/
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.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have created a login and trying to save the UserName and UserID for
session but I am getting an error at this line
mAppPreference.setUserID(userid);
The error is :-
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.android.mivas.AppContoller.AppPreference.setUserID(java.lang.String)' on a null object reference
here is my Login class
public class LoginPagefrag extends Fragment implements OnClickListener, MiFeelingBase
{
private Intent i;
private int urlIndex=0;
private Button btnLogin;
private EditText edUserName,edPassword;
private String strUserName,strPassword;
private String strEmailID;
private MultipartEntity reqEntity;
private Dialog dialog;
private ProgressDialog pDialog;
Context cxt;
private SessionManager session;
SharedPreferences myPriference;
AppPreference mAppPreference;
public static final String TAG_USERID = "userid";
public static String TAG_USERNAME = "username";
private static final Pattern EMAIL_PATTERN = Pattern.compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.loginpage, container, false);
APIAccess.fetchData(LoginPagefrag.this, getActivity(), getActivity());
btnLogin=(Button)rootView.findViewById(R.id.btnLogin);
edUserName=(EditText)rootView.findViewById(R.id.edUserName);
edPassword=(EditText)rootView.findViewById(R.id.edPassword);
btnLogin.setOnClickListener(this);
return rootView;
}
#SuppressWarnings("unused")
private void initialiseNoramlVariable() {
cxt = getActivity();
mAppPreference = AppPreference.getInstance(cxt);
}
public void postLogin()
{
try
{
StringBody username=new StringBody(strUserName);
StringBody password=new StringBody(strPassword);
reqEntity = new MultipartEntity();
reqEntity.addPart("username", username);
reqEntity.addPart("password", password);
}
catch(Exception e)
{
System.out.println("err" + e);
}
}
public void postForgotPass()
{
try
{
StringBody emailid=new StringBody(strEmailID);
reqEntity = new MultipartEntity();
reqEntity.addPart("email", emailid);
}
catch(Exception e)
{
System.out.println("err" + e);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.btnLogin :
if(edUserName.getText().toString().equalsIgnoreCase(""))
{
// Toast.makeText(LoginPagefrag.this, "enter username", Toast.LENGTH_SHORT).show();
}else if(edPassword.getText().toString().equalsIgnoreCase(""))
{
//Toast.makeText(LoginPagefrag.this, "enter pass", Toast.LENGTH_SHORT).show();
}else
{
strUserName=edUserName.getText().toString();
strPassword=edPassword.getText().toString();
urlIndex=0;
APIAccess.fetchData(LoginPagefrag.this, getActivity(), getActivity());
}
break;
}
}
#Override
public String httpPost() {
// TODO Auto-generated method stub
String response="";
if(urlIndex==0)
{
postLogin();
response=APIAccess.openConnection(StaticData.SABAKUCH_LOGIN, reqEntity);
}
return response;
}
#Override
public String httpAfterPost(String str) {
// TODO Auto-generated method stub
if(str!=null)
{
if(urlIndex==0)
{
if(SabaKuchParsechat.jsonStatus(str)==0)
{
// Toast.makeText(LoginPagefrag.this, SabaKuchParsechat.jsonErrorMessage(str), Toast.LENGTH_SHORT).show();
}
else if(SabaKuchParsechat.jsonStatus(str)==1)
{
LoginData obj=SabaKuchParsechat.parseLoginData(str);
Log.d("objj", "hello"+obj);
String userid = obj.strUserId;
String username= obj.strUserName;
mAppPreference.setUserID(userid);
mAppPreference.setUserName(username);
mAppPreference.setServerKey();
session.setLogin(true);
Intent iintt = new Intent(getActivity(),MainActivity.class);
startActivity(iintt);
}
}
}
return null;
}
private boolean CheckEmail(String email) {
return EMAIL_PATTERN.matcher(email).matches();
}
public ConnectivityManager getSystemService(String connectivityService) {
// TODO Auto-generated method stub
return null;
}
}
Here is my AppPreference class :-
public class AppPreference extends Application {
Context cxt;
private static final String SHARED_APP_PREFERENCE_NAME = "sabakuchapp_pref_key";
public static AppPreference mAppprefernce;
private SharedPreferences pref;
private Editor mEditor;
public AppPreference() {
super();
// TODO Auto-generated constructor stub
}
enum SharedPreferenceKey{
USER_ID, USER_NAME, SERVER_KEY;
}
private AppPreference (Context context){
pref = context.getSharedPreferences(SHARED_APP_PREFERENCE_NAME, Context.MODE_PRIVATE);
mEditor = pref.edit();
}
public AppPreference(Context cxt, SharedPreferences pref, Editor mEditor) {
super();
this.cxt = cxt;
this.pref = pref;
this.mEditor = mEditor;
}
public static AppPreference getInstance(Context context){
if(mAppprefernce == null){
mAppprefernce = new AppPreference(context);
}
return mAppprefernce;
}
public void setUserID(String id){
mEditor.putString(SharedPreferenceKey.USER_ID.toString(), id);
mEditor.commit();
}
public String getUserID(){
return pref.getString(SharedPreferenceKey.USER_ID.toString(), "");
}
public void setUserName(String name){
mEditor.putString(SharedPreferenceKey.USER_NAME.toString(), name);
mEditor.commit();
}
public String getUserName(){
return pref.getString(SharedPreferenceKey.USER_NAME.toString(), "");
}
public void setServerKey(){
String original = getUserID()+"_" + getUserName() + "_SBK";
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
mEditor.putString(SharedPreferenceKey.SERVER_KEY.toString(), sb.toString());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
mEditor.putString(SharedPreferenceKey.SERVER_KEY.toString(), "");
}
mEditor.commit();
return;
}
public String getServerKey(){
return pref.getString(SharedPreferenceKey.SERVER_KEY.toString(), "");
}
}
Please let me know what I am missing here. Thanks in advance.
#SuppressWarnings("unused")
private void initialiseNoramlVariable() {
cxt = getActivity();
mAppPreference = AppPreference.getInstance(cxt);
}
You added "unused" warning by yourself. And you never call this method in fact. So mAppPreference is null. If this method is useless, move mAppPreference = AppPreference.getInstance(cxt); to somewhere else such as onCreateView to make sure it could be inited.
You need to initialize your variable mAppPreference.
I mean you have done that in method initialiseNoramlVariable() but never called the method. You should call the method in onCreateView()
You are not calling initialiseNoramlVariable method and therefor mAppPreference does not get initialized.
This should get you going:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.loginpage, container, false);
APIAccess.fetchData(LoginPagefrag.this, getActivity(), getActivity());
btnLogin=(Button)rootView.findViewById(R.id.btnLogin);
edUserName=(EditText)rootView.findViewById(R.id.edUserName);
edPassword=(EditText)rootView.findViewById(R.id.edPassword);
btnLogin.setOnClickListener(this);
cxt = getActivity();
mAppPreference = AppPreference.getInstance(cxt);
return rootView;
}
I have a listview, when i click on any item in listview a detailed activity will open.This layout has many widgets like textview, ImageView, share buttons etc. Now I want to slide this detail activity of the item to show the detail view of next item in the list. I am following this http://misha.beshkin.lv/android-swipe-gesture-implementation/ but when i swipe from left to right next view is not displaying just getting a toast message "swipe right". Can any one direct me how to work on this? i am new to android Answers will be appreciated. Following is the code i have used
MainActivity.java(listview page)
public class MainActivity extends ListActivity {
ArrayList<HashMap<String, String>> songsList;
ListView list;
LazyAdapter adapter;
JSONArray posts;
// All static variables
static final String URL = "http://siteurl/posts/pages";
static final String KEY_URL_FOR_MAP = "url_site";
static final String KEY_POSTS = "posts";
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_SITEURL = "url";
static final String KEY_DATE = "date";
static final String KEY_CONTENT = "content";
static final String KEY_AUTHOR = "author";
static final String KEY_NAME = "name";
static final String KEY_ATTACHMENTS = "attachments";
static final String KEY_SLUG = "slug";
static final String KEY_THUMB_URL = "thumbnail";
static final String KEY_IMAGES = "images";
static final String KEY_URL = "url";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
final JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
posts = json.getJSONArray(KEY_POSTS);
// looping through all song nodes <song>
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String siteurl = c.getString(KEY_SITEURL);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// to remove all <P> </p> and <br /> and replace with ""
content = content.replace("<br />", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
//authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
String url = null;
String slug = null;
try {
JSONArray atta = c.getJSONArray("attachments");
for(int j = 0; j < atta.length(); j++){
JSONObject d = atta.getJSONObject(j);
slug = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
url = thumbnail.getString(KEY_URL);
}
} catch (Exception e) {
e.printStackTrace();
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_URL_FOR_MAP, siteurl);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug);
map.put(KEY_URL, url);
// adding HashList to ArrayList
songsList.add(map);
}
}catch (JSONException e) {
e.printStackTrace();
}
final ListView list=(ListView)findViewById(android.R.id.list);
// Getting adapter by passing json data ArrayList
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);
// Launching new screen on Selecting Single ListItem
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = songsList.get(position);
Intent in = new Intent(MainActivity.this, SampleDesp.class);
in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
in.putExtra(KEY_URL_FOR_MAP, map.get(KEY_URL_FOR_MAP));
in.putExtra(KEY_DATE, map.get(KEY_DATE));
in.putExtra(KEY_NAME, map.get(KEY_NAME));
in.putExtra(KEY_CONTENT, map.get(KEY_CONTENT));
in.putExtra(KEY_URL, map.get(KEY_URL));
startActivity(in);
}
});
}
}
SampleDesp.java(detailed Activity)
public class SampleDesp extends Activity implements SimpleGestureListener {
private SimpleGestureFilter detector;
static String title;
String content;
// Your Facebook APP ID
private static String APP_ID = "308180782571605"; // Replace with your App ID
// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
Button btnFbLogin;
Button btnPostToWall;
// JSON node keys
static final String KEY_URL_FOR_MAP = "url_site";
private static final String KEY_TITLE = "title";
private static final String KEY_SITEURL = "url";
private static final String KEY_DATE = "date";
private static final String KEY_NAME = "name";
private static final String KEY_CONTENT = "content";
private static final String KEY_URL = "url";
static final String KEY_SLUG1= "slug";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sampledes);
detector = new SimpleGestureFilter(this,this);
final LinearLayout line1 = (LinearLayout)findViewById(R.id.ll1);
LinearLayout line2 = (LinearLayout)findViewById(R.id.ll2);
Button btnShare = (Button)findViewById(R.id.share);
btnShare.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
line1.setVisibility(View.VISIBLE);
}
});
// getting intent data
Intent in = getIntent();
final String url1 = in.getStringExtra(KEY_URL);
ImageView imgv = (ImageView) findViewById(R.id.imgdesc);
ImageLoader imageLoader = new ImageLoader(getApplicationContext());
imageLoader.DisplayImage(url1, imgv);
// Get JSON values from previous intent
final String title = in.getStringExtra(KEY_TITLE);
final String siteurl = in.getStringExtra(KEY_URL_FOR_MAP);
String date = in.getStringExtra(KEY_DATE);
String name = in.getStringExtra(KEY_NAME);
final String content = in.getStringExtra(KEY_CONTENT);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblUrl = (TextView) findViewById(R.id.url_label);
TextView lblCost = (TextView) findViewById(R.id.email_label);
TextView lblDesc = (TextView) findViewById(R.id.mobile_label);
TextView lblCont = (TextView) findViewById(R.id.content_label);
lblName.setText(title);
lblUrl.setText(siteurl);
lblCost.setText(date);
lblDesc.setText(name);
lblCont.setText(content);
final ImageView email3 = (ImageView) findViewById(R.id.email);
email3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
//my codes
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri data = Uri.parse("mailto:?subject=" + title + "&body=" + content);
intent.setData(data);
startActivity(intent);
}
});
final ImageView sms4 = (ImageView) findViewById(R.id.sms);
sms4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
// Perform action on click
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setData(Uri.parse(Uri.encode(title)+Uri.encode(content)));
shareIntent.setType("text/*");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, content);
startActivity(shareIntent);
}
});
final ImageView twitter4 = (ImageView) findViewById(R.id.twitter);
twitter4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
// Perform action on click
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://twitter.com/?status=" + Uri.encode(title) + "" + Uri.encode(siteurl)));
startActivity(i);
}
});
Button btnFbLogin = (Button) findViewById(R.id.btn_fblogin);
btnFbLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Image Button", "button Clicked");
loginToFacebook();
if (facebook.isSessionValid()) {
postToWall();
}
}
});
}
#Override
public boolean dispatchTouchEvent(MotionEvent me){
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
public void onSwipe(int direction) {
String str = "";
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT : str = "Swipe Right";
break;
case SimpleGestureFilter.SWIPE_LEFT : str = "Swipe Left";
break;
case SimpleGestureFilter.SWIPE_DOWN : str = "Swipe Down";
break;
case SimpleGestureFilter.SWIPE_UP : str = "Swipe Up";
break;
}
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
public void onDoubleTap() {
Toast.makeText(this, "Double Tap", Toast.LENGTH_SHORT).show();
}
/**
* Function to login into facebook
* */
private void loginToFacebook() {
// TODO Auto-generated method stub
{
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}else{}
}
}
/**
* Function to post to facebook wall
* */
public void postToWall() {
Bundle parameters = new Bundle();
parameters.putString("title", "visit us");
parameters.putString("link", "http://india.dollardesi.net/ads/metro-logistic-packers-movers/");
// post on user's wall.
facebook.dialog(this, "feed",parameters, new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
/**
* Function to Logout user from Facebook
* */
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// make Login button visible
btnFbLogin.setVisibility(View.VISIBLE);
}
});
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
}
SimpleGestureFilter.java
public class SimpleGestureFilter extends SimpleOnGestureListener{
public final static int SWIPE_UP = 1;
public final static int SWIPE_DOWN = 2;
public final static int SWIPE_LEFT = 3;
public final static int SWIPE_RIGHT = 4;
public final static int MODE_TRANSPARENT = 0;
public final static int MODE_SOLID = 1;
public final static int MODE_DYNAMIC = 2;
private final static int ACTION_FAKE = -13; //just an unlikely number
private int swipe_Min_Distance = 100;
private int swipe_Max_Distance = 350;
private int swipe_Min_Velocity = 100;
private int mode = MODE_DYNAMIC;
private boolean running = true;
private boolean tapIndicator = false;
private Activity context;
private GestureDetector detector;
private SimpleGestureListener listener;
public SimpleGestureFilter(Activity context,SimpleGestureListener sgl) {
this.context = context;
this.detector = new GestureDetector(context, this);
this.listener = sgl;
}
public void onTouchEvent(MotionEvent event){
if(!this.running)
return;
boolean result = this.detector.onTouchEvent(event);
if(this.mode == MODE_SOLID)
event.setAction(MotionEvent.ACTION_CANCEL);
else if (this.mode == MODE_DYNAMIC) {
if(event.getAction() == ACTION_FAKE)
event.setAction(MotionEvent.ACTION_UP);
else if (result)
event.setAction(MotionEvent.ACTION_CANCEL);
else if(this.tapIndicator){
event.setAction(MotionEvent.ACTION_DOWN);
this.tapIndicator = false;
}
}
//else just do nothing, it's Transparent
}
public void setMode(int m){
this.mode = m;
}
public int getMode(){
return this.mode;
}
public void setEnabled(boolean status){
this.running = status;
}
public void setSwipeMaxDistance(int distance){
this.swipe_Max_Distance = distance;
}
public void setSwipeMinDistance(int distance){
this.swipe_Min_Distance = distance;
}
public void setSwipeMinVelocity(int distance){
this.swipe_Min_Velocity = distance;
}
public int getSwipeMaxDistance(){
return this.swipe_Max_Distance;
}
public int getSwipeMinDistance(){
return this.swipe_Min_Distance;
}
public int getSwipeMinVelocity(){
return this.swipe_Min_Velocity;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
final float xDistance = Math.abs(e1.getX() - e2.getX());
final float yDistance = Math.abs(e1.getY() - e2.getY());
if(xDistance > this.swipe_Max_Distance || yDistance > this.swipe_Max_Distance)
return false;
velocityX = Math.abs(velocityX);
velocityY = Math.abs(velocityY);
boolean result = false;
if(velocityX > this.swipe_Min_Velocity && xDistance > this.swipe_Min_Distance){
if(e1.getX() > e2.getX()) // right to left
this.listener.onSwipe(SWIPE_LEFT);
else
this.listener.onSwipe(SWIPE_RIGHT);
result = true;
}
else if(velocityY > this.swipe_Min_Velocity && yDistance > this.swipe_Min_Distance){
if(e1.getY() > e2.getY()) // bottom to up
this.listener.onSwipe(SWIPE_UP);
else
this.listener.onSwipe(SWIPE_DOWN);
result = true;
}
return result;
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
this.tapIndicator = true;
return false;
}
#Override
public boolean onDoubleTap(MotionEvent arg0) {
this.listener.onDoubleTap();;
return true;
}
#Override
public boolean onDoubleTapEvent(MotionEvent arg0) {
return true;
}
#Override
public boolean onSingleTapConfirmed(MotionEvent arg0) {
if(this.mode == MODE_DYNAMIC){ // we owe an ACTION_UP, so we fake an
arg0.setAction(ACTION_FAKE); //action which will be converted to an ACTION_UP later.
this.context.dispatchTouchEvent(arg0);
}
return false;
}
static interface SimpleGestureListener{
void onSwipe(int direction);
void onDoubleTap();
}
}
I think that it may work:
//code from your onItemClick
HashMap<String, String> map = songsList.get(position);
Intent in = new Intent(MainActivity.this, SampleDesp.class);
in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
in.putExtra(KEY_URL_FOR_MAP, map.get(KEY_URL_FOR_MAP));
in.putExtra(KEY_DATE, map.get(KEY_DATE));
in.putExtra(KEY_NAME, map.get(KEY_NAME));
in.putExtra(KEY_CONTENT, map.get(KEY_CONTENT));
in.putExtra(KEY_URL, map.get(KEY_URL));
in.putExtra(LIST_POSITION, position); //passing incremented position
startActivity(in);
And then in your details Activity you will have position of current item of the list that details are displayed on the screen. So now you can increment position, and use the same code (the above one) in your onSwipe(int direction) method. So if you want to open next item details on your left swipe you do something like this:
public void onSwipe(int direction) {
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT :
break;
case SimpleGestureFilter.SWIPE_LEFT :
Intent in = getIntent();
in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
in.putExtra(KEY_URL_FOR_MAP, map.get(KEY_URL_FOR_MAP));
in.putExtra(KEY_DATE, map.get(KEY_DATE));
in.putExtra(KEY_NAME, map.get(KEY_NAME));
in.putExtra(KEY_CONTENT, map.get(KEY_CONTENT));
in.putExtra(KEY_URL, map.get(KEY_URL));
in.putExtra(LIST_POSITION, position); //passing clicked position
finish();
startActivity(intent);
break;
case SimpleGestureFilter.SWIPE_DOWN :
break;
case SimpleGestureFilter.SWIPE_UP :
break;
}
}
But for this code in SWIPE_LEFT when your adding Extras to your intent, you need access to a HashMap from your MainActivity, so you can add a public static method in your MainActivity like:
public static String getSongFromHashMap(String key) {
return songsList.get(key);
}
And use this method in SWIPE_LEFT code. I know it's not best solution but it should work :)
change
case SimpleGestureFilter.SWIPE_LEFT : str = "Swipe Left";
break;
to
case SimpleGestureFilter.SWIPE_LEFT : str = "Swipe Left";
//Fire intent to your detail activity here
break;
I hope I am closer to your solution.