I have a JSON file which is populated to an activity (Main.java).
This Activity shows 3 random images from the URL on my JSON entries.
What I wanna do is: I have 13 different entries on the my JSON, whenever I click the shown random picture it goes to another activity (ProjectDetail.java) containing the picture,title,and description depends on the item I click based on its entry on the JSON.
What do I have in is by using extra by I dont know exactly how to perform that since I'm using JSON. What should I add into my top_listener method on my Main class and what should I add into my ProjectDetail class?
Thank you.
Main.java
public class Main extends Activity {
/** Called when the activity is first created. */
ArrayList<Project> prjcts=null;
private ImageThreadLoader imageLoader = new ImageThreadLoader();
private final static String TAG = "MediaItemAdapter";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
prjcts = new ArrayList<Project>();
WebService webService = new WebService("http://liebenwald.spendino.net/admanager/dev/android/projects.json");
Map<String, String> params = new HashMap<String, String>();
params.put("var", "");
String response = webService.webGet("", params);
try
{
Type collectionType = new TypeToken<ArrayList<Project>>(){}.getType();
List<Project> lst= new Gson().fromJson(response, collectionType);
for(Project l : lst)
{
prjcts.add(l);
ConstantData.projectsList.add(l);
}
}
catch(Exception e)
{
Log.d("Error: ", e.getMessage());
}
final Button project = (Button) findViewById(R.id.btn_projectslist);
final Button infos = (Button) findViewById(R.id.btn_infos);
final Button contact = (Button) findViewById(R.id.btn_contact);
project.setOnClickListener(project_listener);
infos.setOnClickListener(infos_listener);
contact.setOnClickListener(contact_listener);
ImageView image1;
ImageView image2;
ImageView image3;
try {
image1 = (ImageView)findViewById(R.id.top1);
image2 = (ImageView)findViewById(R.id.top2);
image3 = (ImageView)findViewById(R.id.top3);
} catch( ClassCastException e ) {
Log.e(TAG, "Your layout must provide an image and a text view with ID's icon and text.", e);
throw e;
}
Bitmap cachedImage1 = null;
Bitmap cachedImage2 = null;
Bitmap cachedImage3 = null;
//randomize the index of image entry
int max = prjcts.size();
List<Integer> indices = new ArrayList<Integer>(max);
for(int c = 0; c < max; ++c)
{
indices.add(c);
}
int arrIndex = (int)((double)indices.size() * Math.random());
int randomIndex1 = indices.get(arrIndex);
indices.remove(arrIndex);
int randomIndex2 = indices.get(arrIndex);
indices.remove(arrIndex);
int randomIndex3 = indices.get(arrIndex);
indices.remove(arrIndex);
setImage(cachedImage1, image1, prjcts.get(randomIndex1));
setImage(cachedImage2, image2, prjcts.get(randomIndex2));
setImage(cachedImage3, image3, prjcts.get(randomIndex3));
image1.setOnClickListener(top_listener);
image2.setOnClickListener(top_listener);
image3.setOnClickListener(top_listener);
}
public void setImage(Bitmap cachedImage, final ImageView image, Project pro)
{
//Bitmap cachedImage1 = null;
try {
cachedImage = imageLoader.loadImage(pro.smallImageUrl, new ImageLoadedListener()
{
public void imageLoaded(Bitmap imageBitmap)
{
image.setImageBitmap(imageBitmap);
//notifyDataSetChanged();
}
});
} catch (MalformedURLException e) {
Log.e(TAG, "Bad remote image URL: " + pro.smallImageUrl, e);
}
if( cachedImage != null ) {
image.setImageBitmap(cachedImage);
}
}
private OnClickListener top_listener = new OnClickListener() {
public void onClick(View v) {
Intent top = new Intent(Main.this, InfosActivity.class);
startActivity(top);
}
};
ProjectDetail.java
public class ProjectDetail extends Activity implements OnClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
Button weitersagen = (Button) findViewById(R.id.btn_weitersagen);
weitersagen.setOnClickListener(this);
Button sms = (Button) findViewById(R.id.btn_sms_spenden);
sms.setOnClickListener(this);
int position = getIntent().getExtras().getInt("spendino.de.ProjectDetail.position");
Project project = ConstantData.projectsList.get(position);
try {
ImageView projectImage = (ImageView)findViewById(R.id.project_image);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(project.bigImageUrl).getContent());
projectImage.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
TextView project_title = (TextView)findViewById(R.id.txt_project_title);
project_title.setText(project.project_title);
TextView organization_title = (TextView)findViewById(R.id.txt_organization_title);
organization_title.setText(Html.fromHtml("von " +project.organization_title));
TextView project_description = (TextView)findViewById(R.id.txt_project_description);
project_description.setText(Html.fromHtml(project.project_description));
}
I also have this ConstantData.java, the index which holds my JSON properties:
public class ConstantData{
public static String project_title = "project title";
public static String organization_title = "organization title";
public static String keyword = "keyword";
public static String short_code = "short code";
public static String project_description = "description";
public static String smallImageUrl = "smallImageUrl";
public static String bigImageUrl = "bigImageUrl";
public static String price= "price";
public static String country= "country";
public static ArrayList<Project> projectsList = new ArrayList<Project>();
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(project_title);
out.writeString(organization_title);
out.writeString(keyword);
out.writeString(short_code);
out.writeString(project_description);
out.writeString(smallImageUrl);
out.writeString(bigImageUrl);
out.writeString(price);
out.writeString(country);
}
public static final Parcelable.Creator<ConstantData> CREATOR
= new Parcelable.Creator<ConstantData>() {
public ConstantData createFromParcel(Parcel in) {
return new ConstantData(in);
}
public ConstantData[] newArray(int size) {
return new ConstantData[size];
}
};
private ConstantData(Parcel in) {
project_title = in.readString();
organization_title = in.readString();
keyword = in.readString();
short_code = in.readString();
project_description = in.readString();
smallImageUrl = in.readString();
bigImageUrl = in.readString();
price = in.readString();
country = in.readString();
}
}
You could make the class ConstantData serializable by extending from Parcelable and implementing a couple of methods (see the documentation). Then you could pass a constantData instance as an extra by doing
intent.putExtra("jsonData", constantDataInstance);
and retrieving it from the other activity (in it's onCreate() method) with
getIntent().getExtras().getParcelable("jsonData");
Otherwise you could just past as extra every field independently, but it would be a mess. This way is not only more easy to read and everything, but "well designed".
To pass information from one activity to another when you start the new one you do the following:
Intent top = new Intent(Main.this, InfosActivity.class);
Bundle b = new Bundle();
b.putString("key1", "value2");
b.putString("key2", "value2");
b.putString("key3", "value3");
top.putExtras(b);
startActivity(top);
Then in the newly started activity, in the onCreate() put the following:
Bundle b = getIntent().getExtras();
b.get("key1");
b.get("key2");
b.get("key3");
This will get the values from the previous activity by using the key you provided.
For more complex objects you should extend Parcelable (probably what you'll need) and then use:
b.putParcelable("Key4", yourParcelableObject);
And in your onCreate()
b.getParcelable("Key4");
I hope this helps.
Use gson to parse the json to Java. Then you can use Wagon to move the extras around with ease.
GSON:
https://github.com/google/gson
Wagon:
https://github.com/beplaya/Wagon
Related
I am a new application developer I try intent or pass data through on click image in (slider Layout) from first activity to the second activity. I try to intent (name) to second activity.
I now have a different set of images now, each one having its own name.if user clicking on the first image will intent or pass data of first image only.Also if user clicking on the five image will intent data of five image only.Like that what I want to do.
Please if anyone knows the answer help me.
import com.smarteist.autoimageslider.SliderLayout;
import com.smarteist.autoimageslider.SliderView;
public class SlidShowMain extends AppCompatActivity {
SliderLayout sliderLayout;
private List<SlidShowListData> list_dataList;
private JsonArrayRequest request;
private RequestQueue requestQueue;
private static final String HI ="http://=========/S.php";
TextView textView5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slide_show_new);
sliderLayout = (SliderLayout) findViewById(R.id.imageSlider);
sliderLayout.setIndicatorAnimation(SliderLayout.Animations.WORM);
list_dataList=new ArrayList<>();
sliderLayout.setScrollTimeInSec(1);
textView5 =(TextView)findViewById(R.id.textView5);
SliderView sliderView = new SliderView(this);
setSliderViews();
}
private void setSliderViews() {
request = new JsonArrayRequest(HI, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0; i < response.length(); i++) {
try {
jsonObject = response.getJSONObject(i);
SlidShowListData listData = new SlidShowListData listData = new SlidShowListData(jsonObject.getString("imageurl"),jsonObject.getString("name"),jsonObject.getString("id"));
String name = jsonObject.getString("id");
textView5.append(name + ", " +"\n\n");
list_dataList.add(listData);
} catch (JSONException e) {
e.printStackTrace();
}
}
setupdata(list_dataList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
private void setupdata(List<SlidShowListData> list_dataList) {
for (int i = 0; i <= 4; i++) {
final SlidShowListData ld = list_dataList.get(i);
SliderView view = new SliderView(getBaseContext());
view.setImageUrl(ld.getImageurl());
view.setImageUrl(ld.getname());
view.setImageScaleType(ImageView.ScaleType.CENTER_CROP);
final int finalI = i;
sliderLayout.addSliderView(view);
view.setOnSliderClickListener(new SliderView.OnSliderClickListener() {
#Override
public void onSliderClick(SliderView sliderView) {
Toast.makeText(SlidShowMain.this, "" + (sliderLayout.getCurrentPagePosition() + 1), Toast.LENGTH_SHORT).show();
}
});
}
}
}
public class SlidShowListData {
private String imageurl;
private String name;
private String id;
public SlidShowListData(String imageurl,String name,String id) {
this.imageurl = imageurl;
this.name = name;
this.id = id;
}
public String getImageurl() {
return imageurl;
}
public String getname() {
return name;
}
public String getId() {
return id;
}
}
implementation 'com.github.smarteist:autoimageslider:1.1.1'
implementation 'com.github.bumptech.glide:glide:4.7.1'
<?php
$con=mysqli_connect("localhost","=====","=====","show");
$sql="SELECT * FROM slhow";
$result=mysqli_query($con,$sql);
$data=array();
while($row=mysqli_fetch_assoc($result)){
$data[]=$row;
}
header('Content-Type:Application/json');
echo json_encode($data);
?>
I have tried to write it as follows:
holder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,HomeActivity.class);
intent.putExtra("id",======.=======()); // here problem
context.startActivity(intent);
I don't know what I should write or how on the second line into (====) to send an ID.must send the Id of image that user just clicks, not all ids of images
Anyone know solution , please help me
Use this code for sending data from FirstActivity:
val intent = Intent(this#FirstActivity, SecondActivity::class.java)
intent.putExtra("imagename", imageid)
startActivity(intent)
And this for delivering date in SecondActivity:
var imageid = intent.getStringExtra("imagename")
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/
Im building an app where I have an Array list with strings and a button.
When I press the button it deletes the string from the list (with string.remove) and display it in another activity..
The problem is that when I close the app and reopen it everything goes back to normal. How to save the changes made?
Here is the code:
public class TasksActivity extends AppCompatActivity {
private static ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_tasks);
final Button tasksbtn = (Button) findViewById(R.id.btnfortasks);
Button checkTask = (Button) findViewById(R.id.remove_case);
final TextView tasksView = (TextView) findViewById(R.id.tasks_textView);
final ArrayList<String> tasks = new ArrayList<String>();
tasks.add("one");
tasks.add("two");
tasks.add("three");
tasks.add("four");
tasks.add("five");
tasks.add("six");
Collections.shuffle(tasks);
tasksView.setText(tasks.get(0));
assert tasksbtn != null;
tasksbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Collections.shuffle(tasks);
tasksView.setText(tasks.get(0));
}
});
checkTask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TasksActivity.this, CompletedTasks.class);
intent.putExtra("completedTasks", tasks.get(0));
tasks.remove(tasks.get(0));
startActivity(intent);
}
});
}
}
And the second Activity
public class CompletedTasks extends AppCompatActivity {
String completedTasks;
Global_Variable object = new Global_Variable();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_completed_tasks);
TextView completedTasksView = (TextView) findViewById(R.id.completed_tasks);
Intent intent = getIntent();
completedTasks = intent.getExtras().getString("completedTasks");
object.tasks.add(completedTasks + "\n");
String a = "";
for (int i = 0; i < object.tasks.size(); i++) {
a += object.tasks.get (i);
completedTasksView.setText(a);
Log.d("a", "a---------" + a);
}
}
}
You should probably give try to serialization. Please take look over below sample example.
public class SerializationDemo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Person person = new Person();
person.setName("CoderzHeaven");
person.setAddress("CoderzHeaven India");
person.setNumber("1234567890");
//save the object
saveObject(person);
// Get the Object
Person person1 = (Person)loadSerializedObject(new File("/sdcard/save_object.bin")); //get the serialized object from the sdcard and caste it into the Person class.
System.out.println("Name : " + person1.getName());
}
public void saveObject(Person p){
try
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("/sdcard/save_object.bin"))); //Select where you wish to save the file...
oos.writeObject(p); // write the class as an 'object'
oos.flush(); // flush the stream to insure all of the information was written to 'save_object.bin'
oos.close();// close the stream
}
catch(Exception ex)
{
Log.v("Serialization Save Error : ",ex.getMessage());
ex.printStackTrace();
}
}
public Object loadSerializedObject(File f)
{
try
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
Object o = ois.readObject();
return o;
}
catch(Exception ex)
{
Log.v("Serialization Read Error : ",ex.getMessage());
ex.printStackTrace();
}
return null;
}
Person implements Serializable //Added implements Serializable
{
String name="";
private String number="";
private String address="";
private static final long serialVersionUID = 46543445;
public void setName(String name)
{
this.name = name;
}
public void setNumber(String number)
{
this.number = number;
}
public void setAddress(String address)
{
this.address = address;
}
public String getName()
{
return name;
}
public String getNumber()
{
return number;
}
public String getAddress()
{
return address;
}
}
}
You could try saving your changes to the SharedPreferences. Then when you resatrt your app, read the changes from your ShraredPreferences and apply it to your ListView or whatever you are using.
You can read more about SharedPreferences here: https://developer.android.com/training/basics/data-storage/shared-preferences.html
In this method I am receiving the ArrayList
OkHttpHandler handler = new OkHttpHandler(MainActivity.this,new OkHttpHandler.MyInterface() {
#Override
public void myMethod(ArrayList result) {
Toast.makeText(MainActivity.this, "Connection Succesful",
Toast.LENGTH_LONG).show();
GridViewAdapter adapter = new GridViewAdapter(getApplicationContext(), R.layout.grid_item_layout, result);
what I want is to send this arraylist to another activity in the gridiview. When the user clicks on the image in gridview, I want to send this image in ArrayList to next activity. How to do that>
this is the grid view
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("OnImageButton", "Clicked");
Intent intnt =new Intent(mcontext, SingleViewActivity.class);
//intnt.putExtra("Contact_list", item);
mcontext.startActivity(intnt) ; //This line raises error
Toast.makeText(mcontext, "intent",
Toast.LENGTH_LONG).show();
}
});
I tried parcable, but it didn't work because I only want to send the data to another activity, I don't to start a new activity
this is what I tried
Listitem = new ArrayList<Listitem>();
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
// String id ="2";
String id= c.getString("ID");
String url = c.getString("URL");
Log.d("Id: ", id);
int intid = 0;
Student student = new Student(c.getString("ID"),
"hhe",
c.getString("URL")
);
Intent intent = new Intent(mContext,SingleViewActivity.class);
// Passing data as a parecelable object to StudentViewActivity
intent.putExtra("student",student);
// Opening the activity
mContext.startActivity(intent);
In this method, I am passing ArrayList to another activity
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray("result");
System.out.println(peoples.length());
Listitem = new ArrayList<Listitem>();
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String id= c.getString("ID");
String url = c.getString("URL");
Log.d("Id: ", id);
int intid = 0;
try {
intid = Integer.parseInt(id.toString());
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
DatabaseHandler db = new DatabaseHandler(mContext);
Log.d("Insert: ", "Inserting ..");
db.addObjects(new Objects(intid,"Image1", url, "IMAGES", "Funny"));
Listitem.add(new Listitem(id,url));
Log.e("d", "ppppp");
System.out.println(Listitem);
}
if (mListener != null)
mListener.myMethod(Listitem);
Please refer to my following sample code for sending an arraylist to another activity, then you can use its logic to your app. Hope this helps!
First of all, you need a class that implements Parcelable
public class Person implements Parcelable {
int id;
String name;
int age;
Person (Parcel in){
this.id = in.readInt();
this.name = in.readString();
this.age = in.readInt();
}
Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.id);
dest.writeString(this.name);
dest.writeInt(this.age);
}
public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
public Person createFromParcel(Parcel in) {
return new Person(in);
}
public Person[] newArray(int size) {
return new Person[size];
}
};
}
Then in MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Person> personArrayList = new ArrayList<>();
personArrayList.add(new Person(1, "Person A", 20));
personArrayList.add(new Person(2, "Person B", 30));
personArrayList.add(new Person(3, "Person C", 40));
Intent intent = new Intent(this,PersonsActivity.class);
intent.putExtra("Person_List", personArrayList);
startActivity(intent);
}
}
The PersonsActivity:
public class PersonsActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_persons);
Bundle bundle = getIntent().getExtras();
ArrayList<Person> personArrayList = bundle.getParcelableArrayList("Person_List");
if (personArrayList != null && !personArrayList.isEmpty()) {
for (Person person : personArrayList) {
Log.i("PersonsActivity", String.valueOf(person.id) + " | " + person.name + " | " + String.valueOf(person.age));
}
}
}
}
You will get the following logcat:
11-23 15:40:37.107 4051-4051/? I/PersonsActivity: 1 | Person A | 20
11-23 15:40:37.107 4051-4051/? I/PersonsActivity: 2 | Person B | 30
11-23 15:40:37.107 4051-4051/? I/PersonsActivity: 3 | Person C | 40
You can do this using following way
You can set position of a grid item(here image) you click as a tag to imageview and then you can get the json object or single object from array list using above position and can send to another activity.
holder.imageView.SetTag(position)
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Get your imageview here by using v.findviewbyid and get tag tag
//Like this
//ImageView iv=(ImageView)v.findviewbyid(id of layout you mention to bind holder.imageView)
//Integer mPosition=(Integer)iv.getTag();
//Then fetch that single object by using mPosition from your list and pass it
//JSONObject item = peoples.getJSONObject(mPosition);
Log.d("OnImageButton", "Clicked");
Intent intnt =new Intent(mcontext, SingleViewActivity.class);
//intnt.putExtra("Contact_list", item);
mcontext.startActivity(intnt) ; //This line raises error
Toast.makeText(mcontext, "intent",
Toast.LENGTH_LONG).show();
}
});
//Make constant class and add all data in this arraylist:
//e.g : Constant.arrylist.add(<collection>);
public class Constant{
public static ArrayList<collection>() arrylist = new ArrayList<collection>()
}
//Pass arraylist data
Intent intent = new Intent(this,YourActivity.class);
intent.putInt("position", arrylist.get(position));
startActivity(intent);
//Get position in another activity
Bundle bundle = getIntent().getExtras();
int position = bundle.getInt("position",0);
//Now get Particular data
//e.g
String url = Constant.arrylist.get(position).<url(collection)>;
//And so on..!