Custom Listview force closing - android

I have created a custom list view which keeps force closing and I am having trouble figuring out why. I think I may have not named one of the view correctly since I was modeling this view off another. But I cant find my mistake yet.
Here is my force close error:
08-30 22:04:44.073 4011-4011/com.beerportfolio.beerportfoliopro E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.beerportfoliopro.BreweryLocationInfoAdapter.getView(BreweryLocationInfoAdapter.java:50)
at android.widget.AbsListView.obtainView(AbsListView.java:2410)
at android.widget.ListView.makeAndAddView(ListView.java:1963)
at android.widget.ListView.fillDown(ListView.java:815)
at android.widget.ListView.fillFromTop(ListView.java:876)
at android.widget.ListView.layoutChildren(ListView.java:1813)
at android.widget.AbsListView.onLayout(AbsListView.java:2238)
at android.view.View.layout(View.java:13900)
at android.view.ViewGroup.layout(ViewGroup.java:4391)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
at android.view.View.layout(View.java:13900)
at android.view.ViewGroup.layout(ViewGroup.java:4391)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:13900)
at android.view.ViewGroup.layout(ViewGroup.java:4391)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1649)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1507)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1420)
at android.view.View.layout(View.java:13900)
at android.view.ViewGroup.layout(ViewGroup.java:4391)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:13900)
at android.view.ViewGroup.layout(ViewGroup.java:4391)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2183)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1984)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1221)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4710)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:746)
at android.view.Choreographer.doCallbacks(Choreographer.java:572)
at android.view.Choreographer.doFrame(Choreographer.java:538)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:731)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5536)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1074)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:841)
at dalvik.system.NativeStart.main(Native Method)
My BreweryLocationInfoAdapter code:
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RatingBar;
import android.widget.TextView;
import com.beerportfolio.beerportfoliopro.R;
public class BreweryLocationInfoAdapter extends ArrayAdapter<BreweryLocationData>{
Context context;
int layoutResourceId;
List<BreweryLocationData> data = null;
public BreweryLocationInfoAdapter(Context context, int layoutResourceId, List<BreweryLocationData> 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;
breweryHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new breweryHolder();
holder.txtBrewery = (TextView)row.findViewById(R.id.beerNameList);
holder.txtDistance = (TextView)row.findViewById(R.id.beerBreweryNameList);
row.setTag(holder);
}
else
{
holder = (breweryHolder)row.getTag();
}
BreweryLocationData beer = data.get(position);
holder.txtBrewery.setText(beer.brewery);
holder.txtBrewery.setText(beer.distance);
return row;
}
static class breweryHolder
{
TextView txtBrewery;
TextView txtDistance;
}
}
GetNearbyBreweries code:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.beerportfolio.beerportfoliopro.R;
public class GetNearbyBreweries extends AsyncTask
<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public GetNearbyBreweries (Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Locating Breweries");
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(R.id.topTasteBeers);
//make array list for beer
final List<BreweryLocationData> tasteList = new ArrayList<BreweryLocationData>();
for(int i = 0; i < json.getJSONArray("data").length(); i++) {
String brewery = json.getJSONArray("data").getJSONObject(i).getJSONObject("brewery").getString("name");
String id = json.getJSONArray("data").getJSONObject(i).getJSONObject("brewery").getString("id");
String latitude = json.getJSONArray("data").getJSONObject(i).getString("latitude");
String longitude = json.getJSONArray("data").getJSONObject(i).getString("longitude");
String distance = json.getJSONArray("data").getJSONObject(i).getString("distance");
Toast.makeText(c, "Brewery: " + brewery, Toast.LENGTH_SHORT).show();
int count = i + 1;
//create object
BreweryLocationData tempLocation = new BreweryLocationData(brewery, id, longitude , latitude,distance);
//add to arraylist
tasteList.add(tempLocation);
//add items to listview
BreweryLocationInfoAdapter adapter1 = new BreweryLocationInfoAdapter(c ,R.layout.toptaste_layout, tasteList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
ShortBeerInfo o=(ShortBeerInfo)arg0.getItemAtPosition(arg2);
String tempID = o.id;
String tempBrewID = o.brewery;
Toast toast = Toast.makeText(c, tempID, Toast.LENGTH_SHORT);
toast.show();
//get beer details from id
Intent myIntent = new Intent(c, BeerPage2.class);
myIntent.putExtra("id", tempID);
myIntent.putExtra("breweryID", tempBrewID);
c.startActivity(myIntent);
}
});
}
}
catch(Exception e){
}
Dialog.dismiss();
}
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();
}
}

I think for some reason row isn't getting created.
Can you double check by debugging that row != null by the time you arrive set row.setTag(holder).
I can only guess that 1. maybe the context you are using to get your inflater isn't correct, either way I prefer to use the following method
LayoutInflater.from(context).inflate(R.layout.cell, viewGroup, false);
Or, your resourceID is not right..

You have not written getCount method in your custom adapter:
public int getCount() {
return //Something here
}

