Transfer image data from activity to fragment - android

I have a image in NetworkImageView of a Activity. How to transfer it in another NetworkImageView or ImageView of a Fragment.
first listview
package com.packageNmae;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.enventpc_03.nav11.adater.CustomListAdapter;
import com.enventpc_03.nav11.app.AppController;
import com.enventpc_03.nav11.model.Movie;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class SearchPeople extends BaseActivity {
// Log tag
private static final String TAG = SearchPeople.class.getSimpleName();
// Movies json url
// Movies json url
private static String url = "myurl";
private static String url1 = "my url";
private static String Title = "title";
private static String Location = "loc";
private static String Description = "des";
private static String bitmap = "thumbnailUrl";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
public static final String BITMAP_ID = "id";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// // changing action bar color
// getActionBar().setBackgroundDrawable(
// new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("fullname"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(obj.getString("location"));
movie.setGenre(obj.getString("Description"));
movie.setYear(obj.getInt("id"));
// // Genre is json array
// JSONArray genreArry = obj.getJSONArray("genre");
// ArrayList<String> genre = new ArrayList<String>();
// for (int j = 0; j < genreArry.length(); j++) {
// genre.add((String) genreArry.get(j));
// }
// movie.setGenre(genre);
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
// listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// #Override
// public void onItemClick(AdapterView<?> parent, View view, int position,
// long id) {
// Intent intent = new Intent(MainActivity.this, Details.class);
//
//
// startActivity(intent);
// }
// });
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// your code
// TODO Auto-generated method stub
String name = ((TextView) view.findViewById(R.id.title)).getText().toString();
String location = ((TextView) view.findViewById(R.id.rating)).getText().toString();
String description = ((TextView) view.findViewById(R.id.genre)).getText().toString();
bitmap = ((Movie) movieList.get(position)).getThumbnailUrl();
Intent intent = new Intent(SearchPeople.this, Details.class);
intent.putExtra(Title, name);
intent.putExtra(Location, location);
intent.putExtra(Description, description);
intent.putExtra("images", bitmap);
startActivity(intent);
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public void onBackPressed() {
Intent myIntent = new Intent(SearchPeople.this, UploadActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// clear back stack
startActivity(myIntent);
finish();
return;
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.main, menu);
// return true;
// }
//
// #Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//
// Intent intent = new Intent(this, Details.class);
// intent.putExtra(BITMAP_ID,position);
// startActivity(intent);
//
// }
}
Full Image View class
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.enventpc_03.nav11.app.AppController;
import com.enventpc_03.nav11.model.Movie;
import java.util.ArrayList;
import java.util.List;
public class Details extends BaseActivity {
private static String Title = "title";
private static String Location = "loc";
private static String Description = "des";
ImageButton fb,google,twitter;
boolean isImageFitToScreen;
private static String bitmap = "thumbnailUrl";
private List<Movie> movieList = new ArrayList<Movie>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
// getActionBar().hide();
//Passing url
MyFragment f = new MyFragment();
Bundle b = new Bundle();
bitmap = ((Movie) movieList.get(position)).getThumbnailUrl();
b.putString("images", bitmap);
f.setArguments(b);
Intent i = getIntent();
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
String name = i.getStringExtra(Title);
String location1 = i.getStringExtra(Location);
String description1 = i.getStringExtra(Description);
String bitmap = i.getStringExtra("images");
final NetworkImageView thumbNail = (NetworkImageView) findViewById(R.id.thumbnail);
thumbNail.setImageUrl(bitmap, imageLoader);
TextView lblname = (TextView) findViewById(R.id.name_label);
TextView location = (TextView) findViewById(R.id.each_location);
TextView description = (TextView) findViewById(R.id.each_comment);
lblname.setText(name);
location.setText(location1);
description.setText(description1);
fb=(ImageButton)findViewById(R.id.fb);
fb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent browserIntent =
new Intent(Intent.ACTION_VIEW, Uri.parse("Facebook"));
startActivity(browserIntent);
}
});
thumbNail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyFragment yourFragment= new MyFragment();
fragmentTransaction.add(R.id.myfragment, yourFragment, "FRAGMENT");
fragmentTransaction.commit();
}
});
}
public void onClickHandler(View v) {
switch (v.getId()) {
case R.id.thumbnail:
startActivity(new Intent(this, UploadActivity.class));
}
}
public void onBackPressed() {
Intent myIntent = new Intent(Details.this, SearchPeople.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// clear back stack
startActivity(myIntent);
finish();
return;
}
Fragment
public class MyFragment extends Fragment {
private static String bitmap = "thumbnailUrl";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View myFragmentView = inflater.inflate(R.layout.fragment_full, container, false);
Bundle bundle = this.getArguments();
String page = bundle.getString("images", bitmap);
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
final NetworkImageView thumbNail = (NetworkImageView)myFragmentView.findViewById(R.id.thumbnail);
thumbNail.setImageUrl(page, imageLoader);
return myFragmentView;
}
}
**Note:**Listview to fulldetail image getting properply but not getting to my frament from details Activity

pass image url through fragment's setArguments() method and fetch it in fragment using getArguments().

