I made one custom listview with image and text.When u click on image it ll lead you to new activity.Now i want to pass image and text to new activity.i know with putExtra method you can pass data but i don't know how can i use it here..
thanks in advance...
here is my code for adapter class..
Note..I am parsing data from json
Onclick method is used to go on another activity...
public class Adapter extends BaseAdapter {
private static final String TAG = "Adapter";
private Activity mActivity;
public ArrayList<Data> mObjects;
// /private final Context context;
Context context;
static class ViewHolder {
static ImageView icon;
TextView title;
TextView name;
TextView review;
DownloadImageTask mTask;
String ab[];
// DownloadImageTask1 mTask1;
// ImageView photo;
}
public Adapter(Activity activity, Context context, ArrayList<Data> mObjects) {
this.mActivity = (Activity) activity;
this.context = context;
this.mObjects = mObjects;
}
public void setObjects(ArrayList<Data> mObjects) {
this.mObjects = mObjects;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Data item = mObjects.get(position);
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = mActivity.getLayoutInflater();
rowView = inflater.inflate(R.layout.item, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.icon = (ImageView) rowView.findViewById(R.id.image);
// viewHolder.photo = (ImageView) rowView.findViewById(R.id.photo);
viewHolder.title = (TextView) rowView.findViewById(R.id.title);
viewHolder.name = (TextView) rowView.findViewById(R.id.name);
viewHolder.review = (TextView) rowView.findViewById(R.id.status);
rowView.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) rowView.getTag();
holder.title.setText(item.getmTitle());
holder.name.setText(item.getmConcatinate());
holder.review.setText(item.getmreview());
holder.icon.setBackgroundResource(R.drawable.ic_ab);
// holder.photo.setBackgroundResource(0);
holder.mTask = new DownloadImageTask(item.getmImageUrl(), holder.icon);
if (!holder.mTask.isCancelled()) {
holder.mTask.execute();
}
ViewHolder.icon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Parsing JSON Data", "Before user try122222"); // perform
// action
Intent intent = new Intent(v.getContext(), LargeView.class);
v.getContext().startActivity(intent);
}
});
// holder.mTask1 = new DownloadImageTask1(item.getmImageUrl1(),
// holder.photo);
// if (!holder.mTask1.isCancelled()) {
// holder.mTask1.execute();
// }
return rowView;
}
#Override
public int getCount() {
return (this.mObjects.size());
}
#Override
public Object getItem(int position) {
return (this.mObjects.get(position));
}
#Override
public long getItemId(int position) {
return (position);
}
public AbsListView.RecyclerListener mRecyclerListener = new RecyclerListener() {
public void onMovedToScrapHeap(View view) {
ViewHolder viewHolder = (ViewHolder) view.getTag();
DownloadImageTask imagetask = viewHolder.mTask;
// DownloadImageTask1 imagetask1 = viewHolder.mTask1;
if (imagetask != null) {
imagetask.cancel(true);
}
// if (imagetask1 != null) {
// // imagetask1.cancel(true);
// }
}
};
code in main activity.class
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll().penaltyLog().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile3);
name = (TextView) findViewById(R.id.textView1);
bmImage2 = (ImageView) findViewById(R.id.imageView1);
address = (TextView) findViewById(R.id.textView2);
gender = (TextView) findViewById(R.id.textView3);
loyalitypoints = (TextView) findViewById(R.id.textView7);
followers = (TextView) findViewById(R.id.textView8);
following = (TextView) findViewById(R.id.textView9);
// list13 = new ArrayList<HashMap<String, Object>>();
mListView = (ListView) findViewById(android.R.id.list);
mListView.setClickable(true);
// mListView=(ListView)findViewById(R.id.list);
mAdapter = new Adapter(this,c,mSource );
mListView.setAdapter(mAdapter);
Log.w("Parsing JSON Data", "Before Item click");
mListView.setRecyclerListener(mAdapter.mRecyclerListener);
}
public String getJSONfromURL(String url) {
InputStream is = null;
String result = "";
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
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();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return result;
}
use this way:
ViewHolder.icon.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Parsing JSON Data", "Before user try122222"); // perform
// action
Intent intent = new Intent(context, LargeView.class);
intent.putExtra("name", "dhaval");
context.startActivity(intent);
}
});
pass image in intent is BAD idea. just pass URL, Image Path, image name whatever you have..
like:
Intent intent = new Intent(context, LargeView.class);
intent.putExtra("name", "dhaval");
intent.putExtra("imangeUTL", "www.xyz.com/images/test.png");
context.startActivity(intent);
Related
I have create simple json data pass user first name and last name but i have display only one record but i have put intent in for loop this time multiple activity create and above for loop put intent this time display only one create.
And List size is database table value size.
Like this
FirstName LastName
Android corejava
Android corejava
Android corejava
Android corejava
**My Json Activity **
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fn = (EditText) findViewById(R.id.fn);
ln = (EditText) findViewById(R.id.ln);
insert = (Button) findViewById(R.id.insert1);
show = (Button) findViewById(R.id.button2);
requestQueue = Volley.newRequestQueue(getApplicationContext());
show.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(
new BasicHttpParams());
HttpPost httppost = new HttpPost(
"http://192.168.2.5/Demo/lgin.php");
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient
.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"),
8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (Exception squish) {
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
JSONObject jsonObj = null;
JSONArray jArray = null;
ArrayList<Model> data = new ArrayList<>();
try {
jsonObj = new JSONObject(result);
jArray = jsonObj.getJSONArray("userdetail");
Model model = new Model();
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject = null;
jObject = jArray.getJSONObject(i);
model.setName(jObject.getString("user"));
model.setLastname(jObject.getString("pass"));
Log.d(getClass().getName(), "User = " + model.getName() + "Pas = " + model.getLastname());
data.add(model);
}
Intent intent = new Intent(getApplicationContext(), ViewData.class);
intent.putExtra("data",new Gson().toJson(data));
startActivity(intent);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
});
insert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
StringRequest request = new StringRequest(Request.Method.POST, insertURl, new Response.Listener<String>() {
#Override
public void onResponse(String arg0) {
// TODO Auto-generated method stub
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
}) {
#Override
protected Map<String, String> getParams()
throws AuthFailureError {
// TODO Auto-generated method stub
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("user", fn.getText().toString());
parameters.put("pass", ln.getText().toString());
Log.d(getClass().getName(), "View =" + fn.getText().toString() + "LastNAme = " + ln.getText().toString());
return parameters;
}
};
requestQueue.add(request);
}
});
}
My Recyclerview Class
public class ViewData extends Activity {
private AdapterFish mAdapter;
private List<Model> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.container_fish);
String dataString = getIntent().getStringExtra("data");
ArrayList<Model> list = new Gson().fromJson(dataString, new TypeToken<ArrayList<Model>>() {
}.getType());
mAdapter = new AdapterFish(ViewData.this, (ArrayList<Model>) list);
RecyclerView mRVFishPrice = (RecyclerView) findViewById(R.id.fishPriceList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
mRVFishPrice.setLayoutManager(mLayoutManager);
mRVFishPrice.setAdapter(mAdapter);
}
Adapter
public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
ArrayList<Model> data;
Model current;
int currentPos = 0;
// create constructor to innitilize context and data sent from MainActivity
public AdapterFish(Context context, ArrayList<Model> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.customlayout, parent, false);
MyHolder holder = new MyHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
MyHolder myHolder = (MyHolder) holder;
Model model = data.get(position);
myHolder.tvFirstName.setText(model.getName());
myHolder.tvLastName.setText(model.getLastname());
}
#Override
public int getItemCount() {
return data.size();
}
class MyHolder extends RecyclerView.ViewHolder {
TextView tvFirstName;
TextView tvLastName;
// create constructor to get widget reference
public MyHolder(View itemView) {
super(itemView);
tvFirstName = (TextView) itemView.findViewById(R.id.tvFirstName);
tvLastName = (TextView) itemView.findViewById(R.id.tvLastName);
}
}
}
Convert your Array List into String using Gson and then pass it into Intent.
Intent intent = new Intent(getApplicationContext(), ViewData.class);
intent.putExtra("data",new Gson().toJson(data));
startActivity(intent)
Convert string back to list
String dataString = getIntent().getStringExtra("data") ;
ArrayList<Model> list = new Gson().fromJson(dataString ,new TypeToken<ArrayList<Model>>(){}.getType());
In Gradle
compile 'com.google.code.gson:gson:2.7'
If you are getting your data in Your Log Cat then pass your ArrayList using following approach.
Intent intent = new Intent(YourCurrentActivity.this, ViewData.class);
intent.putStringArrayListExtra("data", data);
startActivity(intent);
In your ViewData Activity you need to do
ArrayList<Model> list = new ArrayList<>();
list = getIntent().getStringArrayListExtra("data");
Pass list ti the your RecyclerView Adapter Class
mAdapter = new AdapterFish(ViewData.this, (ArrayList<Model>) list);
Try this:
Model model ;
for (int i = 0; i < jArray.length(); i++) {
model = new Model();
JSONObject jObject = null;
jObject = jArray.getJSONObject(i);
model.setName(jObject.getString("user"));
model.setLastname(jObject.getString("pass"));
Log.d(getClass().getName(), "User = " + model.getName() + "Pas = " + model.getLastname());
data.add(model);
}
or
Gson gson = new Gson();
data = gson.fromJson(response.toString(), new TypeToken<ArrayList<Model>>() {
}.getType());
I am new in android and am working with a project that loads data from internet into listview. I got my prototype here: kaleidosblog.com/android-listview-load-data-from-json
So these will be the json links:
http://www.funtrial.com/christiancepe/announcements/json.php?page=1
http://www.funtrial.com/christiancepe/announcements/json.php?page=2
So on..
In my activity, I have my EditText, Button and ListView.
Editext will get the url.
Button will be use to load the json link (from url) to listview
Listview will display datas
In my current program, it only works on first click of button. So once I entered the first json, it will show the correct data. But when I try to change the json on EditText, still the ListView is populated by the first json. In short, my ListView does not refresh everytime I am changing the link and clicking the button.
What's wrong with this?
Main Activity:
protected void onCreate(Bundle savedInstanceState) {
final Button searchButton = (Button) findViewById(R.id.searchButton);
final EditText searchForm = (EditText) findViewById(R.id.searchForm);
searchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
list = (ListView) findViewById(R.id.list);
adapter = new ListAdapter(MainActivity.this);
list.setAdapter(adapter);
search = searchForm.getText().toString();
Download_data download_data = new Download_data((download_complete) MainActivity.this);
download_data.download_data_from_link(search);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), search, Toast.LENGTH_LONG).show();
}
});
}
public void get_data(String data){
try {
JSONObject jsonObj = new JSONObject(data);
JSONArray data_array = jsonObj.getJSONArray("announcements");
for (int i = 0 ; i < data_array.length() ; i++)
{
JSONObject obj=new JSONObject(data_array.get(i).toString());
Countries add=new Countries();
add.name = obj.getString("message");
add.code = obj.getString("date");
countries.add(add);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
Download_data.java
public class Download_data implements Runnable {
public download_complete caller;
public interface download_complete{
public void get_data(String data);
}
Download_data(download_complete caller) {
this.caller = caller;
}
private String link;
public void download_data_from_link(String link){
this.link = link;
Thread t = new Thread(this);
t.start();
}
public void run() {
threadMsg(download(this.link));
}
private void threadMsg(String msg) {
if (!msg.equals(null) && !msg.equals("")) {
Message msgObj = handler.obtainMessage();
Bundle b = new Bundle();
b.putString("message", msg);
msgObj.setData(b);
handler.sendMessage(msgObj);
}
}
private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
String Response = msg.getData().getString("message");
caller.get_data(Response);
}
};
public static String download(String url) {
URL website;
StringBuilder response = null;
try {
website = new URL(url);
HttpURLConnection connection = (HttpURLConnection) website.openConnection();
connection.setRequestProperty("charset", "utf-8");
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
} catch (Exception e) {
return "";
}
return response.toString();
}
ListAdapter.java
MainActivity main;
ListAdapter(MainActivity main)
{
this.main = main;
}
#Override
public int getCount() {
return main.countries.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
static class ViewHolderItem {
TextView name;
TextView code;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolderItem holder = new ViewHolderItem();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) main.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cell, null);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.code = (TextView) convertView.findViewById(R.id.code);
convertView.setTag(holder);
}
else
{
holder = (ViewHolderItem) convertView.getTag();
}
holder.name.setText(this.main.countries.get(position).name);
holder.code.setText(this.main.countries.get(position).code);
return convertView;
}
It appears that the countries list is being added to each time in get_data(), but never cleared out. At the start of get_data, you most likely want to clear the countries list with the following call:
countries.clear();
Then the data in the countries list will be cleared out, the new downloaded data will be added to the countries list, and then updated in the view when the adapter is notified of the data change.
Call BaseAdapter In Fragment Close Application
Comment in line spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
Work
Error Log
Class FragmentNews
public class FragmentNews extends Fragment {
ArrayList<Category> categorylist = new ArrayList<Category>();
#Override
public View onCreateView(final LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
final View rootView = inflater.inflate(R.layout.fragment_news,
container, false);
Spinner spinner = (Spinner) rootView.findViewById(R.id.category);
new fechPosts().execute("");
return rootView;
}
class fechPosts extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
ringProgressDialog = new ProgressDialog(getActivity());
ringProgressDialog.setMessage("در حال ارسال پیام");
ringProgressDialog.setCancelable(true);
ringProgressDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String result = fetch(params[0]);
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Activity myActivity = getActivity();
spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
ringProgressDialog.dismiss();
}
}
public String fetch(String titel) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = null;
httppost = new HttpGet(
"http://mynikan.ir/paliz/mobile/GetAllProduct.php");
String r = "ok";
String result = null;
InputStream inputStream = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
JSONArray array = null;
try {
array = new JSONArray(result);
} catch (JSONException e) {
e.printStackTrace();
}
if (array.length() != 0) {
for (int i = 0; i < array.length(); i++) {
JSONObject json_data;
try {
json_data = array.getJSONObject(i);
Category obj = new Category();
obj.Image = json_data.getString("Product_Image");
obj.Title = json_data.getString("Price");
categorylist.add(obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return r;
}
Class Adapter
public class Category_Adapter extends BaseAdapter {
public String[] items;
public LayoutInflater myinflater;
Context context;
static class ViewHolder
{
TextView text;
TextView price;
ImageView im;
}
public int[] picmenu;
ArrayList<Category> categorylist = new ArrayList<Category>();
public Category_Adapter(Context c, ArrayList<Category> pthemop) {
myinflater = LayoutInflater.from(c);
context = c;
categorylist = pthemop;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return categorylist.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(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
// /////
if (convertView == null) {
convertView = myinflater.inflate(R.layout.snipper_single, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.im = (ImageView) convertView.findViewById(R.id.image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(categorylist.get(position).Title);
Picasso.with(context).load(categorylist.get(position).Image)
.into(holder.im);
return convertView;
}}
Class Category
public class Category {
String Title;
String Image;
}
Here:
spinner.setAdapter(new Category_Adapter(getActivity(), categorylist));
line causing issue because spinner object of Spinner is null.
In onCreateView method creating new object instead of initializing object which is using in spinner.
Change onCreateView method as:
spinner = (Spinner) rootView.findViewById(R.id.category);
new fechPosts().execute("");
I have divided my android screen into 2 fragements .In the first one I make a listview from server database to android mobile.The problem is that I can't call getview method in the base adapter class. Do help me out
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) {
return inflater.inflate(R.layout.applistviewfragment, container, false);
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// back=(ImageView)findViewById(R.id.backfoodmenu);
/*
* back.setOnClickListener(new OnClickListener() {
*
* public void onClick(View v) { // TODO Auto-generated method stub
* Intent intent=new Intent(getApplicationContext(),FoodMenu.class);
* intent.putExtra("url", url); startActivity(intent); } });
*/
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
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");
Context context = null;
context = this.getActivity().getApplicationContext();
//(Here i want give lisid from xml)
list=(Listview)findViewById(R.id.list);//i type here it shows an error
adapter = new AppetiserFragment(context, json);
context = getActivity().getApplicationContext();
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);//here i can print 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;
}
}
i can able to print json data in base adpater class . Now i want pass json data in to text,image. i thought getview method is not calling . please help me
You can also user ListActivity instead of ListFragment.
It will behave like normal activity and you can find all the list related methods easily.
like this..,
public class MainActivity extends ListActivity {
oncreate() {
** code
ListView list = getListView();
**code
}
}
I think as you are using the custom list with you id "R.id.list" so no need to extend your fragment with listFragment extend with Fragment only.
other wise if you want use the listFragment then use like in XML
<ListView android:id="#id/android:list" android:layout_height="fill_parent"
android:layout_width="fill_parent" android:layout_weight="1.0"
android:layout_marginTop="2dip" android:scrollingCache="false"
android:clickable="true" android:cacheColorHint="#00000000"
android:focusable="true"
android:background="#drawable/listfocused"
android:dividerHeight="1dip" xmlns:android="http://schemas.android.com/apk/res/android"/>
in java get list as
ListView list = this.getListView();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
...
list=(Listview)findViewById(R.id.list);//i type here it shows an error
...
}
This is because you are trying to find the views in the onCreate() method; at this point of time, the fragment's layout has not yet been inflated, hence all findViewById() calls will return null.
You can only find the view after the layout is inflated, which is in onCreateView(). So override the onCreateView() method and call findViewById() and set the list's adapter there!
I am building a android-based app to implement twitter search function. The button click only works for the first. If i change the search term and click the button again, it fails to refresh. Anyone can give me a hint?
`public class TwitterSActivity extends Activity implements OnClickListener{
EditText etQuery;
Button btnQuery;
class Tweet{
public String username;
public String message;
public String image_url;
}
ArrayList<Tweet> tweets = new ArrayList<Tweet>();
#Override
public void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etQuery = (EditText) findViewById (R.id.et);
btnQuery = (Button) findViewById (R.id.btn);
btnQuery.setOnClickListener(this);
}
#Override
public void onClick(View v){
if(v.getId() == R.id.btn){
Toast.makeText(this, "Query submitted", Toast.LENGTH_LONG).show();
Getdata getdata = new Getdata();
String returned = null;
String searchTerm = etQuery.getText().toString();
try {
returned = getdata.getInternetData(searchTerm);
} catch (Exception e) {
e.printStackTrace();
}
try{
JSONObject jo = new JSONObject(returned);
JSONArray ja = jo.getJSONArray("results");
for(int i=0; i<ja.length(); i++){
JSONObject job = ja.getJSONObject(i);
Tweet tt = new Tweet();
tt.username = job.getString("from_user");
tt.message = job.getString("text");
tt.image_url = job.getString("profile_image_url");
tweets.add(tt);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data: "+e.toString());
}
ListView lv = (ListView) findViewById(R.id.listView1);
class FancyAdapter extends ArrayAdapter<Tweet> {
public FancyAdapter() {
super(TwitterSActivity.this, android.R.layout.simple_list_item_1, tweets);
}
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.listitem, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
holder.populatefrom(tweets.get(position));
return(convertView);
}
class ViewHolder {
public TextView username = null;
public TextView message = null;
public ImageView image = null;
ViewHolder(View listitem){
username = (TextView)listitem.findViewById(R.id.username);
message = (TextView)listitem.findViewById(R.id.message);
image = (ImageView)listitem.findViewById(R.id.avatar);
}
void populatefrom(Tweet t){
username.setText(t.username);
message.setText(t.message);
image.setImageBitmap(getBitmap(t.image_url));
}
}
}
FancyAdapter ar = new FancyAdapter();
lv.setAdapter(ar);
}
}
public Bitmap getBitmap(String bitmapUrl) {
try {
URL url = new URL(bitmapUrl);
return BitmapFactory.decodeStream(url.openConnection().getInputStream());
}
catch(Exception e) {return null;}
}`
Finally i figure it out, here is how I fix it:
I change ArrayList<Tweet> tweets = new ArrayList<Tweet>(); to final ArrayList<Tweet> tweets = new ArrayList<Tweet>();
and then move it under onClick() method. It works well without notifyDataSetChanged().