I correctly fill an array? NewsData_data cannot be resolved to a variable.
NewsData NewsData_data[] = new NewsData[]
{
new NewsData(header[i], short_text[i], team[i], datatime[i], photo_url[i])
};
Problem in:
NewsDataAdapter adapter = new NewsDataAdapter(this,
R.layout.news_details, NewsData_data);
NewsData_data cannot be resolved to a variable. How to fix this error?
public void ListDrwaer() {
String[] header;
String[] short_text;
String[] team;
String[] datatime;
String[] photo_url;
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
header[i] = jsonChildNode.optString("header");
short_text[i] = jsonChildNode.optString("short_text");
team[i] = jsonChildNode.optString("team");
datatime[i] = jsonChildNode.optString("datatime");
photo_url[i] = jsonChildNode.optString("photo_url");
NewsData NewsData_data[] = new NewsData[]
{
new NewsData(header[i], short_text[i], team[i], datatime[i], photo_url[i])
};
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
NewsDataAdapter adapter = new NewsDataAdapter(this,
R.layout.news_details, NewsData_data);
View header1 = getActivity().getLayoutInflater().inflate(R.layout.news_details, null);
listView.addHeaderView(header1);
listView.setAdapter(adapter);
}
public class NewsData {
public String header;
public String short_text;
public String team;
public String datatime;
public String photo_url;
public NewsData(){
super();
}
public NewsData(String header,
String short_text,
String team,
String datatime,
String photo_url) {
super();
this.header = header;
this.short_text = short_text;
this.team = team;
this.datatime = datatime;
this.photo_url = photo_url;
}
}
public class NewsDataAdapter extends ArrayAdapter<NewsData>{
Context context;
int layoutResourceId;
NewsData data[] = null;
public NewsDataAdapter(Context context, int layoutResourceId, NewsData[] 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;
NewsDataHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new NewsDataHolder();
holder.img_news = (ImageView)row.findViewById(R.id.img_news);
holder.header = (TextView)row.findViewById(R.id.header);
holder.short_text = (TextView)row.findViewById(R.id.short_text);
holder.team = (TextView)row.findViewById(R.id.team);
holder.datatime = (TextView)row.findViewById(R.id.datatime);
row.setTag(holder);
}
else
{
holder = (NewsDataHolder)row.getTag();
}
NewsData NewsData = data[position];
Picasso.with(context).load(NewsData.photo_url).into(holder.img_news);
holder.header.setText(NewsData.header);
holder.short_text.setText(NewsData.short_text);
holder.team.setText(NewsData.team);
holder.datatime.setText(NewsData.datatime);
return row;
}
class NewsDataHolder
{
ImageView img_news;
TextView header;
TextView short_text;
TextView team;
TextView datatime;
}
}
Problem in:
NewsDataAdapter adapter = new NewsDataAdapter(this,
R.layout.news_details, NewsData_data);
NewsData_data cannot be resolved to a variable
You need to declare your array outside of the try block so that it is visible to the ArrayAdapter constructor.
As corsair922 mentioned, you'll want to declare your NewsData_data array outside your try catch block, otherwise you won't have access to it from outside the block. Additionally, you want to initialize your array once, and populate the array elements as you go as opposed to reinitializing your array each time:
Edit, I would also recommend you spend some time getting familiar with the Java coding conventions. They will make your code easier to maintain/tidier and will allow other people to better understand your code (http://www.oracle.com/technetwork/java/codeconv-138413.html).
public void ListDrwaer() {
String[] header;
String[] short_text;
String[] team;
String[] datatime;
String[] photo_url;
NewsData NewsData_data[];
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news");
NewsData_data = new NewsData[jsonMainNode.length()];
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
header[i] = jsonChildNode.optString("header");
short_text[i] = jsonChildNode.optString("short_text");
team[i] = jsonChildNode.optString("team");
datatime[i] = jsonChildNode.optString("datatime");
photo_url[i] = jsonChildNode.optString("photo_url");
NewsData_data[i] = new NewsData(header[i], short_text[i], team[i], datatime[i], photo_url[i]);
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
}
NewsDataAdapter adapter = new NewsDataAdapter(this, R.layout.news_details, NewsData_data);
View header1 = getActivity().getLayoutInflater().inflate(R.layout.news_details, null);
listView.addHeaderView(header1);
listView.setAdapter(adapter);
}
Related
I have a JSONArray which I am able to parse, but due to the structure of the array, I am having difficulties mapping the values extracted from fields with the same names. Instead of the for loop assigning values one after the other, the assignment looks at the last instance of the field name. So the values from the second JSONObject are assigned twice.
"Group": [
{
"-Type": "Mouldings",
"CurTier": "BRZ",
"NxtTier": "SIL",
"CurTierFrom": "$4,000",
"CurTierTo": "$9,999",
"NxtTierFrom": "$10,000",
"NxtTierTo": "$14,999",
"CurSales": "$2,107",
"ReqSales": "$7,893"
},
{
"-Type": "Accessories",
"CurTier": "BAS",
"NxtTier": "GLD",
"CurTierFrom": "$0",
"CurTierTo": "$1,499",
"NxtTierFrom": "$1,500",
"NxtTierTo": "$4,999",
"CurSales": "$693",
"ReqSales": "$807"
}
]
Code:
try {
JSONObject reader = new JSONObject(JSON_DATA);
JSONObject PricingTier = reader.getJSONObject("PricingTier");
JSONArray Group = PricingTier.getJSONArray("Group");
for (int i = 0; i < Group.length(); i++) {
JSONObject g = Group.getJSONObject(i);
final String Type = g.getString("#Type");
final String CurTier = g.getString("CurTier");
final String NxtTier = g.getString("NxtTier");
final String CurTierFrom = g.getString("CurTierFrom");
final String CurTierTo = g.getString("CurTierTo");
final String NxtTierFrom = g.getString("NxtTierFrom");
final String NxtTierTo = g.getString("NxtTierTo");
final String CurSales = g.getString("CurSales");
final String ReqSales = g.getString("ReqSales");
final String TypeA = g.getString("#Type");
final String CurTierA = g.getString("CurTier");
final String NxtTierA = g.getString("NxtTier");
final String CurTierFromA = g.getString("CurTierFrom");
final String CurTierToA = g.getString("CurTierTo");
final String NxtTierFromA = g.getString("NxtTierFrom");
final String NxtTierToA = g.getString("NxtTierTo");
final String CurSalesA = g.getString("CurSales");
final String ReqSalesA = g.getString("ReqSales");
fragment.getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
tvType.setText(Type);
tvCurTier.setText(CurTier);
tvNxtTier.setText(NxtTier);
tvCurTierFrom.setText(CurTierFrom);
tvCurTierTo.setText(CurTierTo);
tvNxtTierFrom.setText(NxtTierFrom);
tvNxtTierTo.setText(NxtTierTo);
tvCurSales.setText(CurSales);
tvReqSales.setText(ReqSales);
tvTypeA.setText(TypeA);
tvCurTierA.setText(CurTierA);
tvNxtTierA.setText(NxtTierA);
tvCurTierFromA.setText(CurTierFromA);
tvCurTierToA.setText(CurTierToA);
tvNxtTierFromA.setText(NxtTierFromA);
tvNxtTierToA.setText(NxtTierToA);
tvCurSalesA.setText(CurSalesA);
tvReqSalesA.setText(ReqSalesA);
}
});
}
Result:
"-Type": "Accessories",
"CurTier": "BAS",
"NxtTier": "GLD",
"CurTierFrom": "$0",
"CurTierTo": "$1,499",
"NxtTierFrom": "$1,500",
"NxtTierTo": "$4,999",
"CurSales": "$693",
"ReqSales": "$807"
"-Type": "Accessories",
"CurTier": "BAS",
"NxtTier": "GLD",
"CurTierFrom": "$0",
"CurTierTo": "$1,499",
"NxtTierFrom": "$1,500",
"NxtTierTo": "$4,999",
"CurSales": "$693",
"ReqSales": "$807"
You're getting array(i = 0) and writing in all the 18 variables then taking the value 1 and overwriting this same 18 variables.
You have to separate this variables from same for looping. for example: when Group.getObj(i = 0).
final String Type = g.getString("#Type");
and then when Group.getObj(i = 1):
final String TypeA = g.getString("#Type");
Create a class with getter and setter for your JSONArray Keys.
Use a for loop to read the Values, Refer the code.
for (int i = 0; i < Group.length(); i++) {
JSONObject g = Group.getJSONObject(i);
Actors actors = new Actors();
actors.setType(g.getString("#Type"));
......//your remaining code
arrayList.add(actors);
}
}
Actors is the class name.
Use an adapter class to show the list in ListView.
public class yourAdapter extends ArrayAdapter<Actors> {
LayoutInflater vi;
ViewHolder holder;
int resource;
private final Activity context;
private final ArrayList<Actors> details;
public WifiAdapter(Activity context, int resource , ArrayList<Actors> details) {
super(context, resource, details);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
this.resource = resource;
this.details = details;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null){
holder = new ViewHolder();
v = vi.inflate(resource, null);
holder.Type = (TextView) v.findViewById(R.id.type);
.......//your remaining code
v.setTag(holder);
}
else {
holder =(ViewHolder) v.getTag();
}
holder.Name.setText(details.get(position).getType());
..........//ur remaining code
return v;
}
static class ViewHolder {
public TextView Type;
//your remaing code
}
}
i tried to add two textViews to list item.that data get from list. when the list print, it display correctly. But in list view its not print correctly. Can anyone help me?
This is the custom adapter class.
#Override
public View getView(int arg0, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
final String text1 = listData.get(0);
final String text2 = listData.get(1);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.ratings_list, null);
}
TextView lblListHeader1 = (TextView) convertView.findViewById(R.id.textView1);
lblListHeader1.setText(text1);
TextView lblListHeader2 = (TextView) convertView.findViewById(R.id.textView2);
lblListHeader2.setText(text2);
return convertView;
}
This is the activity code.
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("ratings");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("rest_name");
listData = new ArrayList<String>();
if (restName.equalsIgnoreCase(name)) {
String userName = jsonChildNode.optString("user_name");
String rate = jsonChildNode.optString("rate");
String ratOut = "Rate : " + rate;
listData.add(userName);
listData.add(ratOut);
Log.d("Data", userName + rate);
}
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
RatingsAdapter adapter = new RatingsAdapter(getApplicationContext(),
listData);
listView.setAdapter(adapter);
}
I want to add user name, below of that it's rate.
This is should be the output list.
01-23 11:59:09.102: D/Data(4873): omali 3.5
01-23 11:59:09.102: D/Data(4873): sunil 2
01-23 11:59:09.102: D/Data(4873): kuma#fh.com 1.5
01-23 11:59:09.102: D/Data(4873): fhhhy#ghj.com 0.5
First of all, the way you are building the list, it will never work, since you are deleting it and creating a new one in every iteration, so when you create the adapter, in the listyou only have the last item.
I would do:
ArrayList<Pair<String,String>> listData = new ArrayList<Pair<String,String>>(); //added
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("ratings");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("rest_name");
//removed listData = new ArrayList<String>();
if (restName.equalsIgnoreCase(name)) {
String userName = jsonChildNode.optString("user_name");
String rate = jsonChildNode.optString("rate");
String ratOut = "Rate : " + rate;
listData.add(new Pair<String,String>(userName,ratOut ));//added
//removed listData.add(userName);
//removed listData.add(ratOut);
Log.d("Data", userName + rate);
}
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
RatingsAdapter adapter = new RatingsAdapter(getApplicationContext(),
listData);
listView.setAdapter(adapter);
}
Then, in the custom adapter class, you retrieve that data simply by
#Override
public View getView(int arg0, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
//only this 3 lines change
Pair<String,String> item= listData.get(arg0);
final String text1 = item.first;
final String text2 = item.second;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.ratings_list, null);
}
TextView lblListHeader1 = (TextView) convertView.findViewById(R.id.textView1);
lblListHeader1.setText(text1);
TextView lblListHeader2 = (TextView) convertView.findViewById(R.id.textView2);
lblListHeader2.setText(text2);
return convertView;
}
You are always printing the wrong data, regardless of the position of the item
final String text1 = listData.get(0);
final String text2 = listData.get(1);
So Better take the Different lists of the username and ratOut and display the data
final String text1 = userNameListData.get(arg0);
final String text2 = ratOutListData.get(arg0);
Here arg0 is the position
Replace this:
final String text1 = listData.get(0);
final String text2 = listData.get(1);
with:
final String text1 = listData.get(2*arg0);
final String text2 = listData.get((2*arg0)+1);
change to:
final String text1 = listData.get(arg0*2);
final String text2 = listData.get(arg0*2+1);
and override:
#Override
public int getCount() {
// TODO Auto-generated method stub
return listData.size()/2;
}
As you are adding both the text in one arraylist 0,1 belong to first item and 2,3 belong to 2nd and so on.
Also size of the list view item would be half of the size of arraylist.
Try this.
also change this:
listData = new ArrayList<String>();//<--out side for loop
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("rest_name");
if (restName.equalsIgnoreCase(name)) {
String userName = jsonChildNode.optString("user_name");
String rate = jsonChildNode.optString("rate");
String ratOut = "Rate : " + rate;
listData.add(userName);
listData.add(ratOut);
Log.d("Data", userName + rate);
}
}
I had query title column from database and want to set it in TextView in GridView.
How?
CafeDatasource
public List<Model_Insert> findTblCafe(){
List<Model_Insert> model_Inserts = new ArrayList<Model_Insert>();
Cursor cursor = database.query(CafeDbOpenHelper.TABLE_CAFE, rtv_tbl_Cafe,
null, null, null, null, null);
Log.i("number", "return" + cursor.getCount()+ " rows");
if(cursor.getCount() > 0){
while (cursor.moveToNext()) {
Model_Insert model_Insert = new Model_Insert();
model_Insert.setCafe_Id(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_ID)));
model_Insert.setCafe_Title(cursor.getString(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_TITLE)));
model_Insert.setCafe_Been(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_BEEN)));
model_Insert.setCafe_Want(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_WANT)));
model_Insert.setCafe_Address(cursor.getString(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_ADDRESS)));
model_Insert.setCafe_Thumb(cursor.getString(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_THUMB)));
model_Insert.setCafe_Description(cursor.getString(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_DESCRIPTION)));
model_Insert.setCafe_WifiRate(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_WIFI_RATE)));
model_Insert.setCafe_CoffeeRate(cursor.getInt(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_COFFEE_RATE)));
model_Insert.setCafe_Latitude(cursor.getDouble(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_LATITUDE)));
model_Insert.setCafe_Longitude(cursor.getDouble(cursor.getColumnIndex(CafeDbOpenHelper.CAFE_LONGITUDE)));
model_Inserts.add(model_Insert);
}
}
return model_Inserts;
}
MainActivity
public ArrayList<HashMap<String, String>> placeList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card);
===============================================================
dataSource = new CafeDataSource(this);
dataSource.open();
List<Model_Insert> model_Inserts = dataSource.findTblCafe();// query database (findTblCafe)
if(model_Inserts.size() == 0){
new DownloadImageTask().execute();
model_Inserts = dataSource.findTblCafe();
}
===============================================================
} // End onCreate
public void ShowAllContent() {
GridView gridView1 = (GridView) findViewById(R.id.grid_all);
gridView1.setAdapter(new ImageAdapter(TopActivity.this, placeList));
}
public class DownloadImageTask extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String... params) {
placeList = new ArrayList<HashMap<String,String>>();
JSONParser jParser = new JSONParser();
JSONObject jsonO = jParser.getJSONUrl(url);
try {
places = jsonO.getJSONArray("place");
for (int i = 0; i < places.length(); i++) {
JSONObject jobj = places.getJSONObject(i);
int cafe_id = jobj.getInt(TAG_CAFE_ID);
String cafe_title = jobj.getString(TAG_CAFE_TITLE);
int cafe_been = jobj.getInt(TAG_CAFE_BEEN);
int cafe_want = jobj.getInt(TAG_CAFE_WANT);
String cafe_address = jobj.getString(TAG_CAFE_ADDRESS);
String cafe_thumb = jobj.getString(TAG_CAFE_THUMB);
String cafe_description = jobj.getString(TAG_CAFE_DESCRIPTION);
int cafe_wifi_rate = jobj.getInt(TAG_CAFE_WIFI_RATE);
int cafe_coffee_rate = jobj.getInt(TAG_CAFE_COFFEE_RATE);
double cafe_latitude = jobj.getDouble(TAG_CAFE_LATITUDE);
double cafe_longitude = jobj.getDouble(TAG_CAFE_LONGITUDE);
// Table Save
Model_Insert model_Insert = new Model_Insert();
model_Insert.setCafe_Id(cafe_id);
model_Insert.setCafe_Been(cafe_been);
model_Insert.setCafe_Want(cafe_want);
model_Insert = dataSource.createTableCafeSave(model_Insert);
Log.i("data", " ID " + model_Insert.getCafe_Id());
// Table Cafe
model_Insert = new Model_Insert();
model_Insert.setCafe_Id(cafe_id);
model_Insert.setCafe_Title(cafe_title);
model_Insert.setCafe_Been(cafe_been);
model_Insert.setCafe_Want(cafe_want);
model_Insert.setCafe_Address(cafe_address);
model_Insert.setCafe_Thumb(cafe_thumb);
model_Insert.setCafe_Description(cafe_description);
model_Insert.setCafe_WifiRate(cafe_wifi_rate);
model_Insert.setCafe_CoffeeRate(cafe_coffee_rate);
model_Insert.setCafe_Latitude(cafe_latitude);
model_Insert.setCafe_Longitude(cafe_longitude);
model_Insert = dataSource.createTableCafe(model_Insert);
Log.i("data", " Picture " + model_Insert.getCafe_Id());
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_CAFE_TITLE, cafe_title);
placeList.add(map);
}
// for " piture " Object in json
pictures = jsonO.getJSONArray("pictures");
for (int i = 0; i < pictures.length(); i++) {
JSONObject jObj = pictures.getJSONObject(i);
int cafe_id = jObj.getInt(TAG_CAFE_ID);
String picture_url = jObj.getString(TAG_PICTURE_URL);
// Table Picture
Model_Insert model_Insert = new Model_Insert();
model_Insert.setCafe_Id(cafe_id);
model_Insert.setPitureUrl(picture_url);
model_Insert = dataSource.createTablePicture(model_Insert);
Log.i("pic", " Picture " + model_Insert.getPitureurl());
HashMap<String, String> map = new HashMap<String, String>();
placeList.add(map);
}
} catch (JSONException e) {
// TODO: handle exception
}
return null;
}
protected void onPostExecute(Void unused) {
ShowAllContent(); // When Finish Show Content
}
}
private static class ViewHolder {
public ImageView imageview;
public TextView txtTitle;
}
public class ImageAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String,String>>();
public ImageAdapter(Context c, ArrayList<HashMap<String, String>> myArrayList){
context = c;
MyArr = myArrayList;
}
#Override
public int getCount() {
return MyArr.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View converView, ViewGroup parent) {
ViewHolder viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(converView == null){
converView = inflater.inflate(R.layout.grid_item, null);
}
viewHolder.imageview = (ImageView) converView.findViewById(R.id.imv_card_cafe);
viewHolder.txtTitle = (TextView) converView.findViewById(R.id.txt_title);
/* String str = "frute : juse text";
Integer len;
len = str.length();
if(len > 20){
String result = str.substring(0, 15);
viewHolder.txtTitle.setText(result);
}
else {
viewHolder.txtTitle.setText(str);
} */
=============================================================================
viewHolder.txtTitle.setText(...............................?);
=============================================================================
viewHolder.imageview.setImageResource(mThumb[position]);
return converView;
}
}
because you are getting all titles inside model_Inserts List you will need to pass this List to Custom BaseAdapter for showing in TextView as :
Change ShowAllContent() method as:
public void ShowAllContent() {
GridView gridView1 = (GridView) findViewById(R.id.grid_all);
gridView1.setAdapter(new ImageAdapter(TopActivity.this, placeList,model_Inserts));
}
and ImageAdapter constructor as :
public class ImageAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> MyArr =
new ArrayList<HashMap<String,String>>();
List<Model_Insert> model_Inserts=null;
public ImageAdapter(Context c,
ArrayList<HashMap<String, String>> myArrayList,
List<Model_Insert> model_Inserts){
context = c;
MyArr = myArrayList;
this.model_Inserts=model_Inserts;
}
///your code here...
now use model_Inserts for getting Title to show inside getView
I am newer to the fragments. In oncreate method i pass this value to Appetizerlist. but it shows an error. How to clear the error? Please help me.
public class MyListFragment1 extends ListFragment {
ImageView back;
String url = Main.url;
String Qrimage;
Bitmap bmp;
ListView list;
AppetiserFragment adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.applistviewfragment, null);
list = (ListView) view.findViewById(R.id.list);
return view;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
InputStream is = null;
String result = "";
JSONObject jArray = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url + "test.php3");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
// TODO: handle exception
Log.e("Log", "Error in Connection" + e.toString());
// Intent intent = new Intent(ViewQRCode.this, PimCarder.class);
// startActivity(intent);
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
jArray = new JSONObject(result);
JSONArray json = jArray.getJSONArray("appetiser");
adapter = new AppetiserFragment(this, json);
list.setAdapter(adapter);
} catch (Exception e) {
// TODO: handle exception
Log.e("log", "Error in Passing data" + e.toString());
}
}
}
AppetiserFragment.java
public class AppetiserFragment extends BaseAdapter {
String url = Main.url;
public Context Context;
String qrimage;
Bitmap bmp, resizedbitmap;
Bitmap[] bmps;
Activity activity = null;
private LayoutInflater inflater;
private ImageView[] mImages;
String[] itemimage;
TextView[] tv;
String itemname, price, desc, itemno;
String[] itemnames, checkeditems, itemnos;
String[] prices;
String[] descs;
HashMap<String, String> map = new HashMap<String, String>();
public AppetiserFragment(Context context, JSONArray imageArrayJson) {
Context = context;
// inflater =
System.out.println(imageArrayJson);
// (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(activity);
inflater = LayoutInflater.from(context);
this.mImages = new ImageView[imageArrayJson.length()];
this.bmps = new Bitmap[imageArrayJson.length()];
this.itemnames = new String[imageArrayJson.length()];
this.prices = new String[imageArrayJson.length()];
this.descs = new String[imageArrayJson.length()];
this.itemnos = new String[imageArrayJson.length()];
try {
for (int i = 0; i < imageArrayJson.length(); i++) {
JSONObject image = imageArrayJson.getJSONObject(i);
qrimage = image.getString("itemimage");
itemname = image.getString("itemname");
itemno = new Integer(i + 1).toString();
price = image.getString("price");
desc = image.getString("itemdesc");
System.out.println(price);
itemnames[i] = itemname;
prices[i] = price;
descs[i] = desc;
itemnos[i] = itemno;
byte[] qrimageBytes = Base64.decode(qrimage.getBytes());
bmp = BitmapFactory.decodeByteArray(qrimageBytes, 0,
qrimageBytes.length);
int width = 100;
int height = 100;
resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height,
true);
bmps[i] = bmp;
mImages[i] = new ImageView(context);
mImages[i].setImageBitmap(resizedbitmap);
mImages[i].setScaleType(ImageView.ScaleType.FIT_START);
// tv[i].setText(itemname);
}
System.out.println(map);
} catch (Exception e) {
// TODO: handle exception
}
}
public AppetiserFragment() {
// TODO Auto-generated constructor stub
}
public int getCount() {
return mImages.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder viewHolder;
if (view == null) {
view = inflater.inflate(R.layout.appetiserlistview, null);
System.out.println("prakash");
viewHolder = new ViewHolder();
viewHolder.image = (ImageView) view
.findViewById(R.id.appetiserimage);
viewHolder.text = (TextView) view.findViewById(R.id.appetisertext);
viewHolder.desc = (TextView) view.findViewById(R.id.appetiserdesc);
viewHolder.price = (TextView) view
.findViewById(R.id.appetiserprice);
viewHolder.appitemnum = (TextView) view
.findViewById(R.id.appitemno);
// viewHolder.checkbox = (CheckBox) view.findViewById(R.id.bcheck);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.image.setImageBitmap(bmps[position]);
viewHolder.appitemnum.setText(itemnos[position]);
viewHolder.price.setText(prices[position]);
viewHolder.desc.setText(descs[position]);
// viewHolder.checkbox.setTag(itemnames[position]);
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(itemnames[position]);
return view;
}
static class ViewHolder {
protected TextView text, price, desc, appitemnum;
protected ImageView image;
public static CheckBox checkbox = null;
}
}
i Given whole code i want custom listview using listfragments
In the above code in this line, I'm getting an error at adapter = new Appetizerlist(this, json); Please tell me how to solve the problem. Help me.
as onCreate called before onCreateView so list will null there in onCreate ...........
http://developer.android.com/guide/topics/fundamentals/fragments.html
in oncreate
list.setAdapter(adapter);
in onCreateView you initlized that
list = (ListView) view.findViewById(R.id.list);
......
so move this line list.setAdapter(adapter); in onCreateView
You have error in following line.
adapter = new Appetizerlist(this, json);
Change it to
adapter = new Appetizerlist(getActivity().getApplicationContext(), json);
I want do custom listview using base adapter in listfragment
I try this code:
public class MyListFragment1 extends ListFragment {
ImageView back;
String url = Main.url;
String Qrimage;
Bitmap bmp;
ListView list;
AppetiserFragment adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View tmp_view = inflater.inflate(R.layout.applistviewfragment, container, false);
ListView list = (ListView) tmp_view.findViewById(R.id.list);
InputStream is = null;
String result = "";
JSONObject jArray = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url + "test.php3");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
// TODO: handle exception
Log.e("Log", "Error in Connection" + e.toString());
// Intent intent = new Intent(ViewQRCode.this, PimCarder.class);
// startActivity(intent);
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
jArray = new JSONObject(result);
JSONArray json = jArray.getJSONArray("appetiser");
adapter = new AppetiserFragment(getActivity(), json);
list.setAdapter(adapter);
} catch (Exception e) {
// TODO: handle exception
Log.e("log", "Error in Passing data" + e.toString());
}
return tmp_view;
}
}
AppetiserFragment.java
public class AppetiserFragment extends BaseAdapter {
public static ArrayList<String> arr = new ArrayList<String>();
public static ArrayList<String> itemprice = new ArrayList<String>();
public static ArrayList<Bitmap> image = new ArrayList<Bitmap>();
String url = Main.url;
public Context Context;
String qrimage;
Bitmap bmp, resizedbitmap;
Bitmap[] bmps;
Activity activity = null;
private LayoutInflater inflater;
private ImageView[] mImages;
String[] itemimage;
TextView[] tv;
String itemname, price, desc, itemno;
String[] itemnames, checkeditems, itemnos;
String[] prices;
String[] descs;
HashMap<String, String> map = new HashMap<String, String>();
public AppetiserFragment(Context context, JSONArray imageArrayJson) {
Context = context;
// inflater =
System.out.println(imageArrayJson);
// (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(activity);
inflater = LayoutInflater.from(context);
this.mImages = new ImageView[imageArrayJson.length()];
this.bmps = new Bitmap[imageArrayJson.length()];
this.itemnames = new String[imageArrayJson.length()];
this.prices = new String[imageArrayJson.length()];
this.descs = new String[imageArrayJson.length()];
this.itemnos = new String[imageArrayJson.length()];
try {
for (int i = 0; i < imageArrayJson.length(); i++) {
JSONObject image = imageArrayJson.getJSONObject(i);
qrimage = image.getString("itemimage");
itemname = image.getString("itemname");
itemno = new Integer(i + 1).toString();
price = image.getString("price");
desc = image.getString("itemdesc");
**System.out.println(price);**
itemnames[i] = itemname;
prices[i] = price;
descs[i] = desc;
itemnos[i] = itemno;
byte[] qrimageBytes = Base64.decode(qrimage.getBytes());
bmp = BitmapFactory.decodeByteArray(qrimageBytes, 0,
qrimageBytes.length);
int width = 100;
int height = 100;
resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height,
true);
bmps[i] = bmp;
mImages[i] = new ImageView(context);
mImages[i].setImageBitmap(resizedbitmap);
mImages[i].setScaleType(ImageView.ScaleType.FIT_START);
// tv[i].setText(itemname);
}
System.out.println(map);
} catch (Exception e) {
// TODO: handle exception
}
}
public AppetiserFragment() {
// TODO Auto-generated constructor stub
}
public int getCount() {
return mImages.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder viewHolder;
if (view == null) {
view = inflater.inflate(R.layout.appetiserlistview, null);
viewHolder = new ViewHolder();
viewHolder.image = (ImageView) view
.findViewById(R.id.appetiserimage);
viewHolder.text = (TextView) view.findViewById(R.id.appetisertext);
viewHolder.desc = (TextView) view.findViewById(R.id.appetiserdesc);
viewHolder.price = (TextView) view
.findViewById(R.id.appetiserprice);
viewHolder.appitemnum = (TextView) view
.findViewById(R.id.appitemno);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.image.setImageBitmap(bmps[position]);
viewHolder.appitemnum.setText(itemnos[position]);
viewHolder.price.setText(prices[position]);
viewHolder.desc.setText(descs[position]);
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(itemnames[position]);
return view;
}
static class ViewHolder {
protected TextView text, price, desc, appitemnum;
protected ImageView image;
public static CheckBox checkbox = null;
}
}
I can able to print price value. If I do separately as custom listview I can able to image, text, desc, price. But in MyFragmentlist1 extends with listfragment means I cannot able to view in custom listview. I thought MyListFragment1 in this class only I have problem.
First Create a separate layout layout_txtview. I am just using a textview. You can create layout according to items you want to show in a single row.
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="#000000"
android:textAppearance="?android:attr/textAppearanceSmall" />
Now Use this layout to inflate in getView() method of your custom adapter.
Now in onCreate() method of MyListFragment1 class just set the adapter to your custom adapter
setAdapter(new MyListFragment1 (<apss your constructor argument>));
and its done.
Try moving the setAdapter in the onActivityCreated callback, in this way
#Override
public void onActivityCreated(Bundle savedInstanceState) {
ListView list = getListView();
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}