I want to ask you, how to change programmatically the background color of LinearLayout in CardView when the text in TextView equals specify word or is empty. For example field1 getting string "red", the background of LinearLayout gets red. I'm fetching the data from JSON php file.
MainActivity.class
public class MainActivity extends AppCompatActivity {
private String jsonURL = "http://example.com/test.php";
private final int jsoncode = 1;
private RecyclerView recyclerView;
ArrayList<Model> ModelArrayList;
private Adapter adapter;
private static ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler);
fetchJSON();
}
#SuppressLint("StaticFieldLeak")
private void fetchJSON(){
new AsyncTask<Void, Void, String>(){
protected String doInBackground(Void[] params) {
String response="";
HashMap<String, String> map=new HashMap<>();
try {
HttpRequest req = new HttpRequest(jsonURL);
response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
} catch (Exception e) {
response=e.getMessage();
}
return response;
}
protected void onPostExecute(String result) {
//do something with response
onTaskCompleted(result,jsoncode);
}
}.execute();
}
public void onTaskCompleted(String response, int serviceCode) {
Log.d("responsejson", response.toString());
switch (serviceCode) {
case jsoncode:
if (isSuccess(response)) {
removeSimpleProgressDialog(); //will remove progress dialog
ModelArrayList = getInfo(response);
adapter = new Adapter(this,ModelArrayList);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
}else {
Toast.makeText(MainActivity.this, getErrorCode(response), Toast.LENGTH_SHORT).show();
}
}
}
public ArrayList<Model> getInfo(String response) {
ArrayList<Model> ModelArrayList = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("status").equals("true")) {
JSONArray dataArray = jsonObject.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
Model fieldsModel = new Model();
JSONObject dataobj = dataArray.getJSONObject(i);
fieldsModel.setField1(dataobj.getString("field1"));
fieldsModel.setField2(dataobj.getString("field2"));
ModelArrayList.add(fieldsModel);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return ModelArrayList;
}
public boolean isSuccess(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.optString("status").equals("true")) {
return true;
} else {
return false;
}
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
public String getErrorCode(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
return jsonObject.getString("message");
} catch (JSONException e) {
e.printStackTrace();
}
return "No data";
}
}
Adapter.class
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> {
private LayoutInflater inflater;
private ArrayList<Model> ModelArrayList;
public Adapter(Context ctx, ArrayList<Model> rogerModelArrayList){
inflater = LayoutInflater.from(ctx);
this.ModelArrayList = rogerModelArrayList;
}
#Override
public Adapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.rv_item, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(Adapter.MyViewHolder holder, int position) {
holder.field1.setText(ModelArrayList.get(position).getField1());
holder.field2.setText(ModelArrayList.get(position).getField2());
}
#Override
public int getItemCount() {
return ModelArrayList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView field1,field2;
public MyViewHolder(View itemView) {
super(itemView);
field1 = (TextView) itemView.findViewById(R.id.field1);
field2 = (TextView) itemView.findViewById(R.id.field2);
}
}
}
Model.class
public class Model {
private String field1, field2;
public String getField1() {
return field1;
}
public void setField1(String field1) {
this.field1 = field1;
}
public String getField2() {
return field2;
}
public void setField2(String field2) {
this.field2 = field2;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#cd15e6"
tools:context=".MainActivity">
** <android.support.v7.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginTop="15dp"/> **
</LinearLayout>
rv_item.xml
Here is the LinearLayout which i want to change the color LL_background
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
app:cardCornerRadius="5dp">
<LinearLayout
android:id="#+id/LL_background"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="100dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/field1"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginTop="5dp"
android:layout_weight="1"
android:text="ddd"
android:textColor="#000"
android:textStyle="bold" />
<TextView
android:id="#+id/field2"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:text="ddd"
android:textColor="#000"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Please check my project and share your ideas. Thanks a lot 😊
First of all add layout reference to ViewHolder
class MyViewHolder extends RecyclerView.ViewHolder{
TextView field1,field2;
LinearLayout layout;
public MyViewHolder(View itemView) {
super(itemView);
field1 = (TextView) itemView.findViewById(R.id.field1);
field2 = (TextView) itemView.findViewById(R.id.field2);
layout = itemView.findViewById(R.id.LL_background);
}
}
Then check Field1 and set color
#Override
public void onBindViewHolder(Adapter.MyViewHolder holder, int position) {
holder.field1.setText(ModelArrayList.get(position).getField1());
holder.field2.setText(ModelArrayList.get(position).getField2());
if(ModelArrayList.get(position).getField1().equalIgnoreCase("red")
holder.layout.setBackgroundColor(Color.RED)
}
red is not recognizable in android. Either you have to handle it manually like above or you can send the corresponding #code of color from server and handle it like below:
holder.layout.setBackgroundColor(Color.parseColor("#ff0000"));
You can change layout instead color. Create different layouts that has different background color or different design. Then do this.
#Override
public Adapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.rv_item, parent, false);
if(ModelArrayList.get(position).getField1().equalIgnoreCase("red")
view = inflater.inflate(R.layout.anotherLayout, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
Related
I am trying to make an Activity which will hold all the recents screen in my app not in the android device.
The idea it is to create the recents view like in android.
I do not have for the moment an idea how to do that. I have searched in the official site of android but didn't get what I want.
I have some activities which there is declared WebView and I want to take title, url and the view of that Url and to save to show at VisualHistory.
The design I am able to do I have achieved but I do not know how to show the recents screen or views.
The color of the background should based from url.
If someone don't understand something let me know.
Below you can find a photo which will show what I am trying to do, I have copied this photo from another app.
I have planned these steps to follow to achieve that.
In the Pojo.class and in db it is not defined the image which will be shown in the cardview because I do not know how to achieve that.
I want the background which for the moment in blue to be depended from the url color. Is it any way to get the color of the url ?
Create a POJO.class
Create a DB which will hold this data
Create an Adapter
Create a Fragment
I have a Log here which shows me the items.
[VisualHistoryItem{id=109, title='Wikipedia, the free encyclopedia', url='https://en.m.wikipedia.org/w/index.php?title=Main_Page'}, VisualHistoryItem{id=112, title='', url='https://mail.google.com/'}, VisualHistoryItem{id=113, title='Gmail – kostenloser Speicherplatz und E-Mails von Google', url='https://www.google.com/intl/de/gmail/about/#'}]
This saves a visual history item.
mVisualHistory.setUrl(url);
mVisualHistory.setTitle(view.getTitle());
Bitmap topass= getSnapshoot.takeScreenShot(BookmarkActivity.this);
try {
String filename = mVisualHistory.getId()+".png";
FileOutputStream stream = BookmarkActivity.this.openFileOutput(filename, Context.MODE_PRIVATE);
topass.compress(Bitmap.CompressFormat.PNG, 100, stream);
stream.close();
topass.recycle();
} catch (Exception e) {
e.printStackTrace();
}
mVisualRepository.insertNoteTask(mVisualHistory);
I have created an Activity code is below.
public class ActivityTabs extends AppCompatActivity implements View.OnClickListener {
private PopupMenu mPopupMenu;
private FrameLayout settings;
private FrameLayout frameLayout;
private LinearLayout linearLayout;
private ImageView incognito;
private TextView textOfHistory;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs);
findViewById(R.id.vgGoMain).setOnClickListener(this);
findViewById(R.id.vgAdd).setOnClickListener(this);
settings = findViewById(R.id.vgSettingsHis);
linearLayout = findViewById(R.id.layoutEmptyVisHistory);
settings.setOnClickListener(this);
textOfHistory = findViewById(R.id.tvEmptyHistory);
FragmentVisualHistoryVertical newFragment = new FragmentVisualHistoryVertical();
getSupportFragmentManager().beginTransaction().add(R.id.frameLayoutVisHistory, newFragment).commit();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frameLayoutVisHistory, newFragment)
.commit();
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.vgGoMain:
finish();
return;
case R.id.vgAdd:
Intent intent = new Intent(this, ActivitySearchEngine.class);
startActivity(intent);
finish();
return;
case R.id.vgSettingsHis:
showMenuSettings();
return;
default:
break;
}
}
public void showMenuSettings() {
mPopupMenu = new PopupMenu(this, settings);
final MenuInflater menuInflater = mPopupMenu.getMenuInflater();
menuInflater.inflate(R.menu.history_settings, mPopupMenu.getMenu());
mPopupMenu.show();
}
}
And this is the XML for this Activity.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/historyEmptyBack"
android:gravity="center_horizontal"
android:orientation="vertical">
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout
android:id="#+id/frameLayoutVisHistory"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="#dimen/bottomPanelHeight"></FrameLayout>
<LinearLayout
android:id="#+id/layoutEmptyVisHistory"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:visibility="gone">
<TextView
android:id="#+id/tvEmptyHistoryTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="#dimen/common_24dp"
android:gravity="center_horizontal"
android:lineSpacingExtra="3.0sp"
android:text="#string/VHVEmptyTite"
android:textColor="#color/historyEmptyTitle"
android:textSize="22.0sp" />
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="48.0dip"
android:layout_weight="1.0">
<LinearLayout
android:id="#+id/horizontalEmpty"
style="#style/LayoutEmptySmile"
android:layout_width="#dimen/visual_history_element_width"
android:layout_height="#dimen/visual_history_element_height"
android:orientation="vertical">
<ImageView
style="#style/EmptyHistorySmile"
android:src="#drawable/vh_smile_gray" />
<TextView
style="#style/EmptyHistoryText"
android:layout_marginTop="#dimen/common_16dp"
android:gravity="center_horizontal"
android:paddingLeft="#dimen/common_16dp"
android:paddingRight="#dimen/common_16dp"
android:text="#string/VHVEmptyDesc" />
</LinearLayout>
<LinearLayout
android:id="#+id/verticalEmpty"
style="#style/LayoutEmptySmile"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="#dimen/common_24dp"
android:layout_marginRight="#dimen/common_24dp"
android:orientation="horizontal"
android:paddingLeft="#dimen/common_16dp"
android:paddingTop="#dimen/common_16dp"
android:paddingRight="#dimen/common_16dp"
android:paddingBottom="#dimen/common_16dp">
<ImageView
style="#style/EmptyHistorySmile"
android:src="#drawable/vh_smile_gray" />
<TextView
style="#style/EmptyHistoryText"
android:layout_width="wrap_content"
android:gravity="left"
android:paddingLeft="#dimen/common_16dp"
android:text="#string/VHVEmptyDesc" />
</LinearLayout>
<LinearLayout
android:id="#+id/layoutIncognito"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/bottomPanelHeight"
android:visibility="visible">
<LinearLayout
android:id="#+id/layoutEmptyDesc"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="#dimen/common_16dp"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="#+id/ivEmptyHistory"
android:layout_width="#dimen/history_private"
android:layout_height="#dimen/history_private"
android:src="#drawable/incognito_icon_history" />
<TextView
android:id="#+id/tvEmptyHistory"
style="#style/EmptyHistoryText"
android:layout_marginTop="#dimen/common_16dp"
android:gravity="center_horizontal"
android:paddingLeft="#dimen/common_16dp"
android:paddingRight="#dimen/common_16dp"
android:text="#string/SVSearchPrivateMode"
android:textColor="#color/historyTextColor"
android:textSize="#dimen/common_18sp" />
</LinearLayout>
</LinearLayout>
</FrameLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#color/historyEmptyBack"
android:gravity="bottom"
android:orientation="vertical"
android:paddingLeft="2.0dip"
android:paddingRight="2.0dip">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<LinearLayout style="#style/VisHistoryMenuSideLayout">
<FrameLayout
android:id="#+id/vgGoMain"
style="#style/VisHistoryFrLayoutMenu"
android:paddingRight="14.0dip">
<TextView
style="#style/VisHistoryTvMenu"
android:text="#string/VHVHomeBarButtonItemTitle" />
</FrameLayout>
<View style="#style/VisHistoryEmptyView" />
</LinearLayout>
<FrameLayout
android:id="#+id/vgAdd"
style="#style/VisHistoryFrLayoutMenu">
<ImageView
style="#style/VisHistoryMenuIv"
android:scaleX="0.8"
android:scaleY="0.8"
android:src="#drawable/newtab_button" />
</FrameLayout>
<LinearLayout style="#style/VisHistoryMenuSideLayout">
<View style="#style/VisHistoryEmptyView" />
<FrameLayout
android:id="#+id/vgTrash"
style="#style/VisHistoryFrLayoutMenu">
<ImageView
style="#style/VisHistoryMenuIv"
android:scaleX="1.3"
android:scaleY="1.3"
android:src="#drawable/trash" />
</FrameLayout>
<View style="#style/VisHistoryEmptyView" />
<FrameLayout
android:id="#+id/vgSettingsHis"
style="#style/VisHistoryFrLayoutMenu"
android:paddingLeft="0.0dip"
android:paddingRight="0.0dip">
<android.support.v7.widget.AppCompatImageView
style="#style/VisHistoryMenuIv"
android:layout_gravity="right"
app:srcCompat="#drawable/ic_dots_vertical"
tools:ignore="VectorDrawableCompat" />
</FrameLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</FrameLayout>
</LinearLayout>
This is another Fragment
Here will show of the list
public class FragmentVisualHistoryVertical extends FragmentVisualHistory implements VisualRecyclerAdapter.OnVisualHistoryItemListener {
public View paramView;
private VisualRecyclerAdapter mVisualHistoryRecyclerAdapter;
private RecyclerView mRecyclerView;
private VisualHistoryRepository getmNoteRepository;
private ArrayList<VisualHistoryItem> mVisualHistoryItems = new ArrayList<>();
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
paramView = inflater.inflate(R.layout.fragment_vis_history_vertical, container, false);
mRecyclerView = paramView.findViewById(R.id.rvWebHistory);
initRecyclerView();
getmNoteRepository = new VisualHistoryRepository(getActivity());
retrieveVisualHistory();
return paramView;
}
private void initRecyclerView(){
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(linearLayoutManager);
linearLayoutManager.setReverseLayout(true);
new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(mRecyclerView);
mVisualHistoryRecyclerAdapter = new VisualRecyclerAdapter(mVisualHistoryItems, this, mContext);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mRecyclerView.getContext(),
linearLayoutManager.getOrientation());
mRecyclerView.addItemDecoration(dividerItemDecoration);
mRecyclerView.setAdapter(mVisualHistoryRecyclerAdapter);
}
private void retrieveVisualHistory() {
getmNoteRepository.retrieveVisualHistoryTask().observe(this, new Observer<List<VisualHistoryItem>>() {
#Override
public void onChanged(#Nullable List<VisualHistoryItem> item) {
if(mVisualHistoryItems.size() > 0){
mVisualHistoryItems.clear();
}
if(item != null){
mVisualHistoryItems.addAll(item);
}
mVisualHistoryRecyclerAdapter.notifyDataSetChanged();
}
});
}
#Override
public void onItemClicked(int position) {
}
private void deleteNote(VisualHistoryItem item) {
mVisualHistoryItems.remove(item);
mVisualHistoryRecyclerAdapter.notifyDataSetChanged();
getmNoteRepository.deleteVisualHistoryTask(item);
}
ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
deleteNote(mVisualHistoryItems.get(viewHolder.getAdapterPosition()));
}
};
}
This is the XML.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:aapt="http://schemas.android.com/aapt" android:id="#+id/rvWebHistory" android:layout_width="match_parent" android:layout_height="match_parent"/>
This is the room db
#Database(entities = {VisualHistoryItem.class}, version = 1)
public abstract class VisualHistoryDB extends RoomDatabase {
private static final String DATABASE_NAME = "visualHistory_db";
private static VisualHistoryDB instance;
public static VisualHistoryDB getInstance(final Context context) {
if (instance == null) {
instance = Room.databaseBuilder(
context.getApplicationContext(),
VisualHistoryDB.class,
DATABASE_NAME
).build();
}
return instance;
}
public abstract VisualHistoryDao getVisualHistoryDao();
}
The room db Dao
#Dao
public interface VisualHistoryDao {
#Insert
long[] insertVisualHistory(VisualHistoryItem... visualHistoryItems);
#Query("SELECT * FROM visualHistory")
LiveData<List<VisualHistoryItem>> getVisualHistory();
#Delete
int delete(VisualHistoryItem... visualHistoryItems);
}
This is the pojo.class
#Entity(tableName = "visualHistory")
public class VisualHistoryItem implements Parcelable {
#PrimaryKey(autoGenerate = true)
private int id;
#ColumnInfo(name = "title")
private String title;
#ColumnInfo(name = "url")
private String url;
public VisualHistoryItem(int id, String title, String url) {
this.id = id;
this.title = title;
this.url = url;
}
#Ignore
public VisualHistoryItem() {
}
protected VisualHistoryItem(Parcel in) {
id = in.readInt();
title = in.readString();
url = in.readString();
}
public static final Creator<VisualHistoryItem> CREATOR = new Creator<VisualHistoryItem>() {
#Override
public VisualHistoryItem createFromParcel(Parcel in) {
return new VisualHistoryItem(in);
}
#Override
public VisualHistoryItem[] newArray(int size) {
return new VisualHistoryItem[size];
}
};
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
#Override
public String toString() {
return "VisualHistoryItem{" +
"id=" + id +
", title='" + title + '\'' +
", url='" + url + '\'' +
'}';
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeInt(id);
parcel.writeString(title);
parcel.writeString(url);
}
}
And this is the Adapter.
public class VisualRecyclerAdapter extends RecyclerView.Adapter<VisualRecyclerAdapter.ViewHolder> {
private ArrayList<VisualHistoryItem> mVisualHistoryItem = new ArrayList<>();
private OnVisualHistoryItemListener mItemListener;
private final Context context;
public VisualRecyclerAdapter(ArrayList<VisualHistoryItem> mVisualHistoryItem, OnVisualHistoryItemListener mItemListener, Context context) {
this.context = context;
this.mVisualHistoryItem = mVisualHistoryItem;
this.mItemListener = mItemListener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_visual_history, viewGroup, false);
return new ViewHolder(view, mItemListener);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
Resources res = viewHolder.itemView.getContext().getResources();
viewHolder.visFragmentMain.setBackgroundColor(res.getColor(R.color.blue_text));
viewHolder.tvPageUrl.setText(mVisualHistoryItem.get(i).getUrl());
viewHolder.tvPageName.setText(mVisualHistoryItem.get(i).getTitle());
Bitmap bmp = null;
String filename = mVisualHistoryItem.get(i).getId()+".png";
try {
FileInputStream is = context.openFileInput(filename);
bmp = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
if (bmp!=null) {
BitmapDrawable ob = new BitmapDrawable(context.getResources(), bmp);
viewHolder.ivVisualHistory.setBackground(ob);
}
}
#Override
public int getItemCount() {
return mVisualHistoryItem.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView ivVisualHistory;
OnVisualHistoryItemListener itemListener;
TextView tvPageName, tvPageUrl;
RelativeLayout visFragmentMain;
CardView cardView;
public ViewHolder(#NonNull View itemView, OnVisualHistoryItemListener mItemListener) {
super(itemView);
itemListener = mItemListener;
ivVisualHistory = itemView.findViewById(R.id.ivVisualHistory);
visFragmentMain = itemView.findViewById(R.id.visFragmentMain);
tvPageName = itemView.findViewById(R.id.tvPageName);
tvPageUrl = itemView.findViewById(R.id.tvPageUrl);
cardView = itemView.findViewById(R.id.cardView);
}
#Override
public void onClick(View v) {
itemListener.onItemClicked(getAdapterPosition());
}
}
public interface OnVisualHistoryItemListener {
void onItemClicked(int position);
}
}
This is what I am trying to achieve.
This is my actual view.
Well you can get the favicon of the website and use the Palette class of android explained here to get the prominent color of the url and if you want to get the snapshot you can save the snapshot and save instance data before launching another activity. To take snapshot you can use takesnapshot meathod after creating util class, code as follows:
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.view.View;
class Util {
static Bitmap takeScreenShot(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
//Find the screen dimensions to create bitmap in the same size.
int width = activity.getWindowManager().getDefaultDisplay().getWidth();
int height = activity.getWindowManager().getDefaultDisplay().getHeight();
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
return b;
}
}
in your activity use it to save it to png file as follows:
Bitmap topass=Util.takeScreenShot(this);
try {
//Write file
String filename = "bitmap.png";
FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
topass.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
topass.recycle();
} catch (Exception e) {
e.printStackTrace();
}
Instead of using name "bitmap.png" use your "id.png"(String.valueof(id)+".png") as you have put int "id" name in your db. You can save screenshot of every activity with its id and whenever you build the cardview of it, show the screenshot by the name of "id.png". To show screenshot, you can use
Bitmap bmp = null;
String filename = String.valueof(getId())+".png";
try {
FileInputStream is = this.openFileInput(filename);
bmp = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
if(bmp!=null)
{
ConstraintLayout cl =findViewById(R.id.shopbk); //it can be your any view
BitmapDrawable ob = new BitmapDrawable(getResources(), bmp);
cl.setBackground(ob); /* you should use glide here to show bitmap drawable as your preview will be very small as compared to screenshot actual size*/
}
and as far as getting the color (you said the link is not working) is concerned you can get firstly the bitmap using
try {
URL url = new URL("http://..somepath url../favicon.ico");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch(IOException e) {
System.out.println(e);
}
and then use palette to extract the color using
Palette.generateAsync(image, new Palette.PaletteAsyncListener() {
public void onGenerated(Palette palette) {
// Do something with colors...
}
});
for this you will need to implement one dependancy
dependencies {
...
compile 'com.android.support:palette-v7:21.0.+'
}
I'm building an application , i have created a listview where i can retreive data from mysql database. IT's working very good.
But the problem is that i want to load the data of each item in another activity with details from the database .
Can anyone help me please ?? i'm really stuck , i don't how to do it.
This is my java code :
public class GererUtilisateur extends AppCompatActivity
{
private ArrayList<ClassListItem> itemArrayListU;
private MyAppAdapterU myAppAdapterU;
private ListView listViewU;
private boolean succes = false;
private static final String DB_URL="jdbc:mysql://192.168.1.2/test3_10032018";
private static final String USER="";
private static final String PASS="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gerer_utilisateur);
listViewU=(ListView) findViewById(R.id.listuser);
itemArrayListU = new ArrayList<ClassListItem>();
SynDataU orderData = new SynDataU();
orderData.execute();
}
private class SynDataU extends AsyncTask<String,String,String> {
String msg="";
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... strings) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(DB_URL, USER, PASS);
if (connection == null) {
succes = false;
} else {
String query = "SELECT id_utilisateur , nom , prenom , fonction FROM utilisateur";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) {
while (rs.next()) {
try {
itemArrayListU.add(new ClassListItem(rs.getInt("id_utilisateur"), rs.getString("nom"), rs.getString("prenom") , rs.getString("fonction")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
succes = true;
}
}
}catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
succes = false;
}
return msg;
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(GererUtilisateur.this,"Synchronising","ListView Loading !!!",true);
}
#Override
protected void onPostExecute(String s) {
progressDialog.dismiss();
if (succes = false){
}else{
try{
myAppAdapterU = new MyAppAdapterU(itemArrayListU,GererUtilisateur.this);
listViewU.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listViewU.setAdapter(myAppAdapterU);
}catch (Exception ex){
}
}
}
}
public class MyAppAdapterU extends BaseAdapter {
public class ViewHolder{
TextView id;
TextView prenom;
TextView nom;
TextView fonction;
}
public List<ClassListItem> decisionList;
public Context context;
ArrayList<ClassListItem> arrayList;
private MyAppAdapterU(List<ClassListItem> apps,Context context){
this.decisionList= apps;
this.context=context;
arrayList= new ArrayList<ClassListItem>();
arrayList.addAll(decisionList);
}
#Override
public int getCount() {
return decisionList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ViewHolder viewHolder = null;
if(rowView==null){
LayoutInflater inflater = getLayoutInflater();
rowView= inflater.inflate(R.layout.list_content,parent,false);
viewHolder= new ViewHolder();
viewHolder.id=rowView.findViewById(R.id.tv_id);
viewHolder.nom=rowView.findViewById(R.id.tv_nom);
viewHolder.prenom=rowView.findViewById(R.id.tv_prenom);
viewHolder.fonction=rowView.findViewById(R.id.tv_fonc);
rowView.setTag(viewHolder);
}else
{
viewHolder=(ViewHolder) convertView.getTag();
}
viewHolder.id.setText(decisionList.get(position).getId()+"");
viewHolder.nom.setText(decisionList.get(position).getNom()+"");
viewHolder.prenom.setText(decisionList.get(position).getPrenom()+"");
viewHolder.fonction.setText(decisionList.get(position).getFonction()+"");
return rowView;
}
}
public void ajout(View view){
Intent i = new Intent(getApplicationContext(),AjouterUtil.class);
startActivity(i);
}
And this is my xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mootaz.mobilevoting.GererUtilisateur"
android:background="#drawable/bg">
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="fill_parent"
android:layout_height="400dp"
android:layout_alignParentStart="true"
android:layout_below="#+id/btn_ajout"
android:layout_marginTop="25dp"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
card_view:cardCornerRadius="10dp"
card_view:cardBackgroundColor="#color/BlueGrayLight"
>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listuser"/>
</android.support.v7.widget.CardView>
<android.support.v7.widget.AppCompatButton
android:id="#+id/btn_ajout"
style="#style/RaisedButtonA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="22dp"
android:layout_marginTop="98dp"
android:onClick="ajout"
android:text="Ajouter Utilisateur" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="41dp"
android:fontFamily="cursive"
android:text="Gerer les utilisateurs"
android:textColor="#color/primary"
android:textSize="28dp"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"/>
</RelativeLayout>
In your FirstActivity add this.
listViewU.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Movie movie = movieList.get(position);
// retrieve from movie whatever you want
movie.getName();
Toast.makeText(getApplicationContext(),"Name: "+movie.getName(),Toast.LENGTH_LONG).show();
// creaet intent and add data to it.
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("name",movie.getName());
startActivity(intent);
}
});
In your second activity get data like this.
// get info from intent
Bundle bundle = getIntent().getExtras();
String name = bundle.getString("name");
I have a recycle view which populates data from a server, the components inside are a textView and a Switch. The server can return n number of data. How can i set a unique id to the Switch2 when I am populating the data, because later I will need to set a listener to the Switches, My server actually returns a unique id but I'm not so sure on how to set it to the Switch2, or is there any alternate parameters that can be used to identify the Switch?
layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:layout_editor_absoluteY="81dp">
<android:android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="1dp"
card_view:cardUseCompatPadding="true"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Switch
android:id="#+id/switch2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left|center_vertical"
android:paddingLeft="5dip"
android:layout_marginTop="16dp"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="254dp" />
<TextView
android:id="#+id/user_set_light_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:fontFamily="sans-serif"
android:text="TextView"
android:textSize="20dp"
tools:layout_editor_absoluteX="27dp"
tools:layout_editor_absoluteY="23dp" />
</RelativeLayout>
</android:android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>
adapter
public class populateLights_adapter extends RecyclerView.Adapter<populateLights_adapter.ViewHolder> {
private List<populate_lights> listItems;
private Context context;
public populateLights_adapter(List<populate_lights> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.addlight_items, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
populate_lights listItem = listItems.get(position);
holder.lightText.setText(listItem.getLightName());
holder.status.setChecked(listItem.getState());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView lightText;
public Switch status;
public ViewHolder(View itemView) {
super(itemView);
lightText = (TextView) itemView.findViewById(R.id.user_set_light_id);
status = (Switch) itemView.findViewById(R.id.switch2);
}
}
}
java class
public class populate_lights {
private String lightName;
private boolean state;
public populate_lights(String lightName, boolean state){
this.lightName = lightName;
this.state = state;
}
public String getLightName(){
return lightName;
}
public boolean getState(){
return state;
}
}
main
public class lightsControl extends Fragment {
View myView;
public static final String URL = "serverurl.com";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<populate_lights> listItems;
private Switch mySwitch;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.lightscontrol, container, false);
recyclerView = (RecyclerView) myView.findViewById(R.id.lightsView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
listItems = new ArrayList<>();
loadData();
adapter = new populateLights_adapter(listItems, myView.getContext());
recyclerView.setAdapter(adapter);
return myView;
}
private void loadData(){
final ProgressDialog progressDialog = new ProgressDialog(myView.getContext());
progressDialog.setMessage("Loading");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
Snackbar mySnackbar = Snackbar.make(myView, "Data Fetched!", Snackbar.LENGTH_SHORT);
mySnackbar.show();
Log.v("DATA_RESPONSE", response);
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("lightData");
for(int i=0;i<array.length();i++){
JSONObject obj = array.getJSONObject(i);
Log.v("LIGHT ID ", "index=" + obj.getString("LightID"));
Log.v("Value ", "index=" + obj.getBoolean("Value"));
populate_lights popLights = new populate_lights(
obj.getString("LightID"), //unique id
obj.getBoolean("Value") //value returns true, or false
);
listItems.add(popLights);
}
adapter = new populateLights_adapter(listItems, myView.getContext());
recyclerView.setAdapter(adapter);
}
catch(Exception e){
e.printStackTrace();
}
}},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Snackbar mySnackbar = Snackbar.make(myView, "Oops, there was an error communicating with our server, try again", Snackbar.LENGTH_SHORT);
mySnackbar.show();
Log.v("LoginFormERROR", "index=" + error);
progressDialog.dismiss();
}
}
)
};
RequestQueue requestQueue = Volley.newRequestQueue(myView.getContext());
requestQueue.add(stringRequest);
}
public void showErrorAlert(){
AlertDialog.Builder builder1 = new AlertDialog.Builder(myView.getContext());
builder1.setMessage("Opps, something went wring");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Main Menu",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
getActivity().onBackPressed();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
screenshot
See if this code prints the right position in the logs. Put this inside the constructor of the view holder in the adapter class:
status.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
Log.d("Position: ", String.valueOf(getLayoutPosition()));
}
});
I want data from my JSON to be displayed in another Activity inside a ListView with 3 columns. I made a Layout for my ListView but that's all
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:descendantFocusability="afterDescendants"
android:orientation="vertical"
android:paddingBottom="15dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingTop="15dp">
<TextView
android:id="#+id/txtViewNumarCumparator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="NumarCumparator" />
<TextView
android:id="#+id/listaProduse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtViewNumarCumparator"
android:layout_marginTop="10dp"
android:text="NumarProduse" />
<TextView
android:id="#+id/sumaProduse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="SumaProdsue" />
I have a JSONObject which retrieves data like this :
{"dataCurenta":"11-08-2017",
"produseSelectate":3,
"pretTotal":605
}
Here is the code :
JSONObject json = new JSONObject();
try {
json.put("dataCurenta", getDate(calendarData.getTimeInMillis()));
} catch (JSONException e) {
e.printStackTrace();
}
try {
json.put("produseSelectate", listaProdusePreview.getAdapter().getCount());
} catch (JSONException e) {
e.printStackTrace();
}
try {
json.put("pretTotal", totalPrice);
} catch (JSONException e) {
e.printStackTrace();
}
try {
json.put("numarVanzare", numarVanzare);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("LISTA", json.toString());
Adapter :
public class CardArrayAdapter extends ArrayAdapter<Card> {
private static final String TAG = "CardArrayAdapter";
private List<Card> cardList = new ArrayList<Card>();
static class CardViewHolder {
TextView line1;
TextView line2;
TextView line3;
}
public CardArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public void add(Card object) {
cardList.add(object);
super.add(object);
}
#Override
public int getCount() {
return this.cardList.size();
}
#Override
public Card getItem(int index) {
return this.cardList.get(index);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CardViewHolder viewHolder;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.list_item_card, parent, false);
viewHolder = new CardViewHolder();
viewHolder.line1 = (TextView) row.findViewById(R.id.txtViewNumarCumparator);
viewHolder.line2 = (TextView) row.findViewById(R.id.listaProduse);
viewHolder.line3 = (TextView) row.findViewById(R.id.sumaProduse);
row.setTag(viewHolder);
} else {
viewHolder = (CardViewHolder)row.getTag();
}
Card card = getItem(position);
viewHolder.line1.setText(card.getNumarCumparator());
viewHolder.line2.setText(card.getListaProduse());
viewHolder.line3.setText(card.getSumaProduse());
return row;
}
public Bitmap decodeToBitmap(byte[] decodedByte) {
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
} }
Object class :
public class Card {
private Integer numarCumparator;
private String listaProduse;
private Integer sumaProduse;
public Card(Integer numarCumparator, String listaProduse, Integer sumaProduse) {
this.numarCumparator = numarCumparator;
this.listaProduse = listaProduse;
this.sumaProduse = sumaProduse;
}
public Integer getNumarCumparator() {
return numarCumparator;
}
public void setNumarCumparator(Integer numarCumparator) {
this.numarCumparator = numarCumparator;
}
public String getListaProduse() {
return listaProduse;
}
public void setListaProduse(String listaProduse) {
this.listaProduse = listaProduse;
}
public Integer getSumaProduse() {
return sumaProduse;
}
public void setSumaProduse(Integer sumaProduse) {
this.sumaProduse = sumaProduse;
}}
Hope the question is clear, I really need to get out from this problem.
i need create a custom adapter for a listview but i can't understand how could do it. Actually it works my work but using simply a listview with all objects inside the default android layout for the lists. I need "separate" the objects creating the custom adapter. This is the actual code:
private static class SoluzioniLoader extends AsyncTaskLoader<List<Soluzione>> {
private FermataComune partenza;
private FermataComune arrivo;
private String data;
public SoluzioniLoader(Context context, FermataComune partenza, FermataComune arrivo, String data) {
super(context);
this.partenza = partenza;
this.arrivo = arrivo;
this.data = data;
}
#Override
public List<Soluzione> loadInBackground() {
try {
List<Soluzione> soluzioni = Client.cercaCorseAndata(partenza, arrivo, data);
return soluzioni;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
private LoaderCallbacks<List<Soluzione>> mLoaderCallbacks = new LoaderCallbacks<List<Soluzione>>() {
private ProgressDialog pd;
#Override
public Loader<List<Soluzione>> onCreateLoader(int id, Bundle args) {
pd = new ProgressDialog(SoluzioniActivity.this);
pd.setTitle("Caricamento Soluzioni Trovate");
pd.setMessage("Attendi...");
pd.setIndeterminate(false);
pd.show();
return new SoluzioniLoader(SoluzioniActivity.this, partenza, arrivo, data);
}
#Override
public void onLoadFinished(Loader<List<Soluzione>> loader, List<Soluzione> data) {
try {
pd.dismiss();
} catch(Exception e){
}
if (data == null) {
// ERRORE
} else {
mListView.setAdapter(new ArrayAdapter<Soluzione>(SoluzioniActivity.this, android.r.layout.simple_list_item_1, data));
}
I've already created a layout for the row
<?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"
android:orientation="vertical"
>
<TextView
android:id="#+id/fromhour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
/>
<TextView
android:id="#+id/from"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
/>
<TextView
android:id="#+id/tohour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
/>
<TextView
android:id="#+id/to"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
/>
</LinearLayout>
Any help how could i create and integrate a custom adapter here? Thanks
Try below code:
//Declare your custom adapter:
private EfficientAdapter adapter;
In onCreate() initialize it:
adapter = new EfficientAdapter(this);
Then set your list adapter,
your_listview.setAdapter(adapter);
//Your adapter code:
private class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context context;
private Bitmap imageBitmap = null;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
}
#Override
public int getCount() {
return YOUR_ARRAY.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.featured_item, null);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView.findViewById(R.id.txtTitle);
holder.txtAuthorName = (TextView) convertView.findViewById(R.id.txtAuthorName);
holder.txtDescription = (TextView) convertView.findViewById(R.id.txtDescription);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtTitle.setText(data.get(position).get("article_title"));
holder.txtAuthorName.setText(data.get(position).get("author_name"));
holder.txtDescription.setText(data.get(position).get("article_text"));
return convertView;
}
class ViewHolder {
//YOUR ATTRUBUTES TO DISPLAY IN LIST DECLARE HERE
TextView txtTitle;
TextView txtAuthorName;
TextView txtDescription;
}
}