I have an activity with CustomAdapter ListView and TabLayout with three tabs TrainerTab1, TrainerTab2, TrainerTab3. While clicking on an item it should move to next page that is to TrainerTab1 Fragment.
I need to pass the id from ListView onClick() to fragment page. I have used Bundle to pass value but the items are not working. When I click on an item it's not responding and not showing any error.
My custom ListView Class is:
public class Trainer extends AppCompatActivity {
String tabUrl = "http://adoxsolutions.in/numuww/services/trainers";
private GridView gridView;
ArrayList<HashMap<String, String>> alist = new ArrayList<>();
private TrainAdapter adapter;
private ProgressDialog mprogress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trainer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
new Train().execute();
}
private class Train extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
mprogress = new ProgressDialog(Trainer.this);
mprogress.setMessage("Loading...");
mprogress.setIndeterminate(false);
mprogress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL(tabUrl);
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
connect.setRequestMethod("POST");
//
System.out.println("Response Code:" + connect.getResponseCode());
InputStream in = new BufferedInputStream(connect.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);
Log.d("VALUE:", response);
JSONObject obj = new JSONObject(response);
JSONArray jsArray = obj.optJSONArray("Trainers");
for (int k = 0; k < jsArray.length(); k++) {
HashMap<String, String> map = new HashMap<String, String>();
obj = jsArray.getJSONObject(k);
map.put("id", obj.getString("id"));
map.put("name", obj.getString("name"));
map.put("logo", obj.getString("img"));
alist.add(map);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
gridView = (GridView) findViewById(R.id.trainerGrid);
adapter = new TrainAdapter(getBaseContext(), alist);
gridView.setAdapter(adapter);
adapter.notifyDataSetChanged();
mprogress.dismiss();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.newc, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
return true;
}
else if(id == android.R.id.home){
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
class TrainAdapter extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();
public TrainAdapter(Context c, ArrayList<HashMap<String, String>> list){
context = c;
MyArr = list;
}
#Override
public int getCount() {
return MyArr.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.trainer_list, null);
}
TextView id= (TextView) convertView.findViewById(R.id.trainerId);
ImageView image = (ImageView) convertView.findViewById(R.id.trainerImage);
TextView text = (TextView) convertView.findViewById(R.id.trainerTexts);
try {
image.setImageBitmap(loadBitmap(MyArr.get(position).get("logo")));
text.setText(MyArr.get(position).get("name"));
id.setText(MyArr.get(position).get("id"));
if (((position - 9) / 3) % 9 == 0) {
ImageView adimg = (ImageView) convertView.findViewById(R.id.trainadBanner);
adimg.setScaleType(ImageView.ScaleType.FIT_XY);
adimg.getLayoutParams().height=150;
adimg.getLayoutParams().width=300;
adimg.setImageResource(R.drawable.mainad);
}
} catch (Exception e) {
e.printStackTrace();
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle h=new Bundle();
h.putString("id",MyArr.get(position).get("id"));
Fragment tt1=new TrainerTab1();
tt1.setArguments(h);
}
});
// }else{
// convertView=inflater.inflate(R.layout.trainer_list, parent,false);
// ImageView image= (ImageView) convertView.findViewById(R.id.trainerImage);
// TextView text= (TextView) convertView.findViewById(R.id.trainerTexts);
// try{
// image.setImageResource(R.drawable.ic_action_name);
// text.setText(MyArr.get(position).get("name"));
// if(position % 9 == 0){
// ImageView adimg= (ImageView) convertView.findViewById(R.id.trainadBanner);
// adimg.setImageResource(R.drawable.mainad);
// }
//
// } catch(Exception e){
// e.printStackTrace();
// }
return convertView;
}
private static final String TAG = "ERROR";
private static final int IO_BUFFER_SIZE = 4 * 1024;
private static Bitmap loadBitmap(String tabUrl) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(tabUrl).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + tabUrl);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
android.util.Log.e(TAG, "Could not close stream", e);
}
}
}
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
}
My tab fragment:
public class TrainerTab1 extends Fragment {
String turl="http://adoxsolutions.in/numuww/services/trainer";
TextView tname,tplace,tsex;
public TrainerTab1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView= inflater.inflate(R.layout.fragment_trainer_tab1, container, false);
final String tid=getArguments().getString("id");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
tname= (TextView) rootView.findViewById(R.id.trainerCourse);
tplace= (TextView) rootView.findViewById(R.id.trainerPlace);
tsex= (TextView) rootView.findViewById(R.id.trainerSex);
ImageView photo= (ImageView) rootView.findViewById(R.id.trainer_photo);
}
}
Inside the onClickListener
after adding the bundle to the fragment.
FragmentManager fragmentManager = Trainer.this.getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.someIDForYourFrameLayout, tt1).commit();
can you just ellaborate where to use this exactly. I mean I don't understand how to add id of fragment to transaction.add(R.id.someIDForYourFrameLayout, tt1).commit();
I tried like this:
Bundle h=new Bundle();
h.putString("id",MyArr.get(position).get("id"));
Fragment tt1=new TrainerTab1();
tt1.setArguments(h);
FragmentTransaction transact=getSupportFragmentManager().beginTransaction();
transact.add(R.id.trainerFragment,tt1).commit();
This is my fragment_trainer_tab_1 layout:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:scrollbarSize="1dp"
android:id="#+id/trainerFragment"
tools:context="com.example.anu.numuww.TrainerTab1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="12dp"
android:background="#color/blue">
<ImageView
android:id="#+id/trainer_photo"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_gravity="center"
android:contentDescription="#string/trainers"
android:src="#mipmap/ic_launcher"
android:layout_marginTop="20dp"/>
<TextView
android:id="#+id/trainerCourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:layout_marginTop="12dp"
android:textColor="#ffffff"
android:textSize="22sp"
android:gravity="center"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="#+id/trainerSex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_marginTop="5dp"
android:textColor="#ffffff"
android:textSize="17sp"
android:layout_gravity="center"/>
<TextView
android:id="#+id/trainerPlace"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textColor="#ffffff"
android:textSize="17sp"
android:gravity="center"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#F5F5F5"
android:gravity="center_horizontal"
android:padding="7dp"
android:orientation="horizontal">
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/global"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/messenger"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/google_plus"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/inst_detail"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/telegram"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/facebook"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/twitter"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/inst_instagram"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="14dp"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:text="About Trainer"
android:textColor="#color/blue"
android:textSize="19sp"
android:textStyle="bold"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/para"
android:layout_marginTop="4dp"
android:layout_marginBottom="2dp"
android:textSize="14sp"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
Related
I am trying to make an App that has two tabs in a ViewPager and each tab are fragments and should have a card View in a RecyclerView.I fetch the data from an API added it in an ArrayList. I dont see any error in my Adapter class and DailyMenuFrag. I will appreciate any kind of help
DailyMenuFrag.java
public class DailyMenuFrag extends Fragment {
private List<DailyData> data_list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
data_list = new ArrayList<>();
load_data();
View view = inflater.inflate(R.layout.fragment_daily_menu, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
DailyDataAdapter adapter = new DailyDataAdapter(getActivity(), data_list);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
TextView textView = (TextView) view.findViewById(R.id.tt);
textView.setText("hellp");
return view;
}
public void load_data() {
task.execute("http://yemekapp.kuarkdijital.com.tr/home.php");
}
AsyncTask<String, Void, String> task = new AsyncTask<String, Void, String>() {
#Override
protected String doInBackground(String... params) {
URL url;
HttpURLConnection URLConnection = null;
String current = "";
try {
url = new URL(params[0]);
URLConnection = (HttpURLConnection) url.openConnection();
URLConnection.connect();
InputStream inputStream = URLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
current += (char) data;
data = reader.read();
}
JSONObject dailyObject = null;
JSONObject popularObject = null;
JSONObject jsonObject = new JSONObject(current);
JSONObject banner = jsonObject.getJSONObject("banner");
String daily = jsonObject.getString("daily");
String popular = jsonObject.getString("popular");
JSONArray dailyArray = new JSONArray(daily);
JSONArray popularArray = new JSONArray(popular);
for (int i = 0; i < dailyArray.length(); i++) {
dailyObject = dailyArray.getJSONObject(i);
popularObject = popularArray.getJSONObject(i);
DailyData singleData = new DailyData(dailyObject.getInt("id"), dailyObject.getString("Servings"), dailyObject.getString("Title"), dailyObject.getString("CookTime"), dailyObject.getString("Image"));
data_list.add(singleData);
Log.i("data", data_list.size() + "");
}
}
catch (JSONException e) {
e.printStackTrace();
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
};
}
DailyDataAdapter.java
public class DailyDataAdapter extends RecyclerView.Adapter<DailyDataAdapter.ViewHolder> {
Context context;
List<DailyData> dailyDataList;
public DailyDataAdapter(Context context, List<DailyData> dailyDatas) {
this.context = context;
this.dailyDataList = dailyDatas;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card,parent,false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.title.setText(dailyDataList.get(position).getTitle());
holder.cookTime.setText(dailyDataList.get(position).getCookTime());
holder.servings.setText(dailyDataList.get(position).getServings());
//Image
Glide.with(context).load(dailyDataList.get(position).getImage_link()).into(holder.thumbnail);
}
#Override
public int getItemCount() {
return dailyDataList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView cookTime,servings,title;
public ImageView thumbnail;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
servings = (TextView) itemView.findViewById(R.id.servings);
cookTime = (TextView) itemView.findViewById(R.id.cooktime);
thumbnail = (ImageView) itemView.findViewById(R.id.thumbnail);
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null){
ViewPagger viewPagger = new ViewPagger();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_container,viewPagger);
transaction.commit();
}
}
}
ViewPAgger.java
public class ViewPagger extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_view_pagger,container,false);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.view_pager);
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tab);
viewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
#Override
public Fragment getItem(int position) {
return position == 0? new DailyMenuFrag():new PopularMenuFrag();
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return position == 0? "Daily":"Popular";
}
});
tabLayout.setupWithViewPager(viewPager);
return view;
}
}
ViewPagger.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.nejat.yemektarifiproject.ViewPagger">
<android.support.design.widget.TabLayout
android:id="#+id/tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="40dp">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</FrameLayout>
card.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:card_view="http://schemas.android.com/tools">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_margin="5dp"
android:elevation="3dp"
card_view:cardCornerRadius="0dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/thumbnail"
android:layout_width="match_parent"
android:layout_height="160dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
android:scaleType="fitXY" />
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/thumbnail"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp"
android:textColor="#4c4c4c"
android:textSize="15dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/title"
android:orientation="horizontal">
<TextView
android:id="#+id/servings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="10dp"
android:layout_weight="1"/>
<TextView
android:id="#+id/cooktime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/title"
android:layout_weight="1"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="10dp" />
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Fragment_DailyMenuFrag.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.nejat.yemektarifiproject.DailyMenuFrag">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
>
</android.support.v7.widget.RecyclerView>
<TextView
android:id="#+id/tt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</FrameLayout>
Add this
adapter.notifyDataSetChanged() in postExecute
I think you are forgetting to notify adapter about data change after you are getting data.
Declare your Adapter Global so you can call it from any where
DailyDataAdapter adapter = null;
and initialize it like this in your onCreateView
adapter = new DailyDataAdapter(getActivity(), data_list);
so call this notifyDataSetChanged() after doInBackground in your onPostExecute
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
adapter.notifyDataSetChanged();
}
this should work for you.
Hi in the below displaying all the images into gridview.gridview images displaying correctly.default gridview will give scroll option,Now Scrolling images it's not scrolling smoothly.
Can any one help me .how to scroll smoothly all the images like normal scrolling.this is my below code any where i did mistake please help me
java
public class GridFragment2 extends Fragment {
private static final String TAG = GridFragment.class.getSimpleName();
public static boolean isSelectedGrid2;
private GridView mGridView;
private ProgressBar mProgressBar;
private GridViewAdapter2 mGridAdapter;
private ArrayList<GridItem> mGridData;
private String FEED_URL = "http://javatechig.com/?json=get_recent_posts&count=45", searchKey;
String vv;
LinearLayout top;
View hr;
String catid;
SharedPreferences imgSh;
SharedPreferences p, got;
public GridFragment2() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_gridview2, container, false);
mGridView = (GridView)rootView.findViewById(R.id.gridView);
mProgressBar = (ProgressBar)rootView.findViewById(R.id.progressBar);
top = (LinearLayout)rootView.findViewById(R.id.top);
hr = rootView.findViewById(R.id.hr);
top.setVisibility(View.GONE);
hr.setVisibility(View.GONE);
imgSh = this.getActivity().getSharedPreferences("data", Context.MODE_APPEND);
p = this.getActivity().getSharedPreferences("gridData", Context.MODE_APPEND);
got = this.getActivity().getSharedPreferences("gotData", Context.MODE_APPEND);
//Initialize with empty data
mGridData = new ArrayList<>();
mGridAdapter = new GridViewAdapter2(rootView.getContext(), R.layout.grid_item_layout2, mGridData);
mGridView.setAdapter(mGridAdapter);
//Grid view click event
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//Get item at position
isSelectedGrid2=true;
String catalogueID = p.getString("SelectedCatalogueIdFromGrid1", "");
GridItem item = (GridItem) parent.getItemAtPosition(position);
Intent intent = new Intent(getActivity(), ImageGallery.class);
ImageView imageView = (ImageView) v.findViewById(R.id.grid_item_image);
int[] screenLocation = new int[2];
imageView.getLocationOnScreen(screenLocation);
SharedPreferences prefPosition=getActivity().getSharedPreferences("positionPref", Context.MODE_PRIVATE);
SharedPreferences.Editor positionEditor=prefPosition.edit();
positionEditor.putInt("position", position);
positionEditor.commit();
//Pass the image title and url to DetailsActivity
intent.putExtra("left", screenLocation[0]).
putExtra("top", screenLocation[1]).
putExtra("width", imageView.getWidth()).
putExtra("height", imageView.getHeight()).
putExtra("title", item.getTitle()).
putExtra("image", item.getImage()).
putExtra("catid", catalogueID).putExtra("position",position);
// Log.d("image", (item.getImage()).toString());
//Start details activity
getActivity().finish();
startActivity(intent);
}
});
//Start download
new AsyncHttpTask().execute(FEED_URL);
mProgressBar.setVisibility(View.VISIBLE);
return rootView;
}
//Downloading data asynchronously
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
#Override
protected Integer doInBackground(String... params) {
Integer result = 1;
parseResult();
return result;
}
#Override
protected void onPostExecute(Integer result) {
// Download complete. Lets update UI
if (result == 1) {
mGridAdapter.setGridData(mGridData);
} else {
Toast.makeText(getActivity().getBaseContext(), "Failed to fetch data!", Toast.LENGTH_SHORT).show();
}
//Hide progressbar
mProgressBar.setVisibility(View.GONE);
}
}
String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
private void parseResult() {
catid = p.getString("SelectedCatalogueIdFromGrid1", "");
int clickedPosn = p.getInt("clickedPosition", 0);
int count = p.getInt("numOfImagesInside"+catid+clickedPosn, 0);
Log.d("counterman-id", String.valueOf(count));
GridItem item;
for (int i = 0; i < count; i++) {
item = new GridItem();
item.setTitle("");
// item.setImage("file://" + Environment.getExternalStorageDirectory() + "/" + "thumbImage" + catid + i + ".jpg");
item.setImage("/data/data/com.example.adaptiz.tanishq/"+"thumbImage" + catid + i+".jpg");
// item.setImage(imgSh.getString("thumb" + i, ""));
mGridData.add(item);
}
}
Adapter
public class GridViewAdapter2 extends ArrayAdapter<GridItem> {
//private final ColorMatrixColorFilter grayscaleFilter;
private Context mContext;
private int layoutResourceId;
private ArrayList<GridItem> mGridData = new ArrayList<GridItem>();
public GridViewAdapter2(Context mContext, int layoutResourceId, ArrayList<GridItem> mGridData) {
super(mContext, layoutResourceId, mGridData);
this.layoutResourceId = layoutResourceId;
this.mContext = mContext;
this.mGridData = mGridData;
}
/**
* Updates grid data and refresh grid items.
*
* #param mGridData
*/
public void setGridData(ArrayList<GridItem> mGridData) {
this.mGridData = mGridData;
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
Typeface type_normal = Typeface.createFromAsset(getContext().getAssets(), "HelveticaNeue-Light.otf");
holder = new ViewHolder();
holder.titleTextView = (TextView) row.findViewById(R.id.grid_item_title);
holder.titleTextView.setTypeface(type_normal);
holder.download=(ImageView)row.findViewById(R.id.img);
holder.imageView = (ImageView) row.findViewById(R.id.grid_item_image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
GridItem item = mGridData.get(position);
holder.titleTextView.setText(Html.fromHtml(item.getTitle()));
File image = new File(item.getImage(), "");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[16*1024];
options.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), options);
// bitmap = Bitmap.createScaledBitmap(bitmap, 230, 230, true);
Log.d("the bitmap size", String.valueOf(bitmap.getWidth() + " " + bitmap.getHeight()));
holder.imageView.setImageBitmap(bitmap);
//bitmap=null;
// Picasso.with(mContext).load(item.getImage()).into(holder.imageView);
return row;
}
static class ViewHolder {
TextView titleTextView;
ImageView imageView;
ImageView download;
}
xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/toprel"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="30dp"
android:id="#+id/top"
android:orientation="horizontal"
android:layout_alignParentTop="true"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="30dp"
android:id="#+id/searchTitle"
android:layout_centerVertical="true"
android:text="Search"
android:textSize="15sp"
android:gravity="left"
android:layout_toRightOf="#+id/leftTitle"
android:layout_toEndOf="#+id/leftTitle" />
<EditText
android:inputType="text"
android:layout_centerVertical="true"
android:layout_width="200dp"
android:layout_height="30dp"
android:id="#+id/searchBox"
android:background="#drawable/searchbg2x"
android:layout_toRightOf="#+id/searchTitle"
android:layout_toEndOf="#+id/searchTitle"
android:layout_marginLeft="15dp"
android:singleLine="true"
android:imeOptions="actionSearch"
/>
</LinearLayout>
<View
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="1dp"
android:id="#+id/hr"
android:background="#000000"
android:layout_below="#id/top"
/>
<GridView
android:layout_below="#+id/hr"
android:id="#+id/gridView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:columnWidth="200dp"
android:gravity="center"
android:numColumns="4"
android:stretchMode="columnWidth"
android:verticalSpacing="5dp"
android:listSelector="#android:color/transparent"
android:clickable="true"
android:fastScrollEnabled="true"/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_centerInParent="true"
android:visibility="gone"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="20dp"
android:orientation="horizontal"
android:id="#+id/userlayout"
android:layout_alignParentTop="true"
android:visibility="gone"
android:layout_alignRight="#+id/gridView"
android:layout_alignEnd="#+id/gridView"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textSize="18sp"
android:id="#+id/userView"
android:text="username"
/>
<ImageView
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_width="20dp"
android:layout_height="10dp"
android:background="#drawable/icon"
/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="15sp"
android:layout_gravity="bottom"
android:layout_alignBottom="#+id/gridView"
android:layout_centerHorizontal="true" />
</RelativeLayout>
For that you have to use Image Loader to load image.
Refer below link for that.
http://www.androidhive.info/2012/07/android-loading-image-from-url-http/
I have retrieved data from a remote db using json and i have created a custom listView with this data. I have three TextView and one CheckBox and it works perfectly. So, i have added a button that would control selected items in list and eventually transfer selected item in another activity. Problem was solved as suggested,but if i scroll list, selected items losts status.I think it depends from horder or adapter. Can someone help me? Here is my code
public class Activity2 extends ActionBarActivity implements OnItemClickListener {
TextView txtLavorante;
TextView txtCodice;
Intent currIntent;
ListView list;
String myJSON;
ArrayList <String> checkedValue;
private ProgressDialog pDialog;
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "ID";
private static final String TAG_NAME = "Descrizione";
private static final String TAG_PRICE ="Costo";
private static final String TAG_TIME ="Durata_m";
JSONArray serv_man = null;
ArrayList<HashMap<String, String>> list_serv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity2);
list = (ListView) findViewById(R.id.listView);
currIntent = getIntent();
txtLavorante = (TextView) findViewById (R.id.Lavorante);
txtCodice = (TextView) findViewById(R.id.CodiceLavorante);
stampaValori();
list_serv = new ArrayList<HashMap<String,String>>();
getData();
}
#Override
public void onItemClick(AdapterView arg0, View v, int position, long arg3) {
CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox);
TextView tv = (TextView) v.findViewById(R.id.textView);
cb.performClick();
if (cb.isChecked()) {
checkedValue.add(tv.getText().toString());
Log.i("Btn Test",""+checkedValue);
} else if (!cb.isChecked()) {
checkedValue.remove(tv.getText().toString());
}
}
private void stampaValori() {
String pkg = getApplicationContext().getPackageName();
String tCode = "ID: " + currIntent.getStringExtra(pkg + "ID") + "\n";
String tNome = "Collaboratore scelto: " + currIntent.getStringExtra(pkg + "LAV") + "\n";
txtLavorante.setText(tNome);
txtCodice.setText(tCode);
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
serv_man = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<serv_man.length();i++){
JSONObject c = serv_man.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
String time = c.getString(TAG_TIME);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_ID,id);
persons.put(TAG_NAME,name);
persons.put(TAG_PRICE,price);
persons.put(TAG_TIME,time);
list_serv.add(persons);
}
list = (ListView) findViewById(R.id.listView);
list.setAdapter(new ListatoAdapter(Activity2.this, list_serv));
list.setOnItemClickListener(Activity2.this);
Button b= (Button) findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(Activity2.this, "TEST" + checkedValue, Toast.LENGTH_LONG).show();
Log.i ("Test ",""+checkedValue);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://www.example.com/.php");
// Depends on your web service
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();
// json is UTF-8 by default
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();
Log.i ("Servizi","serv:"+result);
} catch (Exception e) {
// Oops
Log.e("log_tag", "Error converting result " + e.toString());
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Activity2.this);
pDialog.setMessage("Obtaining list...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected void onPostExecute(String result){
pDialog.dismiss();
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_activity2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
ListatoAdapter
public class ListatoAdapter extends BaseAdapter {
private LayoutInflater layoutinflater;
private Context context;
ArrayList<HashMap<String, String>> dataList;
boolean [] itemChecked;
public ListatoAdapter(Context context, ArrayList<HashMap<String, String>> list_serv) {
super();
this.context = context;
this.dataList = list_serv;
itemChecked = new boolean [dataList.size()];
}
#Override
public int getCount() {
return dataList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.prenota_serv, null);
holder = new ViewHolder();
holder.service = (TextView)convertView.findViewById(R.id.et_serv);
holder.id = (TextView)convertView.findViewById(R.id.et_id);
holder.costo = (TextView)convertView.findViewById(R.id.et_costo);
holder.durata = (TextView)convertView.findViewById(R.id.et_dur);
holder.Ceck = (CheckBox)convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.service.setText(dataList.get(position).get("Descrizione"));
holder.id.setText(dataList.get(position).get("ID"));
holder.costo.setText(dataList.get(position).get("Costo"));
holder.durata.setText(dataList.get(position).get("Durata_m"));
holder.Ceck.setChecked(false);
if (itemChecked[position])
holder.Ceck.setChecked(true);
else
holder.Ceck.setChecked(false);
holder.Ceck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (holder.Ceck.isChecked())
itemChecked[position] = true;
else
itemChecked[position] = false;
Log.i("Adapter Test",""+itemChecked[position]);
}
});
return convertView;
}
class ViewHolder {
TextView service;
TextView id;
TextView costo;
TextView durata;
CheckBox Ceck;
}
}
Activity2.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="net.puntosys.www.customadaptertest.Activity2"
android:orientation="vertical">
<TextView android:text="hello_word" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Lavorante"
android:textStyle="bold"
android:textSize="22dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_gravity="right" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/CodiceLavorante"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:visibility="invisible" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView" />
prenota_serv.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Servizio:"
android:textSize="7pt"
android:id="#+id/tv_serv"
android:layout_alignBottom="#+id/tv_id"
android:layout_alignLeft="#+id/tv_id"
android:layout_alignStart="#+id/tv_id" />
<EditText
android:background="#android:drawable/editbox_background"
android:layout_height="wrap_content"
android:layout_width="190dip"
android:id="#+id/et_serv"
android:layout_gravity="center_horizontal"
android:textSize="7pt"
android:layout_alignBottom="#+id/et_id"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Costo Euro:"
android:textSize="7pt"
android:id="#+id/tv_cost"
android:layout_below="#+id/et_serv"
android:layout_alignLeft="#+id/tv_serv"
android:layout_alignStart="#+id/tv_serv" />
<EditText
android:background="#android:drawable/editbox_background"
android:layout_height="wrap_content"
android:layout_width="120dip"
android:id="#+id/et_costo"
android:layout_gravity="center_horizontal"
android:layout_below="#+id/et_serv"
android:layout_alignLeft="#+id/et_serv"
android:layout_alignStart="#+id/et_serv"
android:textSize="7pt" />
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Durata min:"
android:textSize="7pt"
android:id="#+id/tv_dur"
android:layout_below="#+id/et_costo"
android:layout_alignLeft="#+id/tv_cost"
android:layout_alignStart="#+id/tv_cost" />
<EditText
android:background="#android:drawable/editbox_background"
android:layout_height="wrap_content"
android:layout_width="70dip"
android:id="#+id/et_dur"
android:layout_gravity="center_horizontal"
android:textSize="7pt"
android:layout_alignTop="#+id/tv_dur"
android:layout_alignLeft="#+id/et_costo"
android:layout_alignStart="#+id/et_costo" />
<TextView
android:layout_marginTop="5dip"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Nr:"
android:layout_marginLeft="5dip"
android:layout_marginRight="9dip"
android:layout_alignParentLeft="true"
android:textSize="10pt"
android:id="#+id/tv_id"
android:visibility="invisible" />
<EditText
android:background="#android:drawable/editbox_background"
android:layout_height="wrap_content"
android:layout_width="70dip"
android:id="#+id/et_id"
android:layout_gravity="center_horizontal"
android:layout_alignTop="#+id/tv_id"
android:layout_alignLeft="#+id/et_serv"
android:layout_alignStart="#+id/et_serv"
android:enabled="false"
android:elegantTextHeight="false"
android:visibility="invisible" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="CheckBox"
android:layout_below="#+id/tv_dur"
android:layout_alignRight="#+id/et_serv"
android:layout_alignEnd="#+id/et_serv" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/textView"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/tv_dur"
android:layout_alignStart="#+id/tv_dur" />
when user select a check box, put its corresponding data to a list.and send the list in bundle on button click.and receive it on another activity with the key.
you need to create a list like.
ArrayList<HashMap<String, String>> list_selected;
public ListatoAdapter(Context context, ArrayList<HashMap<String, String>> list_serv) {
super();
this.context = context;
this.dataList = list_serv;
list_selected = new ArrayList<HashMap<String, String>>();
}
change the listener as.
holder.Ceck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
HashMap<String,String> data = dataList.get(position);
if(isChecked){
addToSelected(data);
}else{
removeSelected(data);
}
}
});
private void addToSelected(HashMap contact){
if(!list_selected.contains(contact))list_selected.add(contact);
}
private boolean removeSelected(HashMap contact){
return list_selected.remove(contact);
}
public ArrayList<HashMap<String, String>> getSelectedItems(){
return list_selected;
}
access the list from activity as adapter.getSelectedItems();.
declare it in your activity as global
ListatoAdapter adapter;
set adapter in this way.
adapter = new ListatoAdapter(Activity2.this, list_serv);
list.setAdapter(adapter);
and get the list in button Click as.
ArrayList<HashMap<String,String> list = adapter.getSelectedItems();
I know there are a lot of this kind of questions, but here is my problem.
I have a gallery with images and when I click, there is an ImageView to display the selected image in the gallery.
I also have a TextView witch displays a message.
When I click an image in the gallery, my ImageView gets the image and the TextTiew doesnt update its data.
I tried to put the code in a try/catch block and it doesn't throw any exception.
In my Log, the TextView has the exact text I have provided.
I tried using a new thread, but the result is the same: the TextView doesn't update, but my ImageView does.
I tried using runOnUiThread (as far as I know it's the same as a Thread), but still nothing.
I also changed from TextView to EditText, but I have the same problem.
Everyone says: "use a thread" - I did and it didn't work.
I ran out of ideas...
public class VODInterface extends Activity {
public static String[] values;
private static int itemPosition;
public static Activity thisActivity;
public Gallery gallery;
public ListView listView;
public LinearLayout MovieView;
public ImageView imgview;
public boolean submenus=false;
public boolean listviewVisibility = true;
private Handler handler = new Handler() ;
private SharedPreferences ep;
public ArrayList<VODObject> vod;
private ArrayList<Bitmap> tempimg;
private static int MovieSetNumber = 1;
public static int VODIndexPosition = 0;
public VODInterface(){
}
public void onDestroy(){
MainActivity.inChild=false;
super.onDestroy();
}
public void onCreate(Bundle bundle){
super.onCreate(bundle);
this.setContentView(R.layout.listview2);
ep = getSharedPreferences("Settings", 0);
listView = (ListView) this.findViewById(R.id.listView1);
MovieView = (LinearLayout) this.findViewById(R.id.movieView);
imgview = (ImageView)this.findViewById(R.id.imageView2);
// Defined Array values to show in ListView
values = new String[] { "A..Z",
"Category",
"Most Rated",
"Most Watched",
"Recently"
};
//this shows whitch movie should me load images
//we show always only 10 movies
MovieSetNumber = 1;
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
// ListView Item Click Listener
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
itemPosition = position;
handler.post(goDeep);
}
});
}
private Runnable goDeep = new Runnable(){
public void run(){
new goDeep().execute("");
}
};
class goDeep extends AsyncTask<String, String, String>{
ProgressDialog mProgressDialog = new ProgressDialog(VODInterface.this);
String result="";
boolean failLoadVOD=false;
protected void onPreExecute(){
mProgressDialog.setMessage(getString(R.string.downloading));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
//START check if servers are Ok
if(!Server.isOnline()){
Server.getAvailableServer();
Log.i("good", "");
}
if(!Server.isOnline()){
Log.i("WEW", "SERVERS are off");
return null;
}
//END check if servers are Ok
//START synchronize local database with online database
try{
if(ep.contains("downloaded")){
Log.i("localDatabase", "is full");
}
else{
Editor ed = ep.edit();
ed.putString("downloaded", "");
ed.commit();
//load data from database
if(!MainActivity.web.parseVODAndVODCategories()){
failLoadVOD=true;
}
}
}
catch(NullPointerException ee)
{
//lets go get datas from Tibodatabase
Editor ed = ep.edit();
ed.putString("downloaded", "");
ed.commit();
if(!MainActivity.web.parseVODAndVODCategories()){
failLoadVOD=true;
}
}
//END synchronize local database with online database
//START handle menus
if(!submenus) //MainMenu
{
if(itemPosition == 1){
//get all movies ordered by name
List<String> val = MainActivity.voddb.selectAllCategories();
values = new String[val.size()+1];
values[0] ="[...]";
for(int i=0;i<val.size();i++){
values[i+1] = val.get(i);
}
listviewVisibility = true;
}
else{
//show movies
listviewVisibility = false;
}
submenus = true;
}
else{
if(itemPosition == 0){
values = new String[] { "A..Z",
"Category",
"Most Rated",
"Most Watched",
"Recently"
};
submenus = false;
listviewVisibility = true;
}
else{
listviewVisibility = false;
}
}
//END handle menu
if(!listviewVisibility){
getData();
for(int i=0;i<vod.size();i++){
if(!FileExciste(vod.get(i).Icon)){
try{
Bitmap bmp ;
URL newurl = new URL(vod.get(i).Icon);
bmp = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
saveImageToSD(bmp,vod.get(i).Icon);
Log.i(i+"", "done");
}
catch(Exception e){
Log.i("exciste", "exciste");
}
}
else{
Log.i(i+"", "exciste");
}
}
}
runOnUiThread(new Runnable() {
#Override
public void run() {
if(!listviewVisibility){
listView.setVisibility(View.GONE);
MovieView.setVisibility(View.VISIBLE);
populateMovieView();
}
else{
ArrayAdapter<String> adapter = new ArrayAdapter<String>(VODInterface.this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
}
}
});
mProgressDialog.dismiss();
return "";
}
protected void onPostExecute(){
//start adding to cache
super.onPostExecute("");
}
}
private void getData(){
vod = new ArrayList<VODObject>();
for(int i=1;i<MainActivity.voddb.getVODCount()+1;i++){
vod.add(MainActivity.voddb.getVOD(i+""));
if(vod.get(i-1).Icon.contains(" ")){
vod.get(i-1).Icon = vod.get(i-1).Icon.replaceAll(" ", "%20");
Log.i("u korrigjua", vod.get(i-1).Icon);
}
}
}
private void populateMovieView(){
gallery = (Gallery) findViewById(R.id.gallery1);
GalleryImageAdapter gia= new GalleryImageAdapter(this,vod);
gallery.setAdapter(gia);
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, final int position, long id) {
// show the selected Image
/*here is the problem
*
*----------------------------/
*/
try{
LayoutInflater factory = getLayoutInflater();
View view = factory.inflate(R.layout.listview2, null);
EditText title = (EditText) view.findViewById(R.id.editText2);
title.setText(vod.get(position).title);
TextView desc = (TextView) view.findViewById(R.id.editText4);
desc.setText(vod.get(position).description);
Log.i("info", title.getText()+" "+desc.getText());
}
catch(Exception ee){
Log.i("info", ee.getMessage()+" nnn");
}
/*----------------------*/
try{
imgview.setImageBitmap(getImageFromSD(vod.get(position).Icon));
}
catch(Exception ee){
imgview.setImageResource(R.drawable.untitled);
}
}
});
}
public static Bitmap getImageFromSD(String url){
String path = Environment.getExternalStorageDirectory().toString();
File imgFile = new File(path+"/"+WebHelper.getFilenameFromUrl(url));
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
return myBitmap;
}
private void saveImageToSD(Bitmap bmp,String url) throws IOException {
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, "/"+WebHelper.getFilenameFromUrl(url));
fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName (),file.getName());
}
private boolean FileExciste(String url){
String path = Environment.getExternalStorageDirectory().toString();
File file = new File(path, "/"+WebHelper.getFilenameFromUrl(url));
return file.exists();
}
AND this is my XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/vod"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="top" >
<ListView
android:id="#+id/listView1"
android:layout_width="274dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:background="#color/translucent_bblack" >
</ListView>
<LinearLayout
android:id="#+id/movieView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/translucent_black"
android:orientation="vertical"
android:visibility="invisible" >
<Gallery
android:id="#+id/gallery1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:background="#color/translucent_bblack" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/imageView2"
android:layout_width="400dp"
android:layout_height="fill_parent"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#drawable/bord" />
<LinearLayout
android:id="#+id/MovieDesc"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:background="#color/translucent_bblack"
android:orientation="vertical" >
<TextView
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="30dp"
android:inputType="textPersonName"
android:text="Title:"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold" >
</TextView>
<TextView
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/editText3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="30dp"
android:text="Description:"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/editText4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/editText5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="60dp"
android:text="Duration:"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Declare your TextViews as field as like as ImageView---- "imgview" as follows...
public ImageView imgview;
public TextView title;
public TextView desc;
Initialize them in onCreate method as "imgview"
imgview = (ImageView)this.findViewById(R.id.imageView2);
title = (TextView) view.findViewById(R.id.editText2);
desc = (TextView) view.findViewById(R.id.editText4);
And update your gallery.setOnItemClickListener code as follows...
gallery.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, final int position, long id) {
title.setText(vod.get(position).title);
desc.setText(vod.get(position).description);
Log.i("info", title.getText()+" "+desc.getText());
imgview.setImageBitmap(getImageFromSD(vod.get(position).Icon));
}
});
dear
how to show text above customise list when i extends listactivity in my class file..the code is given below..
public class ServerResponce extends ListActivity {
private ArrayList<listobj> tobj = new ArrayList<listobj>();
static String str1;
PickUpLocation pickup=new PickUpLocation();
String pickuplocid= pickup.locationid;
String des=planner.description;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
**//here not work force close**
// ****setContentView(R.layout.list_item);
**// TextView tv = (TextView)findViewById(R.id.text1);
// tv.setText("i want to book a cab for 4 hr/40km from sushant lok to delhi air port at" +
// "4 pm today"
// +"the cab should be 4 seater compact cab with carriage");
// tv.setBackgroundColor(R.color.black);**
//
new MyTask().execute();
}
private class MyTask extends AsyncTask<Void, Void, Void>
{
private ProgressDialog progressDialog;
protected void onPreExecute() {
progressDialog = ProgressDialog.show(ServerResponce.this,
"", "Loading. Please wait...", true);
}
protected void onProgressUpdate(Integer... integer){
TextView tv = null;
tv.setText("gjh");
}
#Override
protected Void doInBackground(Void... arg0) {
try {
URL url = new URL("http://qrrency.com/mobile/j2me/cab/CabBookingStatus.php?requestid=666");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
int l=0;
int k=0;
StringBuffer buffer=new StringBuffer();
String str=" ";
while ((l=in.read())!=-1)
{
buffer.append((char)l);
str=str+(char)l;
}
in.close();
//
try {
JSONObject json = new JSONObject(str);
JSONArray nameArray=json.getJSONArray("bookings");
JSONObject[] cabListing=new JSONObject[nameArray.length()];
for (int i = 0; i < cabListing.length; i++) {
//JSONObject jSONObject = cabListing[i];
JSONObject jSONObject = nameArray.getJSONObject(i);
listobj tweet = new listobj();
JSONObject temp=jSONObject.getJSONObject("booking");
tweet.cabid = temp.getString("cabbookingid");
tweet.author =temp.getString("CabDriverName");
tweet.content =temp.getString("price");
tweet.cabrat=temp.getString("cabrating");
tobj.add(tweet);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e)
{
} catch (IOException e)
{
}
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
setListAdapter(new tListAdaptor(
ServerResponce.this, R.layout.list_item, tobj));
}
}
private class tListAdaptor extends ArrayAdapter<listobj> {
private ArrayList<listobj> tobj;
public tListAdaptor(Context context,int textViewResourceId,ArrayList<listobj> items)
{
super(context, textViewResourceId, items);
this.tobj = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
listobj o = tobj.get(position);
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
TextView bt1 = (TextView) v.findViewById(R.id.bottomtext1);
TextView bt2 = (TextView) v.findViewById(R.id.bottomtext2);
bt.setText("CAB NAME: " +o.author);
bt1.setText("CAB ID: " +o.cabid);
tt.setText("PRICE: " +o.content);
bt2.setText("CAB RATING: " +o.cabrat);
return v;
}
}
public String getItem(int position) {
// TODO Auto-generated method stub
return null;
}
}
xml file is...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RelativeLayout xmlns:android= "http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="6dip">
<TextView android:id="#+id/text" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="false"
android:text=" "
android:textStyle="italic"
/>
<Button
android:text="auto book"
android:id="#+id/autobook"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text"/>
<Button
android:text="cancel"
android:id="#+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text"
android:layout_toRightOf="#id/autobook"/>
</RelativeLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1">
<TextView android:id="#+id/toptext" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:text=" " />
<TextView android:id="#+id/bottomtext" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true" />
<TextView android:id="#+id/bottomtext1" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:text=" " />
<TextView android:id="#+id/bottomtext2" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true" />
</LinearLayout>
</LinearLayout>
You can set the header to by a textview. It will still be in the same format as a list view but the top item in the list view will be your text view
Your code is looking for R.id.text1
TextView tv = (TextView)findViewById(R.id.text1);
But your xml does not have any such id.
So you will get a null for tv.