Row 50 seems to be
holder.txtBrewery.setText(beer.brewery);
So either the TextView which should have id R.id.beerNameList has another id or beer.brewery is null.
You can solve these type of issues quickly if you use the debugger. Just put a breakpoint at the offending line, run the debugger and it will pause at the given line. You can then see exactly which object is null, allowing you to fix the problem in no time.

Don't hold the data in your custom adapter. Always use
BreweryLocationData beer = getItem(position);
to obtain the object that should be represented by the adapter. This way you can avoid issues with the data being modified outside of your adapter.

Related

Add new item on top in custom adapter [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am not able to Add new item on top in custom adapter in Android. Post CommentPageActivity Class and MyAdapter Class for better understanding.
CommentPageActivity class populate ListView and on onclick action, we are calling MyAdapter
package com.sk.comment;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.sk.bhangarwaala.R;
import com.sk.variable.Globals;
import com.sk.variable.Variable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.ActionBar;
import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class CommentPageActivity extends Activity {
MyAdapter listAdapter;
ListView commentPageLvCommentsList;
TextView commentPageTvSkid,commentPageTvLoader;
EditText commentPageEtEnterComments;
LinearLayout commentPageLlCommentsContainer;
Button commentPageBtSubmit;
List<CommentsFeedObj> data;
String key,json;
boolean isTaskCompleted,isError;
LoadComments task= new LoadComments();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment_page);
ActionBar actionBar = getActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.my_red)));
// Enabling Back navigation on Action Bar icon
actionBar.setDisplayHomeAsUpEnabled(true);
key=getIntent().getExtras().getString("skid");
System.out.println("CommentPageActivity.onCreate() | key | "+key);
data = new ArrayList<CommentsFeedObj>();
Display d = ((Activity) this).getWindowManager()
.getDefaultDisplay();
int h = d.getHeight();
int w = d.getWidth();
System.out.println("CommentPageActivity.onCreate()|h|"+h+" |w|"+w);
DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics();
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
System.out.println("CommentPageActivity.onCreate() |height| "+height);
if(w>h){
height=height*65/100;
}else{
height=height*75/100;
}
System.out.println("CommentPageActivity.onCreate() |height| "+height);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height);
commentPageLlCommentsContainer = (LinearLayout)findViewById(R.id.commentPageLlCommentsContainer);
commentPageLlCommentsContainer.setLayoutParams(lp);
commentPageTvSkid = (TextView)findViewById(R.id.commentPageTvSkid);
commentPageTvSkid.setVisibility(View.GONE);
commentPageEtEnterComments = (EditText)findViewById(R.id.commentPageEtEnterComments);
System.out.println("CommentPageActivity.onCreate() width | | "+width);
System.out.println("CommentPageActivity.onCreate() | 80/width*100 | "+width*80/100);
commentPageEtEnterComments.setLayoutParams(new LinearLayout.LayoutParams(width*80/100, LinearLayout.LayoutParams.WRAP_CONTENT));
commentPageLvCommentsList = (ListView)findViewById(R.id.commentPageLvCommentsList);
commentPageTvLoader=(TextView)findViewById(R.id.commentPageTvLoader);
initLoadComments();
commentPageBtSubmit = (Button)findViewById(R.id.commentPageBtSubmit);
//commentPageBtSubmit.setBackgroundResource(R.drawable.ic_email_send);
commentPageBtSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
performAddCommentsOperation();
}
});
}
void initLoadComments(){
task.execute();
}
void loadCommentsView(){
try {
if(error)){
CommentsFeedObj obj = new CommentsFeedObj();
obj.setUserProfileImg("");
obj.setUserName("");
obj.setUserMsg("");
obj.setTimestamp("");
obj.setSkid(key);
obj.setResponseStatus("error");
data.add(obj);
}else{
parseJson(new JSONObject(json));
}
listAdapter= new MyAdapter(this, data);
commentPageLvCommentsList.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
void parseJson(JSONObject response){
System.out.println("CommentPageActivity.parseJson()");
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
CommentsFeedObj obj = new CommentsFeedObj();
obj.setUserProfileImg(feedObj.getString("userProfileImg"));
obj.setUserName(feedObj.getString("userName"));
obj.setUserMsg(feedObj.getString("userMsg"));
obj.setTimestamp(feedObj.getString("timestamp"));
obj.setSkid(feedObj.getString("skid"));
obj.setLogonUserId(feedObj.getString("logonUserId"));
obj.setLogonUserName(feedObj.getString("logonUserName"));
obj.setLogonUserMobileNumber(feedObj.getString("logonUserMobileNumber"));
obj.setUserLocation(feedObj.getString("userLocation"));
obj.setTs_long(Long.parseLong(feedObj.getString("ts_long")));
obj.setResponseStatus("success");
data.add(obj);
}
System.out.println("CommentPageActivity.parseJson() | "+data);
} catch (JSONException e) {
e.printStackTrace();
}
}
private class LoadComments extends AsyncTask<String, Void, String>{
#Override
protected void onPreExecute(){
super.onPreExecute();
commentPageTvLoader.setVisibility(View.VISIBLE);
commentPageTvLoader.setText("Loading...");
}
#Override
protected void onPostExecute(String result){
int i=0;
while(true){
i=i+1;
if(i==4){json=(Globals._N_LOADING_ERROR_COMMENTS); break;}
if(isTaskCompleted && (json==null || json.length()<1)){
task.execute(Variable.WS_URL_LOAD_COMMENTS);
isTaskCompleted=false;
}else if(isTaskCompleted&& (json!=null || json.length()>0))
{/*prgDialog.dismiss();*/break;}
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
}
}, 200);
}// while
loadCommentsView();
commentPageTvLoader.setVisibility(View.GONE);
}
#Override
protected String doInBackground(String... params) {
System.out.println("CommentPageActivity.LoadComments.doInBackground()");
StringBuffer response=new StringBuffer("");
List<NameValuePair> nameVauePairs=new ArrayList<NameValuePair>(1);
InputStream is=null;
nameVauePairs.add(new BasicNameValuePair("skid", key));
try {
HttpPost httppost = new HttpPost(Variable.WS_URL_LOAD_COMMENTS);
HttpClient httpclient = new DefaultHttpClient();
httppost.setEntity(new UrlEncodedFormEntity(nameVauePairs));
HttpResponse response1 = httpclient.execute(httppost);
StatusLine statusLine= response1.getStatusLine();
System.out.println("CommentPageActivity.LoadComments.doInBackground() | statusLine | "+statusLine);
{
HttpEntity entity =response1.getEntity();
is=entity.getContent();
InputStreamReader in =new InputStreamReader(is);
BufferedReader br = new BufferedReader(in);
String info="";
String nl=System.getProperty("line.separator");
while((info=br.readLine())!=null){
response.append(info.toString()+nl);
}
System.out.println("CommentPageActivity.LoadComments.doInBackground() | response.toString() | "+response.toString());
json=response.toString();
isTaskCompleted=true;
isError=false;
br.close();
}
} catch (UnsupportedEncodingException e) {
isTaskCompleted=true;
isError=true;
e.printStackTrace();
}catch (ClientProtocolException e) {
isTaskCompleted=true;
isError=true;
e.printStackTrace();
} catch (IOException e) {
isTaskCompleted=true;
isError=true;
e.printStackTrace();
}
return "";
}// doBackGroud
}// SaveComment
void performAddCommentsOperation(){
System.out.println("CommentPageActivity.performAddCommentsOperation()");
String msg=commentPageEtEnterComments.getText()+"".trim();
String logonUserName=Globals.getInstance().getLogonUserName();
String logonUserMobileNumber=Globals.getInstance().getLogonUserMobileNumber();
String logonUserId=Globals.getInstance().getLogonUserId();
if(msg==null || msg.length()<1){
Toast.makeText(this, "Please enter comments", Toast.LENGTH_SHORT).show();
commentPageEtEnterComments.setText("");
return;
}
commentPageEtEnterComments.setText("");
if(logonUserName!=null && logonUserName.trim().length()>0){
}else{
logonUserName="unknown";
}
if(msg!=null && msg.trim().length()>0){
}else{
msg="nice shop";
}
CommentsFeedObj obj = new CommentsFeedObj();
obj.setUserProfileImg("");
obj.setUserName(logonUserName);
obj.setUserMsg(msg);
obj.setTimestamp(""+new Date());
obj.setSkid(key);
obj.setLogonUserId(logonUserId);
obj.setLogonUserName(logonUserName);
obj.setLogonUserMobileNumber(logonUserMobileNumber);
obj.setUserLocation("");
obj.setTs_long(System.currentTimeMillis());
data.add(obj);
listAdapter= new MyAdapter(this, data);
//commentPageLvCommentsList.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
performSaveCommentOperation(obj);
}
void performSaveCommentOperation(CommentsFeedObj obj){
new SaveComment().execute(obj);
}
private class SaveComment extends AsyncTask<CommentsFeedObj, Void, String>{
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected void onPostExecute(String result){
}
#Override
protected String doInBackground(CommentsFeedObj... params) {
System.out.println("CommentPageActivity.SaveComment.doInBackground()");
StringBuffer response=new StringBuffer("");
List<NameValuePair> nameVauePairs=new ArrayList<NameValuePair>(1);
InputStream is=null;
CommentsFeedObj obj=params[0];
nameVauePairs.add(new BasicNameValuePair("ts_long", obj.getTs_long()+""));
nameVauePairs.add(new BasicNameValuePair("skid", obj.getSkid()));
nameVauePairs.add(new BasicNameValuePair("userName", obj.getUserName()));
nameVauePairs.add(new BasicNameValuePair("timestamp", obj.getTimestamp()));
nameVauePairs.add(new BasicNameValuePair("userProfileImg", obj.getUserProfileImg()));
nameVauePairs.add(new BasicNameValuePair("userMsg", obj.getUserMsg()));
nameVauePairs.add(new BasicNameValuePair("host_name", obj.getHost_name()));
nameVauePairs.add(new BasicNameValuePair("gallery_name", obj.getGallery_name()));
nameVauePairs.add(new BasicNameValuePair("logonUserName", obj.getLogonUserName()));
nameVauePairs.add(new BasicNameValuePair("logonUserMobileNumber", obj.getLogonUserMobileNumber()));
nameVauePairs.add(new BasicNameValuePair("logonUserId", obj.getLogonUserId()));
nameVauePairs.add(new BasicNameValuePair("userLocation", obj.getUserLocation()));
try {
HttpPost httppost = new HttpPost(Variable.WS_URL_SAVE_COMMENTS);
HttpClient httpclient = new DefaultHttpClient();
httppost.setEntity(new UrlEncodedFormEntity(nameVauePairs));
HttpResponse response1 = httpclient.execute(httppost);
StatusLine statusLine= response1.getStatusLine();
System.out.println("CommentPageActivity.SaveComment.doInBackground() | statusLine | "+statusLine);
{
HttpEntity entity =response1.getEntity();
is=entity.getContent();
InputStreamReader in =new InputStreamReader(is);
BufferedReader br = new BufferedReader(in);
String info="";
String nl=System.getProperty("line.separator");
while((info=br.readLine())!=null){
response.append(info.toString()+nl);
}
System.out.println("CommentPageActivity.SaveComment.doInBackground() | response.toString() | "+response.toString());
br.close();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}// doBackGroud
}// SaveComment
/* #Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_comment_page, menu);
return true;
}*/
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
finish();
return true;
}
}
----------------- MyAdapter Class
package com.sk.comment;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.sk.bhangarwaala.R;
import com.sk.faq.AppController;
import com.sk.variable.Variable;
public class MyAdapter extends BaseAdapter {
private Context activity;
//private LayoutInflater inflater;
private List<CommentsFeedObj> feedItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private static int counter;
/*public MyAdapter(Activity activity, List<CommentsFeedObj> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
}*/
public MyAdapter(Context applicationContext, List<CommentsFeedObj> data) {
// TODO Auto-generated constructor stub
this.activity = applicationContext;
this.feedItems = data;
//inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
if(feedItems!=null)
return feedItems.size();
return 0;
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("DefaultLocale")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
CompleteListViewHolder viewHolder;
View v = convertView;
counter=counter+1;
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
if (convertView == null){
LayoutInflater li = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.comment_page_list_comments, null);
viewHolder = new CompleteListViewHolder(v);
v.setTag(viewHolder);
}else{
viewHolder = (CompleteListViewHolder) v.getTag();
}
CommentsFeedObj item = feedItems.get(position);
System.out.println("MyAdapter.getView() | item | "+item.toString());
// sk id
viewHolder.commentPageTvSkid.setText(item.getSkid());
viewHolder.commentPageTvSkid.setVisibility(View.GONE);
// user profile img
if (item.getUserProfileImg()!=null && !item.getUserProfileImg().equalsIgnoreCase("null") && item.getUserProfileImg().length() >0){ // 1
String img=item.getHost_name()+"/"+item.getGallery_name()+"/"+item.getUserProfileImg();
System.out.println("MyAdapter.getView() | img | "+img);
viewHolder.commentPageNivProfileImg.setImageUrl(img, imageLoader);
}else{
System.out.println("MyAdapter.getView() | DEFAULT_PROFILE_IMG | "+imageLoader);
viewHolder.commentPageNivProfileImg.setImageUrl(Variable.DEFAULT_PROFILE_IMG, imageLoader);// 1
}
// user name
viewHolder.commentPageTvUserName.setText(item.getUserName().toUpperCase());
// time stamp
viewHolder.commentPageTvTimestamp.setText(item.getTimestamp());
// user msg
if(item.getUserMsg()!=null){
viewHolder.commentPageTvUserMsg.setText(item.getUserMsg());
}else{
viewHolder.commentPageTvUserMsg.setVisibility(View.GONE);
}
return v;
}
}//MainClass
class CompleteListViewHolder {
//http://androidadapternotifiydatasetchanged.blogspot.in/
TextView commentPageTvUserName,commentPageTvTimestamp,commentPageTvUserMsg ,commentPageTvSkid ;
NetworkImageView commentPageNivProfileImg ;
public CompleteListViewHolder(View convertView) {
commentPageTvUserName = (TextView) convertView.findViewById(R.id.commentPageListCommentsTvUserName);
commentPageTvTimestamp = (TextView) convertView.findViewById(R.id.commentPageListCommentsTvTimestamp);
commentPageTvUserMsg = (TextView) convertView.findViewById(R.id.commentPageListCommentsTvUserMsg);
commentPageTvSkid = (TextView) convertView.findViewById(R.id.commentPageListCommentsTvSkid);
commentPageNivProfileImg = (NetworkImageView) convertView.findViewById(R.id.commentPageListCommentsNivProfileImg);
}
}
When you add new commnent, always add this comment at the beginning of your data. Then refresh you ListView
data.add(0, commnent);
listAdapter.notifyDataSetChanged();
You can you this before init new Adapter:
data.add(0, value);
This will add new value in the begin of your list.
Finally done, I have used this data.add(0,obj) instead of data.add(obj) on onClick Action.
void onClickCommentButton(){
data.add(0,obj);
listAdapter= new MyAdapter(this, data);
commentPageLvCommentsList.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
You will be able to do by adding header at top. There should be methods with adapterView or list. I had done last year . It allows only one header item per list though I remember.

I want to fetch image from mysql to android listview using php json...?

> This is my MainActivity.java That receives all json data from the php file and converts into string format and print it in listview using string array but i have problem with bitmap image array
I want to add multiple items in listview like textview and image i dont have problem with textview it displays properly but with image it is not done
package com.demo.php.listview;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.util.Base64;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnItemClickListener {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> al1 = new ArrayList<String>();
ArrayList<String> al2 = new ArrayList<String>();
ArrayList<String> al3=new ArrayList<String>();
String targetmonth;
String targetyear;
String targetamount;
String Dphoto;
// int responseCode;
//int listItemCount=0;
ListView listview ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(Color.WHITE);
setTitleColor(Color.rgb(0x74, 0, 0x37));
setTitle("Doctor's List");
requestWindowFeature(Window.FEATURE_RIGHT_ICON);
setContentView(R.layout.main);
listview = (ListView) findViewById(R.id.listView1);
listview.setOnItemClickListener(this);
new LoadData().execute();
}
private class LoadData extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
// can use UI thread here
protected void onPreExecute() {
this.progressDialog = ProgressDialog.show(MainActivity.this, ""," Loading...");
}
#Override
protected void onPostExecute(final Void unused) {
try{
listview.setAdapter(new DataAdapter(MainActivity.this,
al.toArray(new String[al.size()]),
al1.toArray(new String[al1.size()]),
al2.toArray(new String[al2.size()]),
al3.toArray(new Bitmap[al3.size()])));
this.progressDialog.dismiss();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// HTTP post
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
try{
HttpPost httppost = new HttpPost("http://10.0.2.2/android/test.php");
StringEntity se = new StringEntity("envelope",HTTP.UTF_8);
httppost.setEntity(se);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 3000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
//buffered reader
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 80);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
try{
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
targetamount=json_data.getString("DName");
targetmonth=json_data.getString("Dspl");
targetyear = json_data.getString("Dedu");
Dphoto = json_data.getString("Dphoto");
al.add(targetmonth);
al1.add(targetyear);
al2.add(targetamount);
al3.add(Dphoto);
//listItemCount=al2.size();
}
}
catch(JSONException e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
} catch (ParseException e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
catch (Exception e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
return null;
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(this, NextItem.class);
startActivity(intent);
}
}
>This is my DataAdapter
I am not getting the image in Listview I am little bit confuse about the image bitmap array please helps with that bitmap
package com.demo.php.listview;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.MediaStore.Images;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class DataAdapter extends BaseAdapter {
Context mContext;
private LayoutInflater mInflater;
String targetmonth;
String targetyear;
String targetamount;
//Bitmap Dphoto1;
String[] month;
String[] year;
String[] amount;
String[] Dphoto1;
Bitmap[] Dphoto2;
private String src;
public DataAdapter(Context c, String[] month, String[] year, String[] amount,Bitmap[] Dphoto2) {
//this.sta = sta;
Bitmap[] = (Bitmap[]) getBitmapFromURL(Dphoto2);
this.month = month;
this.year = year;
this.amount = amount;
this.Dphoto2=Dphoto2;
mContext = c;
mInflater = LayoutInflater.from(c);
}
public int getCount() {
return month.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.doctor, parent, false);
holder = new ViewHolder();
holder.month = (TextView) convertView
.findViewById(R.id.Dname);
holder.year = (TextView) convertView.findViewById(R.id.Dspl);
holder.amount = (TextView) convertView
.findViewById(R.id.Dedu);
holder.Dphoto2=(ImageView)convertView.findViewById(R.id.Dphoto2);
if (position == 0) {
convertView.setTag(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
holder.month.setText(month[position]);
holder.year.setText(year[position]);
holder.amount.setText(amount[position]);
holder.Dphoto2.setImageBitmap(Dphoto2[position]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return convertView;
}
private Object getBitmapFromURL(Bitmap[] dphoto2) {
// TODO Auto-generated method stub
try{
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
static class ViewHolder {
public ImageView Dphoto2;
public TextView Dphoto1;
public ImageView Dphoto;
TextView month;
TextView year, amount;
}
public class ImageLoadTask {
public void execute(String dphoto1) {
// TODO Auto-generated method stub
}
}}
The JSON text will deliver a base64 encoded bitmap or jpg.
ArrayList<String> al3=new ArrayList<String>();
change that to:
ArrayList<Bitmap> al3=new ArrayList<Bitmap>();
And in the loop change:
al3.add(Dphoto);
to:
Bitmap bitmap = decodeBitmapFromBase64 (Dphoto);
al3.add(bitmap);
Remove:
Bitmap[] = (Bitmap[]) getBitmapFromURL(Dphoto2); // does not even compile!
You have to implement a function decodeBitmapFromBase64(). You can find code for it on this site.
Remove all Toast()s from doInBackground. They are not allowed there. Put them in onPostExecute instead.

Copy selected row data when click on row in listview and value send to new activity for display as textview

Hiiii I want when i should click the row data , it seems to copy the value of row and pass to another activity for display as textview. I am taking data by single row values from table using mysql. A "Hope of Help" will be appreciated from your side PLEASE !!
//MainActivity.java
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.widget.TextView;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
/*
* #author Firzan Ghulam
*/
public class MainActivity extends Activity{
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<String> al = new ArrayList<String>();
String targetmonth;
int responseCode;
int listItemCount=0;
ListView listview ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listview = (ListView) findViewById(R.id.listView1);
new LoadData().execute();
// listening to single list item on click
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("product", product);
startActivity(i);
}
});
}
private class LoadData extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
// can use UI thread here
protected void onPreExecute() {
this.progressDialog = ProgressDialog.show(MainActivity.this, ""," Can you just see your roof...");
}
#Override
protected void onPostExecute(final Void unused) {
try{
listview.setAdapter(new DataAdapter(MainActivity.this,al.toArray(new String[al.size()])));
this.progressDialog.dismiss();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// HTTP post
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
try{
HttpPost httppost = new HttpPost("http://palaknehazz.com/app/ap.php");
StringEntity se = new StringEntity("envelope",HTTP.UTF_8);
httppost.setEntity(se);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 3000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
//buffered reader
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 80);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
System.out.println("Magu data aagaya"+result);
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
try{
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
//targetamount=json_data.getString("targetamount");
targetmonth=json_data.getString("targetmonth");
//targetyear = json_data.getString("targetyear");
al.add(targetmonth);
//al1.add(targetyear);
//al2.add(targetamount);
//listItemCount=al2.size();
}
}
catch(JSONException e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
} catch (ParseException e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
catch (Exception e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
return null;
}
}
}
//Data Adapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class DataAdapter extends BaseAdapter {
Context mContext;
private LayoutInflater mInflater;
String targetmonth;
String[] month;
public DataAdapter(Context c, String[] month) {
this.month = month;
mContext = c;
mInflater = LayoutInflater.from(c);
}
public int getCount() {
return month.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.customgrid, parent, false);
holder = new ViewHolder();
holder.month = (TextView) convertView
.findViewById(R.id.targetmonth);
if (position == 0) {
convertView.setTag(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
holder.month.setText(month[position]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return convertView;
}
static class ViewHolder {
TextView month;
}
}
//SingleListItem
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.meter);
TextView txtProduct = (TextView) findViewById(R.id.product_label);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("product");
// displaying selected product name
txtProduct.setText(product);
}
}
//Logcat error
05-14 22:48:02.644: D/dalvikvm(461): GC_CONCURRENT freed 56K, 2% free 14428K/14663K, paused 8ms+6ms
05-14 22:48:03.051: D/gralloc_goldfish(461): Emulator without GPU emulation detected.
05-14 22:48:05.121: I/System.out(461): Magu data aagaya[{"id":"1","targetmonth":"Karan is a intelligegnt guy if you know what i mean haha frieds plays very important role i TV serial life i believe hahaha i mean who guess for being myself"},{"id":"2","targetmonth":"He's the unpredictable foolish man you are looking forward for seriously"},{"id":"3","targetmonth":"Same here you are looking"}]
05-14 22:48:08.294: D/AndroidRuntime(461): Shutting down VM
05-14 22:48:08.294: W/dalvikvm(461): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
05-14 22:48:08.341: E/AndroidRuntime(461): FATAL EXCEPTION: main
05-14 22:48:08.341: E/AndroidRuntime(461): java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView
05-14 22:48:08.341: E/AndroidRuntime(461): at com.demo.php.listview.MainActivity$LoadData$1.onItemClick(MainActivity.java:94)
05-14 22:48:08.341: E/AndroidRuntime(461): at android.widget.AdapterView.performItemClick(AdapterView.java:292)
05-14 22:48:08.341: E/AndroidRuntime(461): at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
05-14 22:48:08.341: E/AndroidRuntime(461): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
05-14 22:48:08.341: E/AndroidRuntime(461): at android.widget.AbsListView$1.run(AbsListView.java:3168)
05-14 22:48:08.341: E/AndroidRuntime(461): at android.os.Handler.handleCallback(Handler.java:605)
05-14 22:48:08.341: E/AndroidRuntime(461): at android.os.Handler.dispatchMessage(Handler.java:92)
05-14 22:48:08.341: E/AndroidRuntime(461): at android.os.Looper.loop(Looper.java:137)
05-14 22:48:08.341: E/AndroidRuntime(461): at android.app.ActivityThread.main(ActivityThread.java:4340)
05-14 22:48:08.341: E/AndroidRuntime(461): at java.lang.reflect.Method.invokeNative(Native Method)
05-14 22:48:08.341: E/AndroidRuntime(461): at java.lang.reflect.Method.invoke(Method.java:511)
05-14 22:48:08.341: E/AndroidRuntime(461): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-14 22:48:08.341: E/AndroidRuntime(461): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-14 22:48:08.341: E/AndroidRuntime(461): at dalvik.system.NativeStart.main(Native Method)
in your main Activity change
// selected item
String product = ((TextView) view).getText().toString();
by
// selected item
String product = ((TextView) view.findViewById(R.id.targetmonth)).getText().toString();

java.lang.NullPointerException in getting data to ListView in Android

Hie Friends
I have one ListView which displays image data from JSON parser for that I use Custom Base Adapter.
But I got following exception.
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.ecard.ECard_main$AsycLove.onPostExecute(ECard_main.java:193)
at com.example.ecard.ECard_main$AsycLove.onPostExecute(ECard_main.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:602)
at android.os.AsyncTask.access$600(AsyncTask.java:156)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
My Code Is:
package com.example.ecard;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import com.loopj.android.image.SmartImageView;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ECard_main extends Activity
{
String catagories;
String anim_id,album_id,anim_name,anim_thumb,anim_url;
TextView title;
SmartImageView image;
ListView hlv;
ArrayList<HashMap<String, String>> albumList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.ecard_main);
Intent i=getIntent();
catagories=i.getExtras().getString("Catagories");
title=(TextView)findViewById(R.id.tv_main_title);
image=(SmartImageView)findViewById(R.id.IV_image);
title.setText(catagories);
//hlv = getListView();
hlv = (ListView) findViewById(android.R.id.list);
albumList = new ArrayList<HashMap<String, String>>();
new AsycLove().execute();
}
class AsycLove extends AsyncTask<String, String, String>
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(ECard_main.this);
progressDialog.setTitle("Loading");
progressDialog.setMessage("Please wait");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected String doInBackground(String... aurl)
{
try
{
HttpPost postMethod = new HttpPost("http://demo1.idevtechnolabs.com/smartecard/love.php");
BufferedReader bufferedReader = null;
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
response = client.execute(postMethod);
final int statusCode = response.getStatusLine().getStatusCode();
Log.v("Album ::","Response:::--->"+response.toString());
Log.v("Album ::","Status Code:::--->"+statusCode);
bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer("");
String line = "";
String LineSeparator = System.getProperty("line.separator");
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line + LineSeparator);
}
bufferedReader.close();
//-------------CONVERT DATA TO JSON---------------------------------
try
{
String myjsonstring = stringBuffer.toString();
JSONArray jsonArray = new JSONArray(myjsonstring);
JSONObject jsonObj = null;
albumList.clear();
jsonObj = jsonArray.getJSONObject(0);
for(int i=0; i<jsonArray.length();i++)
{
jsonObj = jsonArray.getJSONObject(i);
anim_id = jsonObj.getString("animation_id");
album_id = jsonObj.getString("album_id");
anim_name = jsonObj.getString("animation_name");
anim_thumb= jsonObj.getString("animation_thumb");
anim_url = jsonObj.getString("animation_url");
anim_url=anim_url.replaceAll("\"","");
Log.v("Anim URL","Anim URL::"+anim_url);
Log.v("Anim Name","Anim Name::"+anim_name);
HashMap<String, String> tmp_album = new HashMap<String, String>();
tmp_album.put("anim_id", anim_id);
tmp_album.put("anim_thumb", anim_thumb);
albumList.add(tmp_album);
}
}
catch (Exception e)
{
Log.v("Home ::","Call JSON Exception in get Album in List--->"+e.toString());
e.printStackTrace();
}
}
catch (IOException e)
{
Log.v("Exception: Get get Album in List","Name-"+e.toString());
e.printStackTrace();
}
return "0";
}
#Override
protected void onPostExecute(String code)
{
Toast.makeText(getApplicationContext(), "Image URL Call Successfully", Toast.LENGTH_LONG).show();
Log.v("Album","Album List::"+albumList);
ECard_main_Custom_Adapter adapter =new ECard_main_Custom_Adapter(getApplicationContext(),albumList);
hlv.setAdapter(adapter);
progressDialog.dismiss();
progressDialog = null;
}
}
}
And My Adapter Is:
import java.util.ArrayList;
import java.util.HashMap;
import com.loopj.android.image.SmartImageView;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class ECard_main_Custom_Adapter extends BaseAdapter
{
private Context context;
ArrayList<HashMap<String, String>> listAlbum;
ViewHolder vholder;
Drawable image;
public ECard_main_Custom_Adapter(Context context, ArrayList<HashMap<String, String>> albumList)
{
this.context = context;
this.listAlbum=albumList;
}
#Override
public int getCount()
{
Log.v("1","1");
return listAlbum.size();
}
#Override
public Object getItem(int position)
{
Log.v("1","2");
return position;
}
#Override
public long getItemId(int position)
{
Log.v("1","3");
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
Log.v("1","1");
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi=convertView;
vi = inflater.inflate(R.layout.ecard_main_adapter, null);
vholder = new ViewHolder();
vholder.img_album=(SmartImageView)vi.findViewById(R.id.IV_image);
vi.setTag(vholder);
try
{
String anim_id=listAlbum.get(position).get("anim_id");
String url=listAlbum.get(position).get("anim_thumb");
Log.v("Anim ID and Anim URL","Id:"+anim_id+" URL:"+url);
vholder.img_album.setImageUrl(url);
}
catch (Exception e)
{
// TODO: handle exception
Log.v("Error Ecard","Error is:::"+e);
}
return vi;
}
static class ViewHolder
{
SmartImageView img_album;
}
}
Please tell me where I am wrong.
Any help is appreciated.
Thanks In advance.
First correct this
hlv = (ListView) findViewById(android.R.id.list);
to
hlv = (ListView) findViewById(R.id.list);
It might cause an error. and make sure your ecard_main.xml layout contains ListView with id list

