I have created an app that I want to list all the installed applications to to a custom listview. bt unfortunately the activity crashes at the start! can any one please help me on this! I cant find the error, since it does not give any!
AppActivity.java
package com.ex.layout;
import java.util.List;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class AppActivity extends Activity implements OnItemClickListener{
String[] name = getaAppName();
String[] packs = getPackName();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView li = (ListView) findViewById(R.id.applist);
ListviewAdapet list = new ListviewAdapet(this, name, packs);
li.setAdapter(list);
li.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(this,"Title => "+name[position]+"=> n Description"+packs[position], Toast.LENGTH_SHORT).show();
}
public String[] getaAppName() {
List<PackageInfo> apps = getPackageManager().getInstalledPackages(0);
String appname[] = new String[apps.size()];
for (int number = 0; number < apps.size(); number++) {
PackageInfo pack = apps.get(number);
appname[number] = pack.applicationInfo.loadLabel(getPackageManager()).toString();
}
return appname;
}
public String[] getPackName(){
List<PackageInfo> apps = getPackageManager().getInstalledPackages(0);
String packnames[] = new String[apps.size()];
for (int i = 0; i < apps.size(); i++) {
PackageInfo pack = apps.get(i);
packnames[i] = pack.packageName;
}
return packnames;
}
}
this is the next class! it extends baseadapter to get the output.
listviewadapet.java
package com.ex.layout;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class ListviewAdapet extends BaseAdapter{
Activity context;
String[] appname , packname;
public ListviewAdapet(Activity Context, String[] appname , String[] packname) {
// TODO Auto-generated constructor stub
super();
this.appname = appname;
this.packname = packname;
this.context = Context;
}
public class Viewholder{
TextView appname;
TextView packname;
}
public int getCount(String[] array) {
// TODO Auto-generated method stub
int count = array.length;
return count;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Viewholder view;
LayoutInflater inflator = context.getLayoutInflater();
if (convertView == null) {
convertView = inflator.inflate(R.layout.listitem, null);
view = new Viewholder();
view.appname = (TextView) convertView.findViewById(R.id.appname);
view.packname= (TextView) convertView.findViewById(R.id.packagename);
convertView.setTag(view);
} else {
view = (Viewholder) convertView.getTag();
}
view.appname.setText(appname[position]);
view.packname.setText(packname[position]);
return convertView;
}
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
}
Please help me on this!
Thank you.
You have done two serious errors in code.
Error 1
String[] name = getaAppName();
String[] packs = getPackName();
You are calling these two methods before onCreate.REMEMBER getPackageManager needs Activity context.If you define it before onCreate you will get damn NullPointerException
So change your code
from
public class AppActivity extends Activity implements OnItemClickListener{
String[] name = getaAppName();
String[] packs = getPackName();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
To
public class AppActivity extends Activity implements OnItemClickListener{
String[] name;
String[] packs;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
name = getaAppName();
packs = getPackName();
Error 2
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
You will get Empty list if you return 0 here.
So change it to
public int getCount() {
return packname.length;
}
Related
I am supposed to access a button of an element in a grid view and supposed to capture the onItemClick() activity of that button, but somehow I am not able to do it. Help me out. I am posting my code below. Please check it.
package com.nik.cardone;
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
public class Fragment2 extends Fragment{
GridView fragment2Grid;
POJOMenuGrid pojo;
ArrayList<POJOMenuGrid> arr;
String[] name = {"Manchow Soup","Clear Soup","Mushroom Soup","Corn Soup","Tomato Soup"};
String[] desc = {"Soya water with capsicum , carrots , medium spicy"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v = inflater.inflate(R.layout.new_order_fragment_2, null);
initialize();
fragment2Grid = (GridView)v.findViewById(R.id.fragment2Grid);
fragment2Grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
View v = arg0.getChildAt(arg2);
// TODO Auto-generated method stub
System.out.println("In grid :");
}
});
for(int i=0;i<5;i++){
arr.add(new POJOMenuGrid(name[i], desc[0], R.drawable.t2));
}
System.out.println(arr.get(0).getName()+" "+arr.get(0).getDescription()+" ");
CustomGridAdapter adapter = new CustomGridAdapter(v.getContext(), arr);
fragment2Grid.setAdapter(adapter);
System.out.println("adapter set");
return v;
}
private void initialize() {
// TODO Auto-generated method stub
arr = new ArrayList<POJOMenuGrid>();
}
}
Custom Adapter
package com.nik.cardone;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomGridAdapter extends BaseAdapter{
Context context;
ArrayList<POJOMenuGrid> arr;
LayoutInflater inflater;
TextView itemName;
TextView itemDescription;
ImageView itemImage;
Button plus;
Button minus;
TextView counter;
public CustomGridAdapter(Context context, ArrayList<POJOMenuGrid> arr) {
super();
this.context = context;
this.arr = arr;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
System.out.println("in constructor");
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arr.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arr.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
System.out.println("in adapter 1");
arg1 = inflater.inflate(R.layout.grid_single_item, null);
System.out.println("in adapter 2");
itemName = (TextView)arg1.findViewById(R.id.itemName);
itemDescription = (TextView)arg1.findViewById(R.id.itemDescription);
//counter = (TextView)arg1.findViewById(R.id.counter);
itemImage = (ImageView)arg1.findViewById(R.id.itemImage);
plus = (Button)arg1.findViewById(R.id.plus);
minus = (Button)arg1.findViewById(R.id.minus);
plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
System.out.println("In plus :");
// TODO Auto-generated method stub
TextView counter = (TextView)arg0.findViewById(R.id.counter);
int counter1 = Integer.parseInt(counter.getText().toString());
counter1++;
counter.setText(""+counter1);
}
});
minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
TextView counter = (TextView)arg0.findViewById(R.id.counter);
int counter1 = Integer.parseInt(counter.getText().toString());
counter1--;
counter.setText(""+counter1);
}
});
System.out.println("in adapter 3");
itemName.setText(arr.get(arg0).getName());
itemDescription.setText(arr.get(arg0).getDescription());
itemImage.setImageResource(arr.get(arg0).getImage());
System.out.println("in adapter 4");
return arg1;
}
}
In my application I have search tab which display images with their name in grid view and now I want to implement search functionality. I have been searching in google for past two days but I didn't get any solution. Any idea or tutorial 0r how can I achieve this?
Anyone help me with this.
Thanks in advance.
mainactivity
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import com.example.diceapp.R;
public class SearchActivity extends Activity
{
JSONArray results;
JSONObject jobj;
SearchCustomAdapter adapter1;
ImageButton ib;
ArrayList<String> a1,a2,a3,a4;
ArrayList<String> name=new ArrayList<String>();
ArrayList<String> description=new ArrayList<String>();
ArrayList<String> image=new ArrayList<String>();
ArrayList<String> price=new ArrayList<String>();
Button add;
String pid;
GridView gView;
EditText src;
int textlength = 0;
ArrayList<String> p_name = new ArrayList<String>();
ArrayList<String> p_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.search_activity);
a1=new ArrayList<String>();
a2=new ArrayList<String>();
a3=new ArrayList<String>();
a4=new ArrayList<String>();
src=(EditText)findViewById(R.id.srcetxt);
/*src.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
SearchActivity.this.adapter1.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});*/
new Searchtask().execute();
gView = (GridView)findViewById(R.id.gridView1);
gView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
System.out.println("outside on click"+position);
}
});
ib=(ImageButton)findViewById(R.id.imageButton1);
}
private class Searchtask extends AsyncTask<String, String, JSONObject>
{
private ProgressDialog pDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(SearchActivity.this);
pDialog.setMessage("Loading Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args)
{
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl("http:link.php");
return json;
}
#Override
protected void onPostExecute(JSONObject json)
{
System.out.println("---------------return name list json------------"+json);
pDialog.dismiss();
try
{
jobj=json.getJSONObject("response");
// Getting Array of Contacts
results = jobj.getJSONArray("obejects");
System.out.println("In product Activity after JSON");
// looping through All Contacts
for(int i = 0; i < results.length(); i++)
{
JSONObject c = results.getJSONObject(i);
name.add(c.getString("name"));
image.add(c.getString("image"));
price.add(c.getString("price"));
description.add(c.getString("Description"));
}
}
catch (JSONException e)
{
e.printStackTrace();
}
adapter1 = new SearchCustomAdapter(getApplicationContext(), R.layout.gridlistimg, name, image,description,price);
gView.setAdapter(adapter1);
}
}
}
baseadapter class
package com.example.diceapp.search;
import java.util.ArrayList;
import android.content.Context;
import android.content.Intent;
import android.sax.StartElementListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import com.example.diceapp.AAAMainActivity;
import com.example.diceapp.R;
import com.example.diceapp.category.ImageLoader;
public class SearchCustomAdapter extends BaseAdapter
{
Context context;
LayoutInflater inflater;
ArrayList<String> aaaa1,bbbb1,cccc1;
ArrayList<String> c_pname;
ArrayList<String> c_pimage;
ArrayList<String> c_pprice;
ArrayList<String> c_pdescription;
String[] data_text;
String[] data_image;
ImageLoader iloader;
public SearchCustomAdapter(Context c, int productDescribe,ArrayList<String> pname, ArrayList<String> pimage,
ArrayList<String> productdescription, ArrayList<String> pprice)
{
// TODO Auto-generated constructor stub
this.context=c;
this.c_pname=pname;
this.c_pprice=pprice;
this.c_pdescription=productdescription;
this.c_pimage=pimage;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
iloader= new ImageLoader(context.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return c_pname.size();
//return data_text.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int pos) {
// TODO Auto-generated method stub
//return c_pname.indexOf(getItem(pos));//arg0;
return pos;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
View row=convertView;
ViewHolder vh;
if(row==null)
{
row=inflater.inflate(R.layout.custom_search_activity, parent, false);
vh=new ViewHolder();
vh.pname=(TextView)row.findViewById(R.id.product_name);
vh.pprice=(TextView)row.findViewById(R.id.textView2);
vh.image1=(ImageView) row.findViewById(R.id.imageView1);
vh.btn=(Button)row.findViewById(R.id.p_custom_tv);
/*row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
System.out.println("outside on click"+position);
ArrayList<String> sendingary=new ArrayList<String>();
sendingary.add(c_pname.get(position));
sendingary.add(c_pprice.get(position));
sendingary.add(c_pimage.get(position));
sendingary.add(c_pdescription.get(position));
Intent cp=new Intent(context.getApplicationContext(),product_details.class);
cp.putStringArrayListExtra("aryvalue", sendingary);
cp.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(cp);
}
});*/
row.setTag(vh);
}
else
{
vh = (ViewHolder) row.getTag();
row=convertView;
}
vh.pname.setText(c_pname.get(position));
vh.pprice.setText("KD "+c_pprice.get(position));
iloader.DisplayImage(c_pimage.get(position), vh.image1);
return row;
}
public static class ViewHolder
{
TextView pname,pprice;
ImageView image1;
Button btn;
}
public SearchCustomAdapter getFilter() {
// TODO Auto-generated method stub
return null;
}
}
If you use ArrayAdapter as your gridview's adapter, you can override getFilter() method and return your own Filter, which is able to filter items according to entered text. See e.g. this link to learn how to work with Filter. Good luck. :-)
Hi I just edit your code please replace and check it
SearchActivity.java
import java.util.ArrayList;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
public class SearchActivity extends Activity {
JSONArray results;
JSONObject jobj;
SearchCustomAdapter adapter1;
ImageButton ib;
ArrayList<String> a1, a2, a3, a4;
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> description = new ArrayList<String>();
ArrayList<String> image = new ArrayList<String>();
ArrayList<String> price = new ArrayList<String>();
Button add;
String pid;
GridView gView;
EditText src;
int textlength = 0;
ArrayList<String> p_name = new ArrayList<String>();
ArrayList<String> p_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.search_activity);
a1 = new ArrayList<String>();
a2 = new ArrayList<String>();
a3 = new ArrayList<String>();
a4 = new ArrayList<String>();
src = (EditText) findViewById(R.id.srcetxt);
src.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
if (src.getText().toString().trim().length() > 0) {
applySearch(src.getText().toString().trim());
} else {
adapter1.setC_pname(name);
adapter1.setC_pdescription(description);
adapter1.setC_pimage(image);
adapter1.setC_pprice(price);
adapter1.notifyDataSetChanged();
}
}
});
new Searchtask().execute();
gView = (GridView) findViewById(R.id.gridView1);
gView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
System.out.println("outside on click" + position);
}
});
ib = (ImageButton) findViewById(R.id.imageButton1);
}
private class Searchtask extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchActivity.this);
pDialog.setMessage("Loading Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl("http:link.php");
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
System.out.println("---------------return name list json------------" + json);
pDialog.dismiss();
try {
jobj = json.getJSONObject("response");
// Getting Array of Contacts
results = jobj.getJSONArray("obejects");
System.out.println("In product Activity after JSON");
// looping through All Contacts
for (int i = 0; i < results.length(); i++) {
JSONObject c = results.getJSONObject(i);
name.add(c.getString("name"));
image.add(c.getString("image"));
price.add(c.getString("price"));
description.add(c.getString("Description"));
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter1 = new SearchCustomAdapter(getApplicationContext(), R.layout.gridlistimg, name, image, description, price);
gView.setAdapter(adapter1);
}
}
private void applySearch(String searchStr) {
ArrayList<String> searchname = new ArrayList<String>();
ArrayList<String> searchdescription = new ArrayList<String>();
ArrayList<String> searchimage = new ArrayList<String>();
ArrayList<String> searchprice = new ArrayList<String>();
for (int i = 0; i < name.size(); i++) {
if (name.get(i).contains(searchStr)) {
searchname.add(name.get(i));
searchdescription.add(description.get(i));
searchimage.add(image.get(i));
searchprice.add(price.get(i));
}
}
adapter1.setC_pname(searchname);
adapter1.setC_pdescription(searchdescription);
adapter1.setC_pimage(searchimage);
adapter1.setC_pprice(searchprice);
adapter1.notifyDataSetChanged();
}
}
SearchCustomAdapter.java
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class SearchCustomAdapter extends BaseAdapter {
Context context;
LayoutInflater inflater;
ArrayList<String> aaaa1, bbbb1, cccc1;
ArrayList<String> c_pname;
ArrayList<String> c_pprice;
ArrayList<String> c_pdescription;
ArrayList<String> c_pimage;
public void setC_pname(ArrayList<String> c_pname) {
this.c_pname = c_pname;
}
public void setC_pimage(ArrayList<String> c_pimage) {
this.c_pimage = c_pimage;
}
public void setC_pprice(ArrayList<String> c_pprice) {
this.c_pprice = c_pprice;
}
public void setC_pdescription(ArrayList<String> c_pdescription) {
this.c_pdescription = c_pdescription;
}
String[] data_text;
String[] data_image;
ImageLoader iloader;
public SearchCustomAdapter(Context c, int productDescribe, ArrayList<String> pname, ArrayList<String> pimage, ArrayList<String> productdescription, ArrayList<String> pprice) {
// TODO Auto-generated constructor stub
this.context = c;
this.c_pname = pname;
this.c_pprice = pprice;
this.c_pdescription = productdescription;
this.c_pimage = pimage;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
iloader = new ImageLoader(context.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return c_pname.size();
// return data_text.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int pos) {
// TODO Auto-generated method stub
// return c_pname.indexOf(getItem(pos));//arg0;
return pos;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
ViewHolder vh;
if (row == null) {
row = inflater.inflate(R.layout.custom_search_activity, parent, false);
vh = new ViewHolder();
vh.pname = (TextView) row.findViewById(R.id.product_name);
vh.pprice = (TextView) row.findViewById(R.id.textView2);
vh.image1 = (ImageView) row.findViewById(R.id.imageView1);
vh.btn = (Button) row.findViewById(R.id.p_custom_tv);
/*
* row.setOnClickListener(new OnClickListener() {
*
* #Override public void onClick(View arg0) {
*
* System.out.println("outside on click"+position);
*
*
* ArrayList<String> sendingary=new ArrayList<String>();
*
* sendingary.add(c_pname.get(position));
*
* sendingary.add(c_pprice.get(position));
*
* sendingary.add(c_pimage.get(position));
*
* sendingary.add(c_pdescription.get(position));
*
* Intent cp=new
* Intent(context.getApplicationContext(),product_details.class);
*
* cp.putStringArrayListExtra("aryvalue", sendingary);
*
* cp.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
*
* context.startActivity(cp);
*
* } });
*/
row.setTag(vh);
} else {
vh = (ViewHolder) row.getTag();
row = convertView;
}
vh.pname.setText(c_pname.get(position));
vh.pprice.setText("KD " + c_pprice.get(position));
iloader.DisplayImage(c_pimage.get(position), vh.image1);
return row;
}
public static class ViewHolder {
TextView pname, pprice;
ImageView image1;
Button btn;
}
}
I'm trying to add a Custom ListView With an Adapter to a Fragment.
I don't Know where is the problem exactly, I think I got everything in place yet I cant get rid of the Unfortunately Stopped message.
I Used the debug and knew where it all collapses ;
in the Fragment class at the
for (int i = 0;i<4;i++){
.
.
.
questions.add(question);
when the debug reaches this statement it ends.
Fragment
import java.util.List;
import code.me.R.id;
import android.R.layout;
import android.app.Application.ActivityLifecycleCallbacks;
import android.app.Fragment;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
#SuppressLint("NewApi")
public class Fragment1 extends Fragment
{
ListView lv;
List<Question> questions;
Integer[] Q_Id ;
String[] AskerUserName = {"Jack" ,"John" ,"Lio" ,"Sam" ,"Mike" };
String[] AnswererUserName ={"Jacob" ,"Mario" ,"Tom" ,"Shon" ,"Jasmine" };
String[] Qusetion = {"What?" ,"Where?" ,"When" ,"How?" ,"Who?" };
String[] Answer = {"jjjjjjjjjj","llllllll","fffffffff","eeeeeeeeeeee","oooooooooooo"};
#Override
public View onCreateView( LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState )
{
for (int i = 0;i<4;i++){
int qid = i;
String AUName = AskerUserName[i].toString();
String AnUName = AnswererUserName[i].toString();
String Ans = Answer[i].toString();
String Ques = Qusetion[i].toString();
Question question = new Question(qid, AUName, AnUName, Ans, Ques);
questions.add(question);
}
View view = inflater.inflate(R.layout.frag1, container, false);
QuestionsAdapter questad = new QuestionsAdapter(getActivity(),questions);
lv = (ListView) view.findViewById(id.listView1);
lv.setAdapter(questad);
return inflater.inflate( R.layout.frag1,
container, false );
}
}
Adapter
import java.util.List;
import code.me.R.id;
import android.R.layout;
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.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class QuestionsAdapter extends BaseAdapter {
private final Activity context;
public List<Question> questions;
LayoutInflater inflater;
public QuestionsAdapter(Activity context,List<Question> qu) {
this.context = context;
this.questions = qu;
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View view , ViewGroup parent){
View rowView = view;
if(view == null)
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.question_answer_item, null,false);
TextView askerUserName = (TextView) view.findViewById(id.askerUsername);
askerUserName.setText(questions.get(position).getAskerUserName().toString());
TextView question = (TextView) view.findViewById(id.Question);
question.setText(questions.get(position).getQuestion().toString());
TextView ratingView = (TextView) view.findViewById(id.RatingAsker);
//ratingView.setText(questions.get(position)._RatingU);
TextView ratingAnswerer = (TextView) view.findViewById(id.RatingAnswerer);
//ratingAnswerer.setText(questions.get(position).getRatingView());
return rowView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return questions.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return questions.get(position)._QId;
}
}
Class_Question
public class Question {
private
String _Answer ;
String _AnswererUserName;
String _AskerUserName ;
String _Question ;
Integer _QId;
Integer _RatingU;
Integer _RatingQ;
public Question (int Q_Id,String AUName,String AnUName,String Ans,String Ques){
_QId = Q_Id;
_AnswererUserName = AnUName;
_AskerUserName = AUName;
_Answer = Ans;
_Question = Ques;
}
public String getAnswer() {
// TODO Auto-generated method stub
return _Answer;
}
public String getAnswererUserName() {
// TODO Auto-generated method stub
return _AnswererUserName;
}
public String getAskerUserName() {
// TODO Auto-generated method stub
return _AskerUserName;
}
public String getQuestion() {
// TODO Auto-generated method stub
return _Question;
}
public int getRatingView() {
// TODO Auto-generated method stub
return _RatingU;
}
public void setRatingQ() {
// TODO Auto-generated method stub
}
public int getRatingQ() {
// TODO Auto-generated method stub
return _RatingQ;
}
}
You never initialize the List<Question> questions in your fragment.
You never initialize your question collection. That's why it stops when you try to add questions in onCreateView. Either initialize List questions initially or some time before you try to add things to it.
This is my code , I have a problem ,error message about ResourcesNotFoundException this is a piece of code to view employees it has 2 buttons one to do delete and the other to do update.
I don't know the reason of this exception.
package com.example.task_9;
import java.util.ArrayList;
import com.example.task_9.my_dataBase.employees_con;
import com.example.task_9.my_dataBase.my_database;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class manage extends Activity {
ListView listview;
TextView totalrecords,tv;
//my_database db;
public ArrayList<employees> emp_list ;
employees_con con;
//Button logout;
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
setContentView(R.layout.manage);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("Employees Record:");
totalrecords = (TextView) findViewById(R.id.textView2);
listview = (ListView) findViewById(R.id.listView1);
// logout=(Button) findViewById(R.id.button1);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
emp_list = new ArrayList<employees>();
emp_list.clear();
con = new employees_con(this);
// db = new my_database(getApplicationContext());
// db.getWritableDatabase();
ArrayList<employees> e_list =con.getAllData() ;
for (int i = 0; i < e_list.size(); i++) {
Log.d("for_getall ", "ok ");
int e_id = e_list.get(i).getId();
Log.d("fun_getall ", "ok ");
// System.out.println("tidno>>>>>" + tidno);
String e_name = e_list.get(i).getUser_name();
String e_password = e_list.get(i).getPassword();
int e_age = e_list.get(i).getAge();
int e_status = e_list.get(i).getStatus();
Log.d("fun_getall ", "ok ");
employees emp_model = new employees();
emp_model.setId(e_id);
emp_model.setUser_name(e_name);
emp_model.setPassword(e_password);
emp_model.setAge(e_age);
emp_model.setStatus(e_status);
Log.d("addlist ", "ok ");
emp_list.add(emp_model);
}
Log.d("out for ", "ok ");
totalrecords.setText("Total Records :-" + emp_list.size());
listview.setAdapter(new ListAdapter(this));
con.close();
}
private class ListAdapter extends BaseAdapter {
//ArrayList<employees> data=new ArrayList<employees>();
Context contxt;
TextView id;
TextView user_name;
TextView password;
TextView age;
TextView status;
ImageView img;
employees obj;
LayoutInflater inflater;
public ListAdapter(Context context) {
// TODO Auto-generated constructor stub
contxt=context;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return emp_list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
// TODO Auto-generated method stub
/*if (v == null) {
v = inflater.inflate(R.layout.view, null);}*/
if (v == null)
{
LayoutInflater vi = (LayoutInflater)contxt.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.view, null); // album_list.xml this layout of the custom listview
Log.d("view if", "ok ");
}
id=(TextView) v.findViewById(R.id.textView6);
user_name=(TextView) v.findViewById(R.id.textView7);
password=(TextView) v.findViewById(R.id.textView8);
age=(TextView) v.findViewById(R.id.textView9);
status=(TextView) v.findViewById(R.id.textView10);
img =(ImageView) v.findViewById(R.id.imageView1);
Log.d("out if", "ok ");
obj = emp_list.get(position);
user_name.setText(obj.getUser_name());
id.setText(obj.getId());
password.setText(obj.getPassword());
age.setText(obj.getAge());
status.setText(obj.getStatus());
Log.d("view else ", "ok ");
final int temp = position;
(v.findViewById(R.id.button1))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
int emp_id=emp_list.get(temp).getId();
String emp_name = emp_list.get(temp).getUser_name();
String emp_password = emp_list.get(temp).getPassword();
int emp_age=emp_list.get(temp).getAge();
int emp_status=emp_list.get(temp).getStatus();
Intent intent = new Intent(manage.this,update.class);
Bundle bundle = new Bundle();
bundle.putInt("id", emp_id);
bundle.putString("name", emp_name);
bundle.putString("password", emp_password);
bundle.putInt("age", emp_age);
bundle.putInt("status", emp_status);
intent.putExtras(bundle);
startActivity(intent);
}
});
(v.findViewById(R.id.button2))
.setOnClickListener(new OnClickListener() {
employees_con con=new employees_con(contxt);
public void onClick(View arg0) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(manage.this);
alertbox.setCancelable(true);
alertbox.setMessage("Are you sure you want to delete ?");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
con.DeleteEmp(emp_list.get(temp).getUser_name().toString());
con.close();
manage.this.onResume();
Toast.makeText(
getApplicationContext(),
"Record Deleted...",
Toast.LENGTH_SHORT).show();
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
Toast.makeText(
getApplicationContext(),
"No Clicked...",
Toast.LENGTH_SHORT).show();
}
});
alertbox.show();
}
});
return v;
}
}
}
}
Change
id.setText(obj.getId());
with
id.setText(String.valueOf(obj.getId()));
if you pass an int as argument for a TextView android will look for a String with id the int you provide. If it does not found throws an exception
One important this is that you should use Activity.onCreate() method in place of Activity.onStart().
Android 2.3.3
I have seen few questions at stackoverflow, regarding refreshing the listview. But none of them worked for me.
I have a dynamic listview and I have a button inside it. The data is being populated from database and each listview row is a custom layout. On press of the (Clear) button, the database is cleared(which works fine) and the listview should get refreshed(the part to be figured out).
Below is the code...
import java.util.ArrayList;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.mobilevoiceapps.advancedvoicecalculatorfree.R;
public class History extends ListActivity {
ListView lvHistory;
ArrayAdapter<String> adHistory;
ArrayList<String> alHistoryCopy = new ArrayList<String>();
String[] emptyList = { "Your Calculations History is Empty. Please Perform Some Calculations and visit again." };
Database db;
Cursor c;
String expression = "";
String result = "";
boolean isEmpty = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// setContentView(R.layout.history);
lvHistory = getListView();
final MyCustomAdapter myad = new MyCustomAdapter();
db = new Database(this);
c = db.retrieve_history();
if (!((c.moveToFirst()) || c.equals(null) || c.getCount() == 0)) {
} else if (c.getCount() > 0) {
c.moveToFirst();
}
LayoutInflater header = getLayoutInflater();
View header_View = header.inflate(R.layout.history_header, null);
lvHistory.addHeaderView(header_View);
View second_Header_View = header.inflate(
R.layout.history_second_header, null);
lvHistory.addHeaderView(second_Header_View);
Button btnClearHistory = (Button) second_Header_View
.findViewById(R.id.btnClearHistory);
btnClearHistory.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.clear_history();
myad.notifyDataSetChanged();
lvHistory.invalidateViews();
lvHistory.refreshDrawableState();
}
});
lvHistory.setAdapter(myad);
}
class MyCustomAdapter extends BaseAdapter {
#Override
public int getCount() {
// TODO Auto-generated method stub
return c.getCount();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
HistoryViewHolder viewHolder;
if (convertView == null) {
LayoutInflater li = getLayoutInflater();
convertView = li.inflate(R.layout.history_row, null);
viewHolder = new HistoryViewHolder();
viewHolder.txtcnt = (TextView) convertView
.findViewById(R.id.txtView_History_Count);
viewHolder.txtexp = (TextView) convertView
.findViewById(R.id.txtView_History_Expression);
viewHolder.txtres = (TextView) convertView
.findViewById(R.id.txtView_History_Result);
convertView.setTag(viewHolder);
} else {
viewHolder = (HistoryViewHolder) convertView.getTag();
}
viewHolder.txtcnt.setText(String.valueOf(position + 1));
System.out.println("Position"
+ viewHolder.txtcnt.getText().toString());
c.moveToPosition(position);
expression = c.getString(c.getColumnIndex("expression"));
result = c.getString(c.getColumnIndex("result"));
viewHolder.txtexp.setText(expression);
System.out.println("Expression"
+ viewHolder.txtexp.getText().toString());
viewHolder.txtres.setText(result);
System.out.println("Result"
+ viewHolder.txtres.getText().toString());
return convertView;
}
public class HistoryViewHolder {
TextView txtcnt;
TextView txtexp;
TextView txtres;
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (db != null) {
db.close();
}
if (c != null) {
c.close();
}
}
}
EDIT ::: With ScreenShots :::
Try to extend your MyCustomAdapter from BaseAdapter and use notifyDataSetChanged to refresh ListView.
The better way to display database content is CursorAdapter (or CursorLoader) - such adapters listen for update notifications and reloads the content automatically.
try this, You need to refresh you ListView after delete one item using myad.notifyDataSetChanged();
btnClearHistory.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
YourActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
myad.notifyDataSetChanged();
}
});
}
});
Try add c = db.retrieve_history(); after db.clear_history();.
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.clear_history();
c = db.retrieve_history();
myad.notifyDataSetChanged();
lvHistory.invalidateViews();
lvHistory.refreshDrawableState();
}
Hope this helped you.
Just restart your activity..
ActivityName.this.finish();
Intent intent=new Intent(this, ActivityName.class);
startActivity(intent);
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_loja, container, false);
listatividade = (ListView) view.findViewById(R.id.listservico);
String[] valueatividade = new String[] { "atividade 1",
"atividade 2",
"atividade 3" };
adapteratividade = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, valueatividade);
listatividade.setAdapter(adapteratividade);
listaatividade.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
int itemPosition = position;
String itemValue = (String) listaatividade.getItemAtPosition(position);
Toast.makeText(getActivity(), "Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG) .show();
updateData();
}
});
return view;
}
private void updateData() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
String[] valueatividade = new String[] { "atividade 4", "atividade 5", "atividade 6" };
adapteratividade = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, android.R.id.text1, valueatividade);
listatividade.setAdapter(adapteratividade);
}
});
}