thumbNail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyFragment yourFragment= new MyFragment();
Bundle b = new Bundle();
b.putString("url", getIntent.getStringExtra("images"));
yourFragment.setArguments(b);
fragmentTransaction.add(R.id.myfragment, yourFragment, "FRAGMENT");
fragmentTransaction.commit();
}
});

Related

ArrayList get method causes app to be crashed

I am inflating the menu from JSON which contain its name and id. I had written Fragment5 which is used to be calling an URL for JSON. In that url I want to call the id of the menu.
This is my code. The code is running fine if I am commenting the two line
String scat = menu_nms.get(0);
int cat = Integer.parseInt(scat);
MainActivity.java
package com.latrodealz.wowwdealz;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.latrodealz.wowwdealz.adapter.SlidingMenuAdapter;
import com.latrodealz.wowwdealz.fragment.Fragment1;
import com.latrodealz.wowwdealz.fragment.Fragment2;
import com.latrodealz.wowwdealz.fragment.Fragment3;
import com.latrodealz.wowwdealz.fragment.Fragment4;
import com.latrodealz.wowwdealz.fragment.Fragment5;
import com.latrodealz.wowwdealz.model.ItemSlideMenu;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by NgocTri on 10/18/2015.
*/
public class MainActivity extends AppCompatActivity {
private List<ItemSlideMenu> listSliding;
private SlidingMenuAdapter adapter;
private ListView listViewSliding;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
//Web api url
public static final String MENU_URL = "http://69.89.31.191/~webtech6/android_wow/menu_dtls.php";
//Tag values to read from json
public static final String MENU_ID = "menu_id";
public static final String MENU_NM = "menu_nm";
//ArrayList for Storing menu ids and names
private ArrayList<String> menu_ids;
private ArrayList<String> menu_nms;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menu_ids = new ArrayList<>();
menu_nms = new ArrayList<>();
//Calling the getMenuData method
getMenuData();
//Init component
listViewSliding = (ListView) findViewById(R.id.lv_sliding_menu);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
listSliding = new ArrayList<>();
//Add item for sliding list
listSliding.add(new ItemSlideMenu(R.drawable.ic_action_settings, "Home"));
adapter = new SlidingMenuAdapter(this, listSliding);
listViewSliding.setAdapter(adapter);
//Display icon to open/ close sliding list
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Set title
setTitle(listSliding.get(0).getTitle());
//item selected
listViewSliding.setItemChecked(0, true);
//Close menu
drawerLayout.closeDrawer(listViewSliding);
//Display fragment 1 when start
replaceFragment(0);
//Handle on item click
listViewSliding.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Set title
setTitle(listSliding.get(position).getTitle());
//item selected
listViewSliding.setItemChecked(position, true);
//Replace fragment
replaceFragment(position);
//Close menu
drawerLayout.closeDrawer(listViewSliding);
}
});
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_opened, R.string.drawer_closed) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
}
};
drawerLayout.addDrawerListener(actionBarDrawerToggle);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void getMenuData() {
//Showing a progress dialog while our app fetches the data from url
final ProgressDialog loading = ProgressDialog.show(this, "Please wait...", "Fetching data...", false, false);
//Creating a json array request to get the json from our api
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(MENU_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Dismissing the progressdialog on response
loading.dismiss();
//Displaying our grid
showMenu(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding our request to the queue
requestQueue.add(jsonArrayRequest);
}
private void showMenu(JSONArray jsonArray) {
//Looping through all the elements of json array
for (int i = 0; i < jsonArray.length(); i++) {
//Creating a json object of the current index
JSONObject obj = null;
try {
//getting json object from current index
obj = jsonArray.getJSONObject(i);
//getting menuid and menuname from json object
menu_ids.add(obj.getString(MENU_ID));
menu_nms.add(obj.getString(MENU_NM));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Add item for sliding list
for (int i = 0; i < menu_ids.size(); i++) {
listSliding.add(new ItemSlideMenu(R.drawable.ic_action_about, menu_nms.get(i)));
}
adapter = new SlidingMenuAdapter(this, listSliding);
listViewSliding.setAdapter(adapter);
//Add item for sliding list
listSliding.add(new ItemSlideMenu(R.drawable.ic_action_settings, "MY CART"));
listSliding.add(new ItemSlideMenu(R.drawable.ic_action_settings, "MY ACCOUNT"));
listSliding.add(new ItemSlideMenu(R.drawable.ic_action_settings, "MY ORDERS"));
adapter = new SlidingMenuAdapter(this, listSliding);
listViewSliding.setAdapter(adapter);
//Display Array List
// Toast.makeText(getBaseContext(), menu_ids + "", Toast.LENGTH_LONG).show();
// Toast.makeText(getBaseContext(), menu_nms + "", Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_search:
// User chose the "Settings" item, show the app settings UI...
Intent intent = new Intent(MainActivity.this, SearchableActivity.class);
startActivityForResult(intent, 0);
//Toast.makeText(this, "You have selected Search Search Menu", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_kart:
// User chose the "Favorite" action, mark the current item
// as a favorite...
Toast.makeText(this, "You have selected Search KART Menu", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_notifications:
// User chose the "Favorite" action, mark the current item
// as a favorite...
Toast.makeText(this, "You have selected Search Notifications Menu", Toast.LENGTH_SHORT).show();
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
//return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
/**
* Called when the user clicks the Search Menu
* public void callSearchActivity(View view) {
* Intent intent = new Intent(this, SearchActivity.class);
* startActivity(intent);
* }
*/
//Create method replace fragment
private void replaceFragment(int pos) {
Fragment fragment = null;
int menu_size = menu_ids.size();
String scat = menu_nms.get(0);
int cat = Integer.parseInt(scat);
if (pos == 0) {
fragment = new Fragment1();
} else if (pos > 0 && pos <= menu_size) {
SharedPreferences sharePref = getSharedPreferences("menu_dtls", Context.MODE_PRIVATE);
sharePref.edit().remove("menu_id").commit();
SharedPreferences.Editor editor = sharePref.edit();
editor.putInt("menu_id", pos);
editor.apply();
fragment = new Fragment5();
} else if (pos == (menu_size + 1)) {
fragment = new Fragment2();
} else if (pos == (menu_size + 2)) {
fragment = new Fragment3();
} else if (pos == (menu_size + 3)) {
fragment = new Fragment4();
} else {
fragment = new Fragment1();
}
if (null != fragment) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_content, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.latrodealz.wowwdealz/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.latrodealz.wowwdealz/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
Fragment5.java
package com.latrodealz.wowwdealz.fragment;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import com.latrodealz.wowwdealz.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class Fragment5 extends Fragment {
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String FLAG = "flag";
public Fragment5() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment5, container, false);
//TextView menu_id = (TextView)rootView.findViewById(R.id.textid);
//SharedPreferences sharePref = this.getActivity().getSharedPreferences("menu_dtls", Context.MODE_PRIVATE);
//int menuId = sharePref.getInt("menu_id", 0);
// menu_id.setText(String.valueOf(menuId));
ImageView purple=(ImageView)rootView.findViewById(R.id.gridicon);
purple.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getFragmentManager()
.beginTransaction()
.replace(R.id.main_content, new Fragment4())
.commit();
}
});
new DownloadJSON().execute();
return rootView;
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle("Fetching data...");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
SharedPreferences sharePref = getActivity().getSharedPreferences("menu_dtls", Context.MODE_PRIVATE);
int menuId = sharePref.getInt("menu_id", 0);
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://69.89.31.191/~webtech6/android_wow/load.php?catId="+menuId);
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("worldpopulation");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("rank", jsonobject.getString("rank"));
map.put("country", jsonobject.getString("country"));
map.put("population", jsonobject.getString("population"));
map.put("flag", jsonobject.getString("flag"));
// Set the JSON Objects into the array
//Toast.makeText(getActivity().getBaseContext(), map + "", Toast.LENGTH_LONG).show();
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) getActivity().findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
Perhaps you get exception during JSON parsing. You may surround Integer.parseInt(scat); with try- catch catching ParsingException if Json has no such a field.
But more neat solution is to use GSON with Retrofit, so you can automatically parse you response to java objects, created by jsonschema2pojo.com

get id of Json object using the intent , do a web query to get details (in json object) and then update the UI

I have two activities...In first activity its a list view where i get the data from the Json file....now when user click on an item of the list view a new activity should open...so i pass the id from activity 1 to activity 2 using an intent. Instead of sending all the details using intent is there any other way that i can only pass the id to activity 2 and then query json file to get details (json object) and then update the UI.
Here is my code.
Activity 1:-
package activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;
/**
* Created by on 11/25/15.
*/
public class ProductsList extends Activity {
// Log tag
private static final String TAG = ProductsList.class.getSimpleName();
// Movies json url
// private static final String url = "http://*.*.*.*:0000/android_login_api/toys.json"; //home
private static final String url = "http://*.*.*.*:0000/android_login_api/toys.json"; //starbucks
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
// Search EditText
EditText inputSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.products_list_view);
listView = (ListView) findViewById(R.id.list);
inputSearch = (EditText) findViewById(R.id.inputSearch);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Movie item = (Movie) adapter.getItem(position);
Intent intent = new Intent(ProductsList.this, ProductDetailInformation.class);
intent.putExtra("id", item.getId().toString());
// intent.putExtra("name", item.getTitle().toString());
// intent.putExtra("price", item.getPrice().toString());
// Bundle reviews = new Bundle();
// reviews.putDouble("rating", ((Number) item.getRating()).doubleValue());
// intent.putExtras(reviews);
// intent.putExtra("description", item.getDescription().toString());
//
// //send image
// BitmapDrawable bd = (BitmapDrawable) ((NetworkImageView) v.findViewById(R.id.thumbnail))
// .getDrawable();
// Bitmap bitmap=bd.getBitmap();
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// bd.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, baos);
// byte[] imgByte = baos.toByteArray();
// intent.putExtra("image", imgByte);
//based on item add info to intent
startActivity(intent);
}
});
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// // changing action bar color
// getActionBar().setBackgroundDrawable(
// new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setThumbnailUrl(obj.getString("image"));
movie.setRating(((Number) obj.get("rating"))
.doubleValue());
movie.setAddtocart(obj.getInt("addtocart"));
movie.setDescription(obj.getString("description"));
movie.setId(obj.getString("id"));
// movie.setThumbnailUrl(obj.getString("image1"));
// Price is json array
// JSONArray priceArry = obj.getInt("price");
// ArrayList<String> price = new ArrayList<String>();
// for (int j = 0; j < priceArry.length(); j++) {
// price.add((String) priceArry.get(j));
// }
movie.setPrice(obj.getString("price"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
//ProductsList.this.listView.getFilter().filter(cs);
// TODO Auto-generated method stub
String text = inputSearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
**
Activity 2:
**
package activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import adapter.CustomListAdapter;
import model.Movie;
import puerile.toystore.com.R;
/**
* Created by on 12/3/15.
*/
public class ProductDetailInformation extends Activity {
private static final String TAG = ProductDetailInformation.class.getSimpleName();
// Movies json url
// private static final String url = "http://*.*.*.*:0000/android_login_api/toys.json"; //home
private static final String url = "http://*.*.*.*:0000/android_login_api/toys.json"; //starbucks
private ProgressDialog pDialog;
TextView title;
TextView description;
TextView price;
TextView rating;
NetworkImageView image;
TextView id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
title = (TextView) findViewById(R.id.title);
price = (TextView) findViewById(R.id.price);
rating = (TextView) findViewById(R.id.rating);
description = (TextView) findViewById(R.id.description);
image = (NetworkImageView) findViewById(R.id.thumbnail);
Intent intent = getIntent();
// String headerInfo = intent.getExtras().getString("name");
// String priceInfo = intent.getExtras().getString("price");
//// String addtocartInfo = intent.getExtras().getString("addtocart");
// Bundle userdata = intent.getExtras();
// double result = userdata.getDouble("rating");
// String detailInfo = intent.getExtras().getString("description");
// // String ratingInfo = intent.getExtras().getString("rating");
// Bundle extras = getIntent().getExtras();
// byte[] b = extras.getByteArray("image");
// Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
// BitmapDrawable background = new BitmapDrawable(bmp);
String idInfo = intent.getExtras().getString("id");
// title.setText(headerInfo);
// price.setText(priceInfo);
//// title.setText(addtocartInfo);
// String stringdouble = Double.toString(result);
// rating.setText(stringdouble);
// description.setText(detailInfo);
// image.setBackground(background);
id.setText(idInfo);
hidePDialog();
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
You will need a proper endpoint to get the toy details. Normally passing the id as a REST path (android_login_api/toys/) or in the query string (android_login_api/toys?id=), there are multiple options.
If you have only the endpoint with the list of toys, instead of passing only the id to the Activity2, you can also use the intent to send the json section of the toy which user have been selected, as a string. So, Activity2 will receive the json data in the intent data.
Anyway, I extremely recommend you to use a serialisation library, such as GSON or Jackson, to convert JSON into Java classes. It is easy to create a model from JSON objects and configure Volley to return the required model Java class (or list) when you send a Volley request.

How do I reuse the image that is already imported to the detail view of this RSS Fragment

I have this code that receives the RSS feed and displays it into a Row, however, it does not carry over the image once the row has been clicked. How do I achieve this image transfer from the list view to the detailed view.
This is the RSS Reader View
package com.sieae.jamaicaobserver.rss.ui;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* This activity is used to display a list of rss items
*/
public class RssFragment extends Fragment {
private RSSFeed myRssFeed = null;
private Activity mAct;
private LinearLayout ll;
private RelativeLayout pDialog;
public class MyCustomAdapter extends ArrayAdapter<RSSItem> {
public MyCustomAdapter(Context context, int textViewResourceId,
List<RSSItem> list) {
super(context, textViewResourceId, list);
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
final ViewHolder holder;
if(row==null){
LayoutInflater inflater=mAct.getLayoutInflater();
row=inflater.inflate(R.layout.fragment_rss_row, null);
holder = new ViewHolder();
holder.listTitle=(TextView)row.findViewById(R.id.listtitle);
holder.listPubdate=(TextView)row.findViewById(R.id.listpubdate);
holder.listDescription=(TextView)row.findViewById(R.id.shortdescription);
holder.listThumb =(ImageView)row.findViewById(R.id.listthumb);
row.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.listTitle.setText(myRssFeed.getList().get(position).getTitle());
holder.listPubdate.setText(myRssFeed.getList().get(position).getPubdate());
String html = myRssFeed.getList().get(position).getRowDescription();
holder.listDescription.setText(html);
holder.listThumb.setImageDrawable(null);
//get Imageloader
ImageLoader imageLoader = Helper.initializeImageLoader(mAct);
//LayoutInflater inflater = (LayoutInflater) mAct
// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//View v = inflater.inflate(R.layout.fragment_rss, null);
//ListView listView = (ListView) v.findViewById(R.id.rsslist);
//pausing on scrolling the listview
//boolean pauseOnScroll = true; // or true
//boolean pauseOnFling = true; // or false
//PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling);
//listView.setOnScrollListener(listener);
String thumburl = myRssFeed.getList().get(position).getThumburl();
if (thumburl != "" && thumburl != null){
//setting the image
imageLoader.displayImage(myRssFeed.getList().get(position).getThumburl(), holder.listThumb, new SimpleImageLoadingListener() {
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (10 > loadedImage.getWidth() || 10 > loadedImage.getHeight()) {
// handle scaling
holder.listThumb.setVisibility(View.GONE);
} else {
holder.listThumb.setVisibility(View.VISIBLE);
}
}
});
} else {
holder.listThumb.setVisibility(View.GONE);
}
return row;
}
}
static class ViewHolder {
TextView listTitle;
TextView listPubdate;
TextView listDescription;
ImageView listThumb;
int position;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ll = (LinearLayout) inflater.inflate(R.layout.fragment_rss, container, false);
setHasOptionsMenu(true);
if ((getResources().getString(R.string.ad_visibility).equals("0"))){
// Look up the AdView as a resource and load a request.
AdView adView = (AdView) ll.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}
return ll;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAct = getActivity();
Log.v("INFO", "onAttach() called");
new MyTask().execute();
}
private class MyTask extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute(){
pDialog = (RelativeLayout) ll.findViewById(R.id.progressBarHolder);
}
#Override
protected Void doInBackground(Void... arg0) {
try {
String weburl = RssFragment.this.getArguments().getString(MainActivity.DATA);
URL rssUrl = new URL(weburl);
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler();
myXMLReader.setContentHandler(myRSSHandler);
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
myRssFeed = myRSSHandler.getFeed();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ListView listview = (ListView) ll.findViewById(R.id.rsslist);
if (myRssFeed != null) {
MyCustomAdapter adapter = new MyCustomAdapter(mAct,
R.layout.fragment_rss_row, myRssFeed.getList());
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v,
int position, long id) {
Intent intent = new Intent(mAct,
RssDetailActivity.class);
Bundle bundle = new Bundle();
bundle.putString("keyTitle", myRssFeed
.getItem(position).getTitle());
bundle.putString("keyDescription",
myRssFeed.getItem(position).getDescription());
bundle.putString("keyLink", myRssFeed.getItem(position)
.getLink());
bundle.putString("keyPubdate",
myRssFeed.getItem(position).getPubdate());
bundle.putString("keyThumburl",
myRssFeed.getItem(position).getThumburl());
intent.putExtras(bundle);
startActivity(intent);
}
});
} else {
Helper.noConnection(mAct, true);
}
if (pDialog.getVisibility() == View.VISIBLE) {
pDialog.setVisibility(View.GONE);
//feedListView.setVisibility(View.VISIBLE);
Helper.revealView(listview,ll);
}
super.onPostExecute(result);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.rss_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.refresh_rss:
new MyTask().execute();
return true;
case R.id.info:
//show information about the feed in general in a dialog
if (myRssFeed!=null)
{
String FeedTitle = (myRssFeed.getTitle());
String FeedDescription = (myRssFeed.getDescription());
//String FeedPubdate = (myRssFeed.getPubdate()); most times not present
String FeedLink = (myRssFeed.getLink());
AlertDialog.Builder builder = new AlertDialog.Builder(mAct);
String titlevalue = getResources().getString(R.string.feed_title_value);
String descriptionvalue = getResources().getString(R.string.feed_description_value);
String linkvalue = getResources().getString(R.string.feed_link_value);
if (FeedLink.equals("")){
builder.setMessage(titlevalue+": \n"+FeedTitle+
"\n\n"+descriptionvalue+": \n"+FeedDescription);
} else {
builder.setMessage(titlevalue+": \n"+FeedTitle+
"\n\n"+descriptionvalue+": \n"+FeedDescription +
"\n\n"+linkvalue+": \n"+FeedLink);
};
builder.setNegativeButton(getResources().getString(R.string.ok),null)
.setCancelable(true);
builder.create();
builder.show();
}else{
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
This is the detailed view
package com.sieae.jamaicaobserver.rss.ui;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.sieae.jamaicaobserver.R;
import com.sieae.jamaicaobserver.fav.FavDbAdapter;
import com.sieae.jamaicaobserver.util.WebHelper;
import com.sieae.jamaicaobserver.web.WebviewActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/**
* This activity is used to display details of a rss item
*/
public class RssDetailActivity extends ActionBarActivity {
private WebView wb;
private FavDbAdapter mDbHelper;
private Toolbar mToolbar;
String date;
String link;
String title;
String description;
String favorite;
String listThumb;
#SuppressLint("SetJavaScriptEnabled")#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rss_details);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
TextView detailsTitle = (TextView) findViewById(R.id.detailstitle);
TextView detailsPubdate = (TextView) findViewById(R.id.detailspubdate);
Bundle bundle = this.getIntent().getExtras();
detailsTitle.setText(bundle.getString("keyTitle"));
detailsPubdate.setText(bundle.getString("keyPubdate"));
date = (bundle.getString("keyPubdate"));
link = (bundle.getString("keyLink"));
title = (bundle.getString("keyTitle"));
description = (bundle.getString("keyDescription"));
favorite = (bundle.getString("keyFavorites"));
listThumb = (bundle.getString("keyThumburl"));
wb = (WebView) findViewById(R.id.descriptionwebview);
//parse the html and apply some styles
Document doc = Jsoup.parse(description);
String html = WebHelper.docToBetterHTML(doc, this);;
wb.getSettings().setJavaScriptEnabled(true);
wb.loadDataWithBaseURL(link, html , "text/html", "UTF-8", "");
Log.v("INFO", "Wordpress HTML: " + html);
wb.setBackgroundColor(Color.argb(1, 0, 0, 0));
wb.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
wb.getSettings().setDefaultFontSize(WebHelper.getWebViewFontSize(this));
wb.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null && (url.startsWith("http://") || url.startsWith("http://"))) {
Intent mIntent = new Intent(RssDetailActivity.this, WebviewActivity.class);
mIntent.putExtra(WebviewActivity.URL, url);
startActivity(mIntent);
return true;
} else {
Uri uri = Uri.parse(url);
Intent ViewIntent = new Intent(Intent.ACTION_VIEW, uri);
// Verify it resolves
PackageManager packageManager = getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(ViewIntent, 0);
boolean isIntentSafe = activities.size() > 0;
// Start an activity if it's safe
if (isIntentSafe) {
startActivity(ViewIntent);
}
return true;
}
}
});
if ((getResources().getString(R.string.ad_visibility).equals("0"))) {
// Look up the AdView as a resource and load a request.
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}
Button btnOpen = (Button) findViewById(R.id.openbutton);
//Listening to button event
btnOpen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(link));
startActivity(intent);
}
});
Button btnFav = (Button) findViewById(R.id.favoritebutton);
//Listening to button event
btnFav.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
mDbHelper = new FavDbAdapter(RssDetailActivity.this);
mDbHelper.open();
if (mDbHelper.checkEvent(title, description, date, link, "", "", "rss")) {
// Item is new
mDbHelper.addFavorite(title, description, date, link, "", "", "rss");
Toast toast = Toast.makeText(RssDetailActivity.this, getResources().getString(R.string.favorite_success), Toast.LENGTH_LONG);
toast.show();
} else {
Toast toast = Toast.makeText(RssDetailActivity.this, getResources().getString(R.string.favorite_duplicate), Toast.LENGTH_LONG);
toast.show();
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.share:
String html = description;
html = html.replaceAll("<(.*?)\\>", ""); //Removes all items in brackets
html = html.replaceAll("<(.*?)\\\n", ""); //Must be undeneath
html = html.replaceFirst("(.*?)\\>", ""); //Removes any connected item to the last bracket
html = html.replaceAll(" ", "");
html = html.replaceAll("&", "");
html = html.replaceAll("‘", "‘");
String linkvalue = getResources().getString(R.string.item_share_begin);
String seenvalue = getResources().getString(R.string.item_share_middle);
String appvalue = getResources().getString(R.string.item_share_end);
String applicationName = getResources().getString(R.string.app_name);
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
//this is the text that will be shared
sendIntent.putExtra(Intent.EXTRA_TEXT, (html + linkvalue + link + seenvalue + applicationName + appvalue));
sendIntent.putExtra(Intent.EXTRA_SUBJECT, title); //you can replace title with a string of your choice
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getString(R.string.share_header)));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.rss_detail_menu, menu);
return true;
}
}
You can send Image via Intent as ByteArray or try loading from URL. Loading from URL is preferred as it will not bring OutOfMemoryException or any other issues while passing large bitmap images via Intent. If image is small, you may pass them via Intent.
The code below shows both the methods. Implement which suits your need or works in your URL case.
Sender Activity
//Download image from thumbUrl to bitmap
URL newurl = new URL(myRssFeed.getItem(position).getThumburl());
Bitmap bitmap = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
Intent intent = new Intent(mAct, RssDetailActivity.class);
Bundle bundle = new Bundle();
bundle.putString("keyTitle", myRssFeed.getItem(position).getTitle());
bundle.putString("keyDescription", myRssFeed.getItem(position).getDescription());
bundle.putString("keyLink", myRssFeed.getItem(position).getLink());
bundle.putString("keyPubdate",myRssFeed.getItem(position).getPubdate());
//pass image url
bundle.putString("keyThumburl", myRssFeed.getItem(position).getThumburl());
//sent image bitmap byte array
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, bs);
bundle.putByteArray("byteArray", bs.toByteArray());
intent.putExtras(bundle);
startActivity(intent);
Receiver Activity
Bundle bundle = this.getIntent().getExtras();
//load from bitmap bytearray
Bitmap bitmap = BitmapFactory.decodeByteArray(bundle.getByteArray("byteArray"),0,bundle.getByteArray("byteArray").length);
imageView.setImageBitmap(bitmap);
//or load from image url
new LoadImage().execute(bundle.getString("keyThumbUrl"));
Create an AsyncTask to load image to ImageView from URL sent via Intent
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
imageView.setImageBitmap(image);
} else{
Toast.makeText(RssDetailActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
}

Error: Content view not yet created

I'm new to Android development and I have a problem with setting up getting into the next activity when I click an item in my listview within my ListFragment.
When I compile and run the app, it crashes with the error: Content view not yet created. Here is the relevant code. Any help would be much appreciated!
MainActivity:
package com.example.szen95.meddict;
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.SearchView;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new SearchFragment())
.commit();
}
getSupportActionBar().setElevation(0f);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
SearchManager searchManager = (SearchManager) getSystemService( Context.SEARCH_SERVICE );
SearchView searchView = (SearchView) menu.findItem( R.id.search_bar ).getActionView();
searchView.setSearchableInfo( searchManager.getSearchableInfo( getComponentName() ) );
return super.onCreateOptionsMenu(menu);
}
#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.
return super.onOptionsItemSelected(item);
}
}
SearchFragment:
package com.example.szen95.meddict;
/**
* Created by szen95 on 6/15/15.
*/
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
/**
* A placeholder fragment containing a simple view.
*/
public class SearchFragment extends ListFragment {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://dailymed.nlm.nih.gov/dailymed/services/v2/drugclasses.json";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_CODE = "code";
private static final String TAG_CODING_SYSTEM = "codingSystem";
private static final String TAG_TYPE = "type";
private static final String TAG_NAME = "name";
// contacts JSONArray
JSONArray data = null;
// ArrayAdapter<String> mConditionsAdapter;
public SearchFragment() {
}
ArrayList<HashMap<String, String>> dataList;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
dataList = new ArrayList<HashMap<String, String>>();
// Creating view correspoding to the fragment
View v = inflater.inflate(R.layout.fragment_main, container, false);
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String code = ((TextView) view.findViewById(R.id.code))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getActivity().getApplicationContext(),
Details.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_CODE, code);
startActivity(in);
}
});
new GetData().execute();
return v;
}
/**
* Async task class to get json by making HTTP call
* */
private class GetData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
//
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_DATA);
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String code = c.getString(TAG_CODE);
String codingSystem = c.getString(TAG_CODING_SYSTEM);
String type = c.getString(TAG_TYPE);
String name = c.getString(TAG_NAME);
// tmp hashmap for single contact
HashMap<String, String> data = new HashMap<String, String>();
// adding each child node to HashMap key => value
data.put(TAG_CODE, code);
data.put(TAG_CODING_SYSTEM, codingSystem);
data.put(TAG_TYPE, type);
data.put(TAG_NAME, name);
// adding contact to contact list
dataList.add(data);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
SimpleAdapter adapter = new SimpleAdapter(getActivity(), dataList,
R.layout.list_item_search, new String[] { TAG_NAME, TAG_CODE}, new int[] { R.id.name,
R.id.code});
setListAdapter(adapter);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
//
// #Override
// public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// inflater.inflate(R.menu.menu_main, menu);
//
//
// }
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_about) {
// FetchDataTask defTask = new FetchDataTask();
// defTask.execute();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Details:
package com.example.szen95.meddict;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.TextView;
public class Details extends ActionBarActivity {
// JSON node keys
private static final String TAG_NAME = "name";
private static final String TAG_CODE = "code";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String code = in.getStringExtra(TAG_CODE);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCode = (TextView) findViewById(R.id.code_label);
lblName.setText(name);
lblCode.setText(code);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return onCreateOptionsMenu(menu);
}
}
SearchFragment extends ListFragment. In a ListFragment, getListView() cannot be called in onCreateView(), because onCreateView() is creating the fragment's content view and has not yet completed. The call to getListView() in SearchFragment is the cause of the exception.
Move the the call to getListView() and related to code to one of the fragment lifecycle methods that is called after onCreateView(), such as onViewCreated() or onActivityCreate(). For example:
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String code = ((TextView) view.findViewById(R.id.code))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getActivity().getApplicationContext(),
Details.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_CODE, code);
startActivity(in);
}
});
}