user bug in my app I can not reproduce

I have a feature in my app that gets a users gps coordinates then returns nearby breweries. When I use the feature it has never forced closed, and others have tested it to and it worked. One user reported this error when they opened the activity that gets the user location and tries to get the location of breweries:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.beerportfolio.beerportfoliopro/com.example.beerportfoliopro.FindBrewery}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2355)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
at android.app.ActivityThread.access$600(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5511)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.beerportfoliopro.FindBrewery.onCreate(FindBrewery.java:42)
at android.app.Activity.performCreate(Activity.java:5066)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1101)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
... 11 more
My activity that is launched is:
package com.example.beerportfoliopro;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
import com.beerportfolio.beerportfoliopro.R;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* Created by mike on 7/3/13.
*/
public class FindBrewery extends ActionbarMenu {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.beer_location_list);
String title = "Nearby Breweries";
TextView topTitle = (TextView) findViewById(R.id.beerLocationTitle);
topTitle.setText(title);
//get user location
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
//construct url
String url = myURLandKey;
Log.d("urlTest",url);
//async task goes here
new GetNearbyBreweries(this).execute(url);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
}
Lastly my asynctask is:
package com.example.beerportfoliopro;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.beerportfolio.beerportfoliopro.R;
public class GetNearbyBreweries extends AsyncTask
<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public GetNearbyBreweries (Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Locating Breweries");
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(R.id.locationList);
//make array list for beer
final List<BreweryLocationData> tasteList = new ArrayList<BreweryLocationData>();
for(int i = 0; i < json.getJSONArray("data").length(); i++) {
String brewery = json.getJSONArray("data").getJSONObject(i).getJSONObject("brewery").getString("name");
String id = json.getJSONArray("data").getJSONObject(i).getJSONObject("brewery").getString("id");
String latitude = json.getJSONArray("data").getJSONObject(i).getString("latitude");
String longitude = json.getJSONArray("data").getJSONObject(i).getString("longitude");
String distance = json.getJSONArray("data").getJSONObject(i).getString("distance");
int count = i + 1;
//create object
BreweryLocationData tempLocation = new BreweryLocationData(brewery, id, longitude , latitude,distance);
//add to arraylist
tasteList.add(tempLocation);
//add items to listview
BreweryLocationInfoAdapter adapter1 = new BreweryLocationInfoAdapter(c ,R.layout.listview_item_row, tasteList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
BreweryLocationData o=(BreweryLocationData)arg0.getItemAtPosition(arg2);
String tempID = o.id;
Toast toast = Toast.makeText(c, tempID, Toast.LENGTH_SHORT);
toast.show();
//get beer details from id
Intent myIntent = new Intent(c, BreweryPage2.class);
myIntent.putExtra("id", tempID);
c.startActivity(myIntent);
}
});
}
}
catch(Exception e){
}
Dialog.dismiss();
}
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();
}
}
You are getting a force close when attempting to get the users location. I would add validation that the use has GPS enabled and if not then give them an alert dialog asking them to enable, you may also send them directly to GPS settings.
Can the user reproduce the error?
From your code listing it seems line 42 is(maybe you edited it though):
39 LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
40 Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
41 double longitude = location.getLongitude();
42 double latitude = location.getLatitude();
Cant see why getLatitude() would break and not getLongitude()
You should validate location, to make sure you have it.
As a couple of others have pointed out, it is telling you that the error is on line 42. Unfortunately you have slightly affected the line numbers pasting it here. On your line 42 you are assuming something is not null, and it actually is null.
Given that LocationManager#getLastKnownLocation can return null, and you're not checking for that, I'd say that was your issue, and that your line 42 is where you call location.getLongitude().
getLastKnownLocation will only return a Location if the provider you specify has been used recently. If nothing has forced it to find a location yet, or for a long time (Android considers the last location too old to be correct), then you will get null.

Categories

Resources