i have created a custom alertbar on context menu, which is on the list viewed from json parsing. what i want is to get a details(name of the specific person on which the context menu is opened). i want to set Text in the on the alertbar.
Thank you very much for help.
enter code here
public class MyConnectionAsyncTask extends AsyncTask> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("Connecting...");
progressDialog.show();
}
#Override
protected List<MyconnectionManager> doInBackground(String... params) {
try {
URL url = new URL(params[0]);// taking params from execute method
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();//opening connection
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));//putting data into buffer from input stream
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
String json_str = result.toString();
JSONObject parentObject = new JSONObject(json_str);
JSONArray parentArray = parentObject.getJSONArray("result_array");//ARRAY name from API will come here
ArrayList<MyconnectionManager> connectionManagerList = new ArrayList<MyconnectionManager>();//created a list bc we have list of connections
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
MyconnectionManager myconnectionManager = new MyconnectionManager(getActivity());
myconnectionManager.setFullname_myConnection(finalObject.getString("fullname"));
myconnectionManager.setProfilePic_myConnection(finalObject.getString("profile_pic"));
myconnectionManager.setPosition_myconnection(finalObject.getString("position"));
myconnectionManager.setCompany_myConnection(finalObject.getString("company"));
myconnectionManager.setLocation_myConnection(finalObject.getString("location"));
connectionManagerList.add(myconnectionManager);//adding to list
}
return connectionManagerList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<MyconnectionManager> result) {
super.onPostExecute(result);
progressDialog.dismiss();
MyConnectionAdapter adapter = new MyConnectionAdapter(getActivity(), R.layout.single_row_my_connections, result);//creating adpater here
connectionList.setAdapter(adapter);
}
}
adpater Class is below
public class MyConnectionAdapter extends ArrayAdapter {
private List<MyconnectionManager> myconnectionManagerList;
private int resource;
LayoutInflater inflater;
public MyConnectionAdapter(Context context, int resource, List objects) {
super(context, resource, objects);
this.resource = resource;// resource has the layout view so we can also give resource below instead of layout
myconnectionManagerList = objects;
inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.single_row_my_connections, null);//we can give resource here
}
ImageView imageView;
TextView name, company, location, position_company;
imageView = (ImageView) convertView.findViewById(R.id.iv_profile_pic_myconnection);
name = (TextView) convertView.findViewById(R.id.tvname_myconncetion);
company = (TextView) convertView.findViewById(R.id.tvCompany_myconnection);
location = (TextView) convertView.findViewById(R.id.tvlocation_myconnections);
position_company = (TextView) convertView.findViewById(R.id.tvPosition_myconnection);
ImageLoader.getInstance().displayImage(myconnectionManagerList.get(position).getProfilePic_myConnection(), imageView);
name.setText(myconnectionManagerList.get(position).getFullname_myConnection());
company.setText(myconnectionManagerList.get(position).getCompany_myConnection());
location.setText(myconnectionManagerList.get(position).getLocation_myConnection());
position_company.setText(myconnectionManagerList.get(position).getPosition_myconnection());
return convertView;
}
}
context menu is below
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderIcon(R.drawable.small_logo);
menu.setHeaderTitle("Choose Action");
menu.add(0, 1, 0, "Send Message");
menu.add(0,2,1,"Remove Connection");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getItemId()==1){
Toast.makeText(getActivity(),"Send Message",Toast.LENGTH_SHORT).show();
View view=LayoutInflater.from(getActivity()).inflate(R.layout.send_message_layout,null,false);
final EditText et_sub= (EditText) view.findViewById(R.id.et_sub_send_Message);
final EditText et_msg= (EditText) view.findViewById(R.id.etMessage_send_Message);
TextView name= (TextView) view.findViewById(R.id.tv_name_send_message);
name.setText("To: ");//name of user will come here
AlertDialog.Builder ab=new AlertDialog.Builder(getActivity());
ab.setTitle("Send Message");
ab.setView(view);
ab.setNegativeButton("Cancel", null);
ab.setPositiveButton("Send", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String sub = et_sub.getText().toString();
String msg = et_msg.getText().toString();
Toast.makeText(getActivity(), sub + " " + msg, Toast.LENGTH_SHORT).show();
}
});
ab.show();
}else {
Toast.makeText(getActivity(),"Remove Connection",Toast.LENGTH_SHORT).show();
}
return true;
}
You can use
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
int listPosition = info.position;
String nameoOfUser = ((TextView)info.targetView.findViewById(R.id.YOUR_TEXTVIEW_ID)).getText().toString();
name.setText("To: " + nameoOfUser );
}
TextView textViewItem = (TextView)convertView.findViewById(R.id.textViewItem);
textViewItem.setText("your text");
Related
I am building a news app and I want to cache a JSON response to use when there is no network. I tried a lot of ways but it did not work for me.
My async task and my adapter are another side problem when the list loads new items it goes to the top of the screen and after that it adds the items. How can I fix this?
private class jsontask extends AsyncTask<String, String, List<newsmodel>> {
#Override
protected List<newsmodel> doInBackground(String... params) {
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finaljson = buffer.toString();
JSONObject parentobject = new JSONObject(finaljson);
JSONArray parentarray = parentobject.getJSONArray("articles");
for (int i = 0; i < parentarray.length(); i++) {
JSONObject finalobject = parentarray.getJSONObject(i);
newsmodel newsmodel = new newsmodel();
newsmodel.setAuthor(finalobject.getString("author"));
if (finalobject.isNull("author")) {
}
newsmodel.setDescription(finalobject.getString("description"));
newsmodel.setTitle(finalobject.getString("title"));
newsmodel.setImage(finalobject.getString("urlToImage"));
newsmodel.setUrl(finalobject.getString("url"));
newsmodel.setPublishedAt(finalobject.getString("publishedAt"));
moviemodelList.add(newsmodel);
}
return moviemodelList;
} catch (MalformedURLException e) {
e.printStackTrace();
return moviemodelList;
} catch (IOException e) {
e.printStackTrace();
return moviemodelList;
} catch (JSONException e) {
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<newsmodel> result) {
super.onPostExecute(result);
newsadapter adapter = new newsadapter(getApplicationContext(), R.layout.row, result);
lvnews.setAdapter(adapter);
}
}
public class newsadapter extends ArrayAdapter {
private List<newsmodel> moviemodelList;
private int resource;
private LayoutInflater inflater;
public newsadapter(Context context, int resource, List<newsmodel> objects) {
super(context, resource, objects);
moviemodelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
viewholder holder = null;
if (convertView == null) {
holder = new viewholder();
convertView = inflater.inflate(resource, null);
holder.newsimage = (ImageView) convertView.findViewById(R.id.imageView2);
holder.title = (TextView) convertView.findViewById(R.id.textView2);
holder.description = (TextView) convertView.findViewById(R.id.textView3);
holder.author = (TextView) convertView.findViewById(R.id.textView4);
holder.publishdate = (TextView) convertView.findViewById(R.id.textView5);
holder.dotsmenu = (ImageButton) convertView.findViewById(R.id.dots);
convertView.setTag(holder);
} else {
holder = (viewholder) convertView.getTag();
}
final ProgressBar progressBar;
progressBar = (ProgressBar) convertView.findViewById(R.id.progressBar);
ImageLoader.getInstance().displayImage(moviemodelList.get(position).getImage(), holder.newsimage, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
progressBar.setVisibility(view.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
progressBar.setVisibility(view.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
progressBar.setVisibility(view.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
progressBar.setVisibility(view.GONE);
}
});
holder.title.setText(moviemodelList.get(position).getTitle());
holder.description.setText(moviemodelList.get(position).getDescription());
holder.author.setText(moviemodelList.get(position).getAuthor());
holder.publishdate.setText(moviemodelList.get(position).getPublishedAt());
final viewholder finalHolder = holder;
holder.dotsmenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(page.this, finalHolder.dotsmenu);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.dots_menu, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.share:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, moviemodelList.get(position).getUrl());
sendIntent.setType("text/plain");
startActivity(sendIntent);
return true;
}
return false;
}
});
popup.show();
}
});
lvnews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(page.this, webview.class);
intent.putExtra("Link", moviemodelList.get(position).getUrl());
startActivity(intent);
}
});
return convertView;
}
Make a class for testing whether net connection is available or not .
ConnectionDetector.java
public class ConnectionDetector {
public Context context;
public ConnectionDetector(Context context)
{
this.context=context;
}
public boolean isConnecting() {
ConnectivityManager check=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (check!=null){
NetworkInfo[] infos=check.getAllNetworkInfo();
for (int i=0;i<infos.length;i++)
{
if (infos[i].getState()== NetworkInfo.State.CONNECTED)
return true;
}}
return false;
}
}
Create an object ob of above class .
ConnectionDetector ob=new ConnectionDetector(getApplicationContext());
Declare these variables as global variables :
File httpCacheDir;
long httpCacheSize = 5 * 1024 * 1024;// In place of 5 you can use size in mb
HttpResponseCache cache;
Make a function cacher():
public void cacher()
{
httpCacheDir = getExternalCacheDir();
// Cache Size of 5MB
try {
// Install the custom Cache Implementation
HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (Exception e) {
e.printStackTrace();
}
}
Just below the setContentView in onCreate ,add the following code :
cacher();
cache = HttpResponseCache.getInstalled();
if(cache != null) {
// If cache is present, flush it to the filesystem.
// Will be used when activity starts again.
cache.flush();
}
And here comes the final thing , below the url.openConnection line put the following snippet:
if (ob.isConnecting()){
connection.addRequestProperty("Cache-Control", "max-age=0");}
else{
connection.addRequestProperty("Cache-Control", "max-stale=" + 60*60*36);//In place of 36 , you can put hours for which cache is available
connection.setUseCaches(true);
}
I am loading JSON from server but the app crashes if the internet is not available. How to fix this problem? I have added try catch in most part. Unable to find the problem. lvMovies.setAdapter(adapter); gives error when internet is not available. Code works fine when internet is available
public class JSONTest extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private ListView lvMovies;
private ProgressDialog dialog;
private SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jsontest);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeMovieHits);
swipeRefreshLayout.setOnRefreshListener(this);
// Create default options which will be used for every
// displayImage(...) call if no options will be passed to this method
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config); // Do it on Application start
lvMovies = (ListView) findViewById(R.id.lvMovies);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading...");
//new JSONTask().execute("http://ankushkapoor2016.16mb.com/ankush/myjson.txt");
//new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoList.txt");
}
#Override
public void onRefresh() { //SwipeRefreshLayout Refresh Listener
try {
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesData.txt");
} catch (Exception e) {
Toast.makeText(JSONTest.this, e.getMessage() + "\n\n" + e.getCause(), Toast.LENGTH_LONG).show();
}
}
public class JSONTask extends AsyncTask<String, String, List<MovieModel>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
#Override
protected List<MovieModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson1 = buffer.toString();
SharedPreferences sharedPreferences = getSharedPreferences("JSON_DATA", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("json", finalJson1);
editor.commit();
String finalJson=sharedPreferences.getString("json","N/A");
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
List<MovieModel> movieModelList = new ArrayList<>();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
MovieModel movieModel = new MovieModel();
movieModel.setMovie(finalObject.getString("movie"));
movieModel.setYear(finalObject.getInt("year"));
movieModel.setRating((float) finalObject.getDouble("rating"));
movieModel.setDuration(finalObject.getString("duration"));
movieModel.setDirector(finalObject.getString("director"));
movieModel.setTagline(finalObject.getString("tagline"));
movieModel.setImage(finalObject.getString("image"));
movieModel.setStory(finalObject.getString("story"));
List<MovieModel.Cast> castList = new ArrayList<>();
for (int j = 0; j < finalObject.getJSONArray("cast").length(); j++) {
MovieModel.Cast cast = new MovieModel.Cast();
cast.setName(finalObject.getJSONArray("cast").getJSONObject(j).getString("name"));
castList.add(cast);
}
movieModel.setCastList(castList);
movieModelList.add(movieModel);
}
return movieModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<MovieModel> s) {
super.onPostExecute(s);
dialog.dismiss();
MovieAdapter adapter = new MovieAdapter(getApplicationContext(), R.layout.row, s);
lvMovies.setAdapter(adapter);
if (swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.setRefreshing(false);
}
}
}
public class MovieAdapter extends ArrayAdapter {
private List<MovieModel> movieModelList;
private int resource;
private LayoutInflater inflater;
public MovieAdapter(Context context, int resource, List<MovieModel> objects) {
super(context, resource, objects);
movieModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(resource, null);
holder.ivMovieIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
holder.tvMovie = (TextView) convertView.findViewById(R.id.tvMovie);
holder.tvTagline = (TextView) convertView.findViewById(R.id.tvTagline);
holder.tvYear = (TextView) convertView.findViewById(R.id.tvYear);
holder.tvDuration = (TextView) convertView.findViewById(R.id.tvDuration);
holder.tvDirector = (TextView) convertView.findViewById(R.id.tvDirector);
holder.rbMovieRating = (RatingBar) convertView.findViewById(R.id.rbMovie);
holder.tvCast = (TextView) convertView.findViewById(R.id.tvCast);
holder.tvStory = (TextView) convertView.findViewById(R.id.tvStory);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final ProgressBar progressBar;
progressBar = (ProgressBar) convertView.findViewById(R.id.progressBar);
try {
ImageLoader.getInstance().displayImage(movieModelList.get(position).getImage(), holder.ivMovieIcon, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
progressBar.setVisibility(View.GONE);
}
});
holder.tvMovie.setText(movieModelList.get(position).getMovie());
holder.tvTagline.setText(movieModelList.get(position).getTagline());
holder.tvYear.setText("Year: " + movieModelList.get(position).getYear());
holder.tvDuration.setText(movieModelList.get(position).getDuration());
holder.tvDirector.setText(movieModelList.get(position).getDirector());
holder.rbMovieRating.setRating(movieModelList.get(position).getRating() / 2);
StringBuffer stringBuffer = new StringBuffer();
for (MovieModel.Cast cast : movieModelList.get(position).getCastList()) {
stringBuffer.append(cast.getName() + ", ");
}
holder.tvCast.setText(stringBuffer);
holder.tvStory.setText(movieModelList.get(position).getStory());
} catch (Exception e) {
Toast.makeText(getContext(), e.getMessage() + "\n" + e.getCause(), Toast.LENGTH_SHORT).show();
}
return convertView;
}
class ViewHolder {
private ImageView ivMovieIcon;
private TextView tvMovie;
private TextView tvTagline;
private TextView tvYear;
private TextView tvDuration;
private TextView tvDirector;
private RatingBar rbMovieRating;
private TextView tvCast;
private TextView tvStory;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_json, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.jsonRefresh) {
try {
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesData.txt");
return true;
} catch (Exception e) {
Toast.makeText(JSONTest.this, e.getMessage() + "\n\n" + e.getCause(), Toast.LENGTH_LONG).show();
}
}
return super.onOptionsItemSelected(item);
}
}
To prevent crash you should check is device have internet connection, to do that you can use:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
You will also need to add to your AndroidManifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
If you provide logcat message, then maybe I can tell you more about your problem.
Your problem is that you are returning a null arraylist when the internet exceptions are caught. So, the onPostExecute gets null, then the adapter gets null.
If you don't want a null value, pre-declare an empty list and always return it.
Then, the app won't crash, but you will see no data populate in the list, so you may want to do some additional validation that internet is available.
#Override
protected List<MovieModel> doInBackground(String... params) {
List<MovieModel> movieModelList = new ArrayList<>();
try {
// TODO: Stuff
return movieModelList;
} catch ( ... ) {
} finally {
}
return movieModelList;
}
I've used a ListView to show my data from wamp server using mysql, also using JSON parsing , the following is my code....
public class JSONTask extends AsyncTask<String, String, List<PumpModel>> {
#Override
protected List<PumpModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJSON = buffer.toString();
JSONObject parentObject = new JSONObject(finalJSON);
JSONArray parentArray = parentObject.getJSONArray("server_response");
List<PumpModel> pumpModelList = new ArrayList<>();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
PumpModel pumpModel = new PumpModel();
pumpModel.setPump(finalObject.getString("Pump"));
pumpModel.setAvailable(finalObject.getString("Available"));
pumpModelList.add(pumpModel);
}
return pumpModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<PumpModel> result) {
super.onPostExecute(result);
//TODO need to set the data to the list
PumpAdapter adapter = new PumpAdapter(getApplicationContext(), R.layout.row, result);
lvPump.setAdapter(adapter);
}
}
public class PumpAdapter extends ArrayAdapter {
private List<PumpModel> pumpModelList;
private int resource;
private LayoutInflater inflater;
public PumpAdapter(Context context, int resource, List<PumpModel> objects) {
super(context, resource, objects);
pumpModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(resource, null);
}
ImageView ivIcon;
TextView tvPump;
ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
tvPump = (TextView) convertView.findViewById(R.id.tvPump);
// Then later, when you want to display image
ImageLoader.getInstance().displayImage(pumpModelList.get(position).getAvailable(), ivIcon); // Default options will be used
tvPump.setText(pumpModelList.get(position).getPump());
return convertView;
}
}
Now I want to create an onclick listener for my list view, which can be used to open another activity, and show the Description of pumps in TextView.
In your activity, where you defined your listview
you can write
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
ItemClicked item = adapter.getItemAtPosition(position);
Intent intent = new Intent(Activity.this,destinationActivity.class);
//based on item add info to intent
startActivity(intent);
}
});
public ItemClicked getItem(int position){
return items.get(position);
}
ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
In your activity, where you defined your listview
you write
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
ItemClicked item = adapter.getItemAtPosition(position);
Intent intent = new Intent(Activity.this,destinationActivity.class);
//based on item add info to intent
startActivity(intent);
}
});
in your adapter's getItem you write
public ItemClicked getItem(int position){
return items.get(position);
}
Implement an OnItemClickListener (Best place to implement is in your adapter) & on your ListView object setOnItemClickListener(yourItemClickListener);
Refs :
https://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html
https://developer.android.com/reference/android/widget/AdapterView.html#setOnItemClickListener(android.widget.AdapterView.OnItemClickListener)
Hi I need to store items in custom adapter but I got issue while creating custom adapter. Please help me to resolve.
private class Cast extends AsyncTask<Object, Void, ArrayList<String>> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog=new ProgressDialog(Detailed_View.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
private final String KeY = "";
private static final String DEBUG_TAG = "TM";
#Override
protected ArrayList<String> doInBackground(Object... params) {
try {
return getCast();
} catch (IOException e) {
return null;
}
}
#Override
protected void onPostExecute(ArrayList<String> results_Cast) {
updateListOfCast(results_Cast);
dialog.cancel();
};
public ArrayList<String> getCast() throws IOException {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("https://themovie/3/movie/" + id
+ "/credit");
stringBuilder.append("?key=" + key);
URL url = new URL(stringBuilder.toString());
// Log.d("urlstring",stringBuilder.toString() );
InputStream stream = null;
try {
// Establish a connection
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.addRequestProperty("Accept", "application/json"); // Required
// to
// get
// TMDB
// to
// play
// nicely.
conn.setDoInput(true);
conn.connect();
int responseCode = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response code is: " + responseCode + " "
+ conn.getResponseMessage());
stream = conn.getInputStream();
return parseCast(stringify(stream));
} finally {
if (stream != null) {
stream.close();
}
}
}
private ArrayList<String> parseCast(String result) {
String streamAsString = result;
ArrayList<String> results_Cast = new ArrayList<String>();
try {
JSONObject jsonObject = new JSONObject(streamAsString);
JSONArray array = (JSONArray) jsonObject.get("cast");
Log.d("array view", array.toString());
for (int i = 0; i < array.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonMovieObject = array.getJSONObject(i);
results_Cast.add(jsonMovieObject.getString("name"));
ids=jsonMovieObject.getString("id");
results_Cast.add(jsonMovieObject.getString("character"));
}
} catch (JSONException e) {
Log.d("e", e.toString());
Log.d(DEBUG_TAG, "Error parsing JSON. String was: "
+ streamAsString);
}
// Log.d("resulted", results_Cast.toString());
return results_Cast;
}
public String stringify(InputStream stream) throws IOException,
UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(reader);
return bufferedReader.readLine();
}
}
// displays cast
public void updateListOfCast(ArrayList<String> result) {
ListView listView = (ListView) findViewById(R.id.cast_details);
//Log.d("updateViewWithResults", result.toString());
// Add results to listView.
listView.setAdapter(adapter);
Helper.getListViewSize(listView);
gridAdapter = new GridAdapter(this, R.layout.test_row, result); // here I have issue.
listView.setAdapter(gridAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long idss) {
// TODO Auto-generated method stub
String name = (String) parent.getItemAtPosition(position);
Toast.makeText(Detailed_View.this, name+"Id"+ids, Toast.LENGTH_SHORT)
.show();
}
});
public class GridAdapter extends BaseAdapter {
public GridAdapter(Activity a, int resource, ArrayList<String> result) { // here it displays error as The blank final field itemLists may not have been initialized
layoutInflater = (LayoutInflater) a
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
results=result;
activity=a;
loader=new ImageLoader(a.getApplicationContext());
}
}
How to get items of name, id and character to display in custom adapter?
You have to overide all methods..
Example
public class CustomBaseAdapter extends BaseAdapter {
Context context;
List<RowItem> rowItems;
public CustomBaseAdapter(Context context, List<RowItem> items) {
this.context = context;
this.rowItems = items;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
RowItem rowItem = (RowItem) getItem(position);
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
return convertView;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
}
I have an async task that loads a list view of items. I am currently trying to set the onClick to load a new fragment with an "id" that is being retrieved from the list item that is clicked. I have no errors in my code that the Android Studio shows me.
When I run the app and click on the item in the list view I get this FC:
02-13 19:49:56.813 20334-20334/com.beerportfolio.beerportfoliopro E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.beerportfolio.beerportfoliopro.ReadJSONResult$1.onItemClick(ReadJSONResult.java:140)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1237)
at android.widget.ListView.performItemClick(ListView.java:4555)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3037)
at android.widget.AbsListView$1.run(AbsListView.java:3724)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5789)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:843)
at dalvik.system.NativeStart.main(Native Method)
02-13 19:50:42.112 20864-20870/? E/jdwp﹕ Failed sending reply to debugger: Broken pipe
line 140 in ReadJSONResult is:
listenerBeer.onArticleSelected(idToSend);
That line is part of this whole onClick:
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
BeerData beerInfo = beerList.get(arg2);
String idToSend = beerInfo.beerId;
//todo: launch beer fragment
listenerBeer.onArticleSelected(idToSend);
}
});
All the code for ReadJSONResult is:
public class ReadJSONResult extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public ReadJSONResult(Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
//code for on click
OnArticleSelectedListener listenerBeer;
public interface OnArticleSelectedListener{
public void onArticleSelected(String myString);
}
public void setOnArticleSelectedListener(OnArticleSelectedListener listener){
this.listenerBeer = listener;
}
//end code for onClick
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Searching Beer Cellar");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONObject json = new JSONObject(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(android.R.id.list);
//make array list for beer
final List<BeerData> beerList = new ArrayList<BeerData>();
//get json items
for(int i = 0; i < json.getJSONArray("data").length(); i++) {
String beerId = GetBeerDataFromJSON(i,"id", json);
String beerName = GetBeerDataFromJSON(i,"name", json);
String beerDescription = GetBeerDataFromJSON(i,"description" , json);
String beerAbv = GetBeerDataFromJSON(i,"abv" , json);
String beerIbu = GetBeerDataFromJSON(i,"ibu" , json);
String beerIcon = GetBeerIconsFromJSON(i, "icon",json );
String beerMediumIcon = GetBeerIconsFromJSON(i, "medium",json );
String beerLargeIcon = GetBeerIconsFromJSON(i, "large",json );
String beerGlass = GetBeerGlassFromJSON(i, json );
String beerStyle = GetBeerStyleFromJSON(i,"name", json );
String beerStyleDescription = GetBeerStyleFromJSON(i,"description", json );
String beerBreweryId = GetBeerBreweryInfoFromJSON(i, "id", json );
String beerBreweryName = GetBeerBreweryInfoFromJSON(i, "name", json );
String beerBreweryDescription = GetBeerBreweryInfoFromJSON(i, "description", json );
String beerBreweryWebsite = GetBeerBreweryInfoFromJSON(i, "website", json );
//get long and latt
String beerBreweryLat = GetBeerBreweryLocationJSON(i, "longitude", json );
String beerBreweryLong = GetBeerBreweryLocationJSON(i, "latitude", json );
String beerBreweryYear = GetBeerBreweryInfoFromJSON(i, "established", json );
String beerBreweryIcon = GetBeerBreweryIconsFromJSON(i,"large",json);
//create beer object
BeerData thisBeer = new BeerData(beerName, beerId, beerDescription, beerAbv, beerIbu, beerIcon,
beerMediumIcon,beerLargeIcon, beerGlass, beerStyle, beerStyleDescription, beerBreweryId, beerBreweryName,
beerBreweryDescription, beerBreweryYear, beerBreweryWebsite,beerBreweryIcon, beerBreweryLat, beerBreweryLong);
//add beer to list
beerList.add(thisBeer);
}
//update listview
BeerSearchAdapter adapter1 = new BeerSearchAdapter(c ,R.layout.listview_item_row, beerList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
BeerData beerInfo = beerList.get(arg2);
String idToSend = beerInfo.beerId;
//todo: launch beer fragment
listenerBeer.onArticleSelected(idToSend);
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
//todo: all the get functions go here
private String GetBeerDataFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get icons
private String GetBeerBreweryIconsFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getJSONObject("images").getString(whatIsTheKeyYouAreLookFor);;
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get icons
private String GetBeerIconsFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("labels").getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get style information
private String GetBeerStyleFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("style").getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get location data
private String GetBeerBreweryLocationJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getJSONArray("locations").getJSONObject(0).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get brewery information
//get style information
private String GetBeerBreweryInfoFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get glass
private String GetBeerGlassFromJSON(int position, JSONObject json ) {
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("glass").getString("name");
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
BeerSearchAdapter is:
public class BeerSearchAdapter extends ArrayAdapter<BeerData> {
Context context;
int layoutResourceId;
List<BeerData> data = null;
public BeerSearchAdapter(Context context, int layoutResourceId, List<BeerData> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
beerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new beerHolder();
holder.txtBrewery = (TextView)row.findViewById(R.id.beerBreweryNameList);
holder.txtTitle = (TextView)row.findViewById(R.id.beerNameList);
row.setTag(holder);
}
else
{
holder = (beerHolder)row.getTag();
}
BeerData beer = data.get(position);
holder.txtTitle.setText(beer.beerName);
holder.txtBrewery.setText(beer.beerBreweryName);
return row;
}
static class beerHolder
{
TextView txtBrewery;
TextView txtTitle;
}
}
My Search.java where the interface comes form is here:
public class Search extends Fragment implements SearchView.OnQueryTextListener, ReadJSONResult.OnArticleSelectedListener {
private ListView lv;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//set layout here
v = inflater.inflate(R.layout.activity_search, container, false);
setHasOptionsMenu(true);
getActivity().setTitle("Search");
//get user information
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
//todo: code body goes here
// Inflate the layout for this fragment
return v;
}
#Override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu, inflater);
Log.d("click", "inside the on create");
//inflater.inflate(R.menu.main, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search2).getActionView();
searchView.setIconified(false);
searchView.setOnQueryTextListener(this);
}
public boolean onQueryTextSubmit (String query) {
//toast query
//make json variables to fill
// url to make request
String url = "myURL";
try {
query = URLEncoder.encode(query, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String jsonUrl = url + query;
//todo: get json
new ReadJSONResult(getActivity()).execute(jsonUrl);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onArticleSelected(String b){
//code to execute on click
Fragment Fragment_one;
FragmentManager man= getFragmentManager();
FragmentTransaction tran = man.beginTransaction();
//todo: set to beer fragment
Fragment_one = new StylePage2();
final Bundle bundle = new Bundle();
bundle.putString("beerIDSent", b);
Fragment_one.setArguments(bundle);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
Let me know if you need any other code, I am stomped on this and could use a second pair of eyes. Thanks.
From the error message, it is obvious that listenerBeer reference is null.
I see this code:
public void setOnArticleSelectedListener(OnArticleSelectedListener listener){
this.listenerBeer = listener;
}
But I don't see any code that calls it. Unless there is code you have not included that sets the listenerBeer reference, that would explain why it is null.
Somewhere in your code you will have to do something like this:
. . .
setOnArticleSelectedListener(new OnArticleSelectedListener() {
public void onArticleSelected(String myArticle) {
// Do something here....
}
});
. . .
HTH
You have got it correct that at the below call to onArticleSelected your listenerBeer is null.
listenerBeer.onArticleSelected(idToSend);
The only possible reason behind it is that it is not initiallized before making this call. As visible from your code the only place you are doing the initialization is in the below method.
public void setOnArticleSelectedListener(OnArticleSelectedListener listener){
this.listenerBeer = listener;
}
But, I cannot see any implementation of this. Can you do a null check before listenerBeer.onArticleSelected(idToSend); and verify if listenerBeer is initialized like
if (null != listenerBeer){
listenerBeer.onArticleSelected(idToSend);
}else{
Log.d("Null Check", "ListenereBeer is " + String.valueOf(listenerBeer));
}