Loading in Android ListView stucked like forever

I'm new to android programming and I'm practicing in making a Facebook app. I got this ListView and which i will be using to display some information i got from facebook. But the problem is when the Listview starts to load the datas its stucked in the loading part and its taking forever but theres no error in the codes. here are the codes:
package com.example.forwardjunction;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphObject;
public class FragmentLayout extends Activity {
ProgressDialog mDialog;
static String postMessage;
static String from;
static String timeCreated;
static String postId;
static ArrayList<HashMap<String, String>> feedList;
private static final String TAG_MESSAGE = "message";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
static ListView list;
TextView author, feedMessage;
static UiLifecycleHelper uiHelper;
public FragmentLayout() {
// TODO Auto-generated constructor stub
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_layout);
author = (TextView) findViewById(R.id.author);
feedMessage = (TextView) findViewById(R.id.message);
feedList = new ArrayList<HashMap<String, String>>();
uiHelper = new UiLifecycleHelper(this, statusCallback);
// list = (ListView) findViewById(R.id.list);
}
public static class TitlesFragment extends ListFragment {
boolean mDualPane;
int mCurCheckPosition = 0;
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
//
// return null;
// }
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListView list = getListView();
feedList = new ArrayList<HashMap<String, String>>();
Request loadPageFeed = new Request(Session.getActiveSession(),
"163340583656/posts", null, HttpMethod.GET,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
// TODO Auto-generated method stub
Log.i("FEED RESPONSE", response.toString());
try {
GraphObject graphObj = response.getGraphObject();
JSONObject json = graphObj.getInnerJSONObject();
JSONArray jArray = json.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject currObj = jArray.getJSONObject(i);
postId = currObj.getString("id");
if (currObj.has("message")) {
postMessage = currObj.getString("message");
} else if (currObj.has("story")) {
postMessage = currObj.getString("story");
} else {
postMessage = "Forward Publication has posted something.";
}
JSONObject fromObj = currObj
.getJSONObject("from");
from = fromObj.getString("name");
timeCreated = currObj
.getString("created_time");
HashMap<String, String> feed = new HashMap<String, String>();
feed.put(TAG_ID, postId);
feed.put(TAG_MESSAGE, postMessage);
feed.put(TAG_NAME, from);
Log.i("passed", feed.toString());
feedList.add(feed);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
loadPageFeed.executeAsync();
BaseAdapter adapter = new SimpleAdapter(getActivity(), feedList,
R.layout.feed_item, new String[] { TAG_MESSAGE, TAG_NAME,
TAG_ID }, new int[] { R.id.message, R.id.author,
R.id.id_tv });
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
View detailsFrame = getActivity(). findViewById(R.id.details);
mDualPane = detailsFrame != null
&& detailsFrame.getVisibility() == View.VISIBLE;
if (savedInstanceState != null) {
// Restore last state for checked position.
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
if (mDualPane) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
showDetails(mCurCheckPosition);
} else {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setItemChecked(mCurCheckPosition, true);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}
void showDetails(int index) {
mCurCheckPosition = index;
if (mDualPane) {
getListView().setItemChecked(index, true);
DetailsFragment details = (DetailsFragment) getFragmentManager()
.findFragmentById(R.id.details);
if (details == null || details.getShownIndex() != index) {
details = DetailsFragment.newInstance(index);
FragmentTransaction ft = getFragmentManager()
.beginTransaction();
ft.replace(R.id.details, details);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else {
Intent intent = new Intent();
intent.setClass(getActivity(), DetailsActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
}
}
public static class DetailsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
finish();
return;
}
if (savedInstanceState == null) {
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction()
.add(android.R.id.content, details).commit();
}
}
}
public static class DetailsFragment extends Fragment {
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ScrollView scroller = new ScrollView(getActivity());
TextView text = new TextView(getActivity());
int padding = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 4, getActivity()
.getResources().getDisplayMetrics());
text.setPadding(padding, padding, padding, padding);
scroller.addView(text);
// text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
return scroller;
}
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onSaveInstanceState(Bundle savedState) {
super.onSaveInstanceState(savedState);
uiHelper.onSaveInstanceState(savedState);
}
private Session.StatusCallback statusCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.d("FacebookSampleActivity", "Facebook session opened");
} else if (state.isClosed()) {
Log.d("FacebookSampleActivity", "Facebook session closed");
}
}
};
}
And heres the xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/titles"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.example.forwardjunction.FragmentLayout$TitlesFragment" />
</FrameLayout>
I hope you can help me. cheers
*edit> I think the problem is that the listview is empty, i dont really know where the problem is
because the UI thread is Blocked
Rather than using your thread class use Asynctask
class xyz extends Asynctask
{
}
then add to overrididen methods
do in background
on post execute
I m posting the sample code of mine
package com.example.urlconnectionclass;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ProgressDialog pDialog;
String urlString="http://api.androidhive.info/contacts/";
TextView tc;
String s;
JSONArray jr;
JSONObject jb,jb2;
ArrayList<HashMap<String, String>> contact;
String tagid="id";
String tagname="name",tagemail="email",taggender="gender",tagadd="address";
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView)findViewById(R.id.listView1);
contact = new ArrayList<HashMap<String,String>>();
new urlconn().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class urlconn extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
URL url= new URL(urlString);
HttpURLConnection conn =(HttpURLConnection)url.openConnection();
conn.connect();
InputStream is= conn.getInputStream();
s=convertStreamToString(is);
jb = new JSONObject(s);
jr= jb.getJSONArray("contacts");
for(int i=0;i<=jr.length();i++)
{
jb2=jr.getJSONObject(i);
String id=jb2.getString(tagid);
String name=jb2.getString(tagname);
String email=jb2.getString(tagemail);
String address=jb2.getString(tagadd);
String gender=jb2.getString("gender");
HashMap<String, String> map = new HashMap<String, String>();
map.put(tagid, id);
map.put(tagname, name);
map.put(tagemail, email);
map.put("gender", gender);
map.put(tagadd, address);
contact.add(map);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String [] sr={tagid,tagname,tagemail,"gender",tagadd};
int [] in= {R.id.textView1,R.id.textView2,R.id.textView3,R.id.textView4,R.id.textView5};
SimpleAdapter sa= new SimpleAdapter(MainActivity.this, contact, R.layout.mapxml,sr, in);
lv.setAdapter(sa);
}
public String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
}

Categories

Resources