How to retreive data from mysql database in RecyclerView into RadioButton - android

Im creating a RecyclerView using jdbc connection and mysql database. Inside the RecyclerView I am uploading data from my database into one TextView and three radioButtons . Everything works just fine, but my problem is that it only shows the first RadioButton and there is nothing in the second and third one.
Here is my java code :
public class GererVoteInvite extends AppCompatActivity {
private ArrayList<VoteItem> itemArrayList; //List items Array
private MyAppAdapter myAppAdapter; //Array Adapter
private RecyclerView recyclerView; //RecyclerView
private RecyclerView.LayoutManager mLayoutManager;
private boolean success = false; // boolean
private static final String DB_URL = "jdbc:mysql://10.0.2.2/mvoting_db_1.0.0.0";
// private static final String DB_URL = "jdbc:mysql://172.16.24.25/mvoting_db_1.0.0.0"; //"jdbc:mysql://DATABASE_IP/DATABASE_NAME";
private static final String USER = "mootaz";
private static final String PASS = "mootaz";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gerer_vote_invite);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView); //REcyclerview Declaration
recyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
itemArrayList = new ArrayList<VoteItem>(); // Arraylist Initialization
// Calling Async Task
SyncData orderData = new SyncData();
orderData.execute("");
}
// Async Task has three overrided methods,
private class SyncData extends AsyncTask<String, String, String> {
String msg = "Internet/DB_Credentials/Windows_FireWall_TurnOn Error, See Android Monitor in the bottom For details!";
ProgressDialog progress;
//Starts the progress dailog
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(GererVoteInvite.this, "Synchronising",
"RecyclerView Loading! Please Wait...", true);
}
// Connect to the database, write query and add items to array list
#Override
protected String doInBackground(String... strings) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); //Connection Object
if (conn == null) {
success = false;
} else {
// Change below query according to your own database.
String query = "SELECT lib_probleme , lib_solution_1 , lib_solution_2 , lib_solution_3 FROM reunion JOIN probleme JOIN solution WHERE reunion.id_reunion=probleme.id_reunion and probleme.id_probleme=solution.id_probleme ;";
Statement stmt = conn.createStatement();
java.sql.ResultSet rs = stmt.executeQuery(query);
// if resultset not null, I add items to itemArraylist using class created
if (rs != null) {
while (rs.next()) {
try {
itemArrayList.add(new VoteItem(rs.getString("lib_probleme"), rs.getString("lib_solution_1"), rs.getString("lib_solution_2"), rs.getString("lib_solution_3")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
success = false;
}
return msg;
}
// disimissing progress dialoge, showing error and setting up my gridview
#Override
protected void onPostExecute(String msg) {
progress.dismiss();
Toast.makeText(GererVoteInvite.this, msg + "", Toast.LENGTH_LONG).show();
if (success == false) {
} else {
try {
myAppAdapter = new MyAppAdapter(itemArrayList, GererVoteInvite.this);
recyclerView.setAdapter(myAppAdapter);
} catch (Exception ex) {
}
}
}
}
public class MyAppAdapter extends RecyclerView.Adapter<MyAppAdapter.ViewHolder> {
private List<VoteItem> values;
public Context context;
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtProbleme;
public RadioGroup group;
public RadioButton txtSol1;
public RadioButton txtSol2;
public RadioButton txtSol3;
public View layout;
public ViewHolder(View v) {
super(v);
layout = v;
group = (RadioGroup) v.findViewById(R.id.radio_group);
txtProbleme = (TextView) v.findViewById(R.id.tv_probleme);
txtSol1 = (RadioButton) v.findViewById(R.id.rb_1);
txtSol2 = (RadioButton) v.findViewById(R.id.rb_2);
txtSol3 = (RadioButton) v.findViewById(R.id.rb_3);
}
}
// Constructor
public MyAppAdapter(List<VoteItem> myDataset, Context context) {
values = myDataset;
this.context = context;
}
// Create new views (invoked by the layout manager) and inflates
#Override
public MyAppAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.vote_view, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Binding items to the view
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final VoteItem voteItem = values.get(position);
holder.txtProbleme.setText(voteItem.getProbleme());
holder.group.setTag(position);
holder.txtSol1.setText(voteItem.getSol1());
holder.txtSol2.setText(voteItem.getSol2());
holder.txtSol3.setText(voteItem.getSol3());
}
// get item count returns the list item count
#Override
public int getItemCount() {
return values.size();
}
}
}
And here is my layout.xml that containt the item for the RecyclerView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/ac"
android:layout_width="match_parent"
android:layout_height="205dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:padding="5dp">
<android.support.v7.widget.CardView
android:id="#+id/vote_card"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:layout_marginTop="10dp"
card_view:cardBackgroundColor="#color/white"
card_view:cardCornerRadius="10dp"
card_view:cardElevation="5dp">
<TextView
android:id="#+id/tv_probleme"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_marginTop="30dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:text="Probleme :"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="16dp" />
<RadioGroup
android:id="#+id/radio_group"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:id="#+id/rb_1"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_marginTop="60dp"
android:text="Solution 1" />
<RadioButton
android:id="#+id/rb_2"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:text="Solution 2" />
<RadioButton
android:id="#+id/rb_3"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:text="Solution 3" />
</RadioGroup>
</android.support.v7.widget.CardView>
</RelativeLayout>
Here is the screenshot of my app

Related

RecyclerView shows Strings but not Images

I have a SQLite database and want to search Items thorugh DB and then showing the items on recyclerView. Everything looking fine but recyclerView not showing the pictures, But somehow It shows the Strings
Normally pictures I saved inside the SQLite as BLOB should be displayed on the left.
Here is SearchFragment (Where I make the search and start recyclerView to display items)
public class SearchFragment extends Fragment {
Button searchbutton;
EditText editText;
View v;
Cursor cursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_search, container, false);
addListenerOnButton(v);
return v;
}
private void addListenerOnButton(View v) {
searchbutton = v.findViewById(R.id.searchfragment_button);
editText = v.findViewById(R.id.searchfragment_edittext);
searchbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String keystring = editText.getText().toString();
if(keystring.isEmpty())
Toast.makeText(getContext(),R.string.empty_search ,Toast.LENGTH_LONG).show();
else
new FoodQuery().execute(keystring);
}
});
}
//Place I start the search on background
private class FoodQuery extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String [] keys) {
String name_col;
DietAppDatabaseHelper daDBHelper;
SQLiteDatabase daDB;
daDBHelper = new DietAppDatabaseHelper(getContext());
try {
daDB = daDBHelper.getReadableDatabase();
if (Locale.getDefault().getLanguage() == "tr")
name_col = "name_tr";
else
name_col = "name_eng";
String query = "SELECT * FROM food_data WHERE " //Query here
+ name_col + " LIKE ?" ;
cursor = daDB.rawQuery(query, new String[]{"%" + keys[0] + "%"});
viewResults(name_col);
daDB.close();
} catch (SQLiteException e){
Log.d("SearchFragment", "doInBackground: " + e);
}
return null;
}
}
private void viewResults(String lang) {
int name_col = -1; //For language issues not important
if(lang == "name_tr")
name_col = 1;
else if(lang == "name_eng")
name_col = 2;
ArrayList<String> tmpnames = new ArrayList<>(); //I put pictures to byte[] and names to String Arraylist here
ArrayList<byte[]> tmppictures = new ArrayList<>();
if(cursor.moveToFirst()){
tmpnames.add(cursor.getString(name_col));
tmppictures.add(cursor.getBlob(5));
while(cursor.moveToNext()){
tmpnames.add(cursor.getString(name_col));
tmppictures.add(cursor.getBlob(5));
}
}
else {
Looper.prepare();
Toast.makeText(getContext(), R.string.no_food_found, Toast.LENGTH_LONG).show(); //To prevent empty search
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
RecyclerView recyclerView = v.findViewById(R.id.recycler_view);
SearchResultAdapter adapter = new SearchResultAdapter(getContext(), tmppictures, tmpnames);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
recyclerView.setAdapter(adapter);
}
});
}
}
Layout File of SearchFragment
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".fragments.SearchFragment"
android:id="#+id/fragment_search">
<Button
android:id="#+id/searchfragment_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:layout_marginEnd="4dp"
android:layout_marginRight="4dp"
android:text="#string/nav_search"
android:textColor="#FFFFFF"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<EditText
android:id="#+id/searchfragment_edittext"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="64dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintEnd_toStartOf="#+id/searchfragment_button"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="124dp"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="0dp">
</androidx.recyclerview.widget.RecyclerView>
</androidx.constraintlayout.widget.ConstraintLayout>
Here is the adapter
public class SearchResultAdapter extends RecyclerView.Adapter<SearchResultAdapter.ViewHolder>{
private ArrayList<byte[]> foodimages;
private ArrayList<String> foodnames;
private Context context;
public SearchResultAdapter(Context context, ArrayList<byte[]> foodimages, ArrayList<String> foodnames) {
this.foodimages = new ArrayList<>(foodimages);
this.foodnames = new ArrayList<>(foodnames);
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_result_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.foodname.setText(foodnames.get(position));
holder.foodimage.setImageBitmap(BitmapFactory.decodeByteArray(foodimages.get(position), 0, foodimages.size()));
}
#Override
public int getItemCount() {
return foodnames.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView foodimage;
TextView foodname;
RelativeLayout parentLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
foodimage = itemView.findViewById(R.id.food_seacrh_image);
foodname = itemView.findViewById(R.id.food_search_name);
parentLayout = itemView.findViewById(R.id.search_item);
}
}
}
Lastly, the layout of my item to use in recyclerView
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:id="#+id/search_item">
<ImageView
android:id="#+id/food_seacrh_image"
android:layout_width="100dp"
android:layout_height="100dp"
/>
<TextView
android:id="#+id/food_search_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/food_seacrh_image"
android:textColor="#FFFFFF"
android:layout_centerVertical="true"
android:layout_marginLeft="30dp"
android:textSize="17sp"
android:layout_toEndOf="#+id/food_seacrh_image"
android:layout_marginStart="30dp" />
It seems like the problem could be the line:
holder.foodimage.setImageBitmap(BitmapFactory.decodeByteArray(foodimages.get(position), 0, foodimages.size()));
Should probably be:
holder.foodimage.setImageBitmap(BitmapFactory.decodeByteArray(foodimages.get(position), 0, foodimages.get(position).size));
The third param on decodeByteArray should be the length (in bytes) of the image, you are passing in the actual number of images.

E/RecyclerView: No adapter attached; skipping layout. using ASYNC TASK

i've had a problem, when i've tried to view this below fragment showing "skipping layout". Can any one help me out how to solve this problem please.
I'm getting this "No adapter attached; skipping layout." when i CLICK any imageview on ThirdFragment UI ayout, not when the images display in Thirdfragment UI layout.
ThirdFrament.java
public class ThirdFragment extends Fragment implements RecyclerViewAdapter.ItemListener {
static final String url = "https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesData.txt" ;
RecyclerView recyclerView;
RecyclerViewAdapter adapter;
AutoFitGridLayoutManager layoutManager;
private static List<JsonURLFullModel> cart;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView= inflater.inflate(R.layout.fragment_third, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
new JSONTask().execute(url, this);
// Inflate the layout for this fragment
return rootView;
}
public class JSONTask extends AsyncTask<Object, String, ThirdFragModel> {
// Url , , return_value_of_doInBackground
//private ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
//dialog.show(); // this is for ProgressDialog
}
#Override
protected ThirdFragModel doInBackground(Object... params) {
//send and receive data over the web
// can be used to send and receive "streaming" data whose length is not
// known in advance
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0].toString());
RecyclerViewAdapter.ItemListener itemListener = (RecyclerViewAdapter.ItemListener) params[1];
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream(); // this is used to store
// the response, response is always stream
reader = new BufferedReader(new InputStreamReader(stream));
// BufferedReader reads the stream line by line and then store in the reader
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString(); // this contails whole JSON data from the URL
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies"); // "movies" is the JSON Array-object in JSON data URL
List<JsonURLFullModel> movieModelList = new ArrayList<>();
//StringBuffer finalBufferedaData = new StringBuffer();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i); // getting first json object from JSON ARRAY "movies"
JsonURLFullModel movieModel = new JsonURLFullModel();
movieModel.setMovie(finalObject.getString("movie"));
movieModel.setImage(finalObject.getString("image"));
movieModelList.add(movieModel); // adding the final object in list
//finalBufferedaData.append(movieName +"-"+ year +"\n");
}
ThirdFragModel thirdFragModel= new ThirdFragModel(itemListener,movieModelList);
return thirdFragModel;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(ThirdFragModel result) {
super.onPostExecute(result);
//jsonfull.setText(result);
//dialog.dismiss(); // closing dialog, before the content load in ListView(i.e until application lodading it will run, then dialog closes)
adapter = new RecyclerViewAdapter(getActivity(), result.getMovieModelList(), result.getItemListener());
/**
AutoFitGridLayoutManager that auto fits the cells by the column width defined.
**/
layoutManager = new AutoFitGridLayoutManager(getActivity(), 500);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
/**
Simple GridLayoutManager that spans two columns
**/
/*GridLayoutManager manager = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(manager);*/
//AnimationUtils.animate(jsonFullL1, true);
}
}
public void moveToLoginActivity() {
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
}
#Override
public void onItemClick(int mPosition,List<JsonURLFullModel> mValues ) {
Log.d("Fragposition",mPosition+":"+mValues);
Toast.makeText(getActivity(), mValues.get(mPosition).getMovie() + " is clicked", Toast.LENGTH_SHORT).show();
//Intent intent = new Intent(getActivity(), FullScreenViewActivity.class);
Intent intent = new Intent(getActivity(), FullScreenViewInitialActivity.class);
intent.putExtra("position", mPosition);
intent.putExtra("values", (Serializable) mValues);
startActivity(intent);
}
public static List<JsonURLFullModel> getCart() {
if(cart == null) {
cart = new Vector<JsonURLFullModel>();
}
return cart;
}
}
Here is my adapter class which we used in ThirdFragment class as shown above
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
static List<JsonURLFullModel> mValues;
Context mContext;
private ItemListener mListener;
static int mPosition;
public RecyclerViewAdapter(Context context, List<JsonURLFullModel> values, ItemListener itemListener) {
mValues = values;
mContext = context;
mListener=itemListener;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView textView;
public ImageView imageView;
public RelativeLayout relativeLayout;
JsonURLFullModel item;
public ViewHolder(View v) {
super(v);
v.setOnClickListener(this);
textView = (TextView) v.findViewById(R.id.textView1);
imageView = (ImageView) v.findViewById(R.id.imageView1);
relativeLayout = (RelativeLayout) v.findViewById(R.id.relativeLayout);
}
public void setData(final JsonURLFullModel item) {
this.item = item;
Log.d("INFO",item.getImage());
//https://futurestud.io/tutorials/picasso-image-resizing-scaling-and-fit
Picasso.with(mContext)
.load(item.getImage())
.error(R.drawable.ferrari)
.noPlaceholder()
.noFade()
.fit()
.into(imageView, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
//Success image already loaded into the view
Log.d("INFO","success");
}
#Override
public void onError() {
//Error placeholder image already loaded into the view, do further handling of this situation here
Log.d("INFO","error");
}
});
/*imageView.post(new Runnable() {
#Override
public void run(){
Glide.with(mContext).load(item.getImage()).asBitmap().override(1080, 600).into(imageView);
}
});*/
textView.setText(item.getMovie());
}
#Override
public void onClick(View view) {
if (mListener != null) {
mListener.onItemClick(getAdapterPosition(),mValues); // this.getPosition() is depricated
// in API 22 and we got getAdapterPosition()
}
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.recycler_view_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder Vholder, int position) {
Vholder.setData(mValues.get(position));
mPosition=position;
}
#Override
public int getItemCount() {
return mValues.size();
}
//Below interface implimentation can be found in ThirdFragment
// you can write below interface separetly or in you can write in this class like below
public interface ItemListener {
void onItemClick(int mPosition, List<JsonURLFullModel> mValues);
}
}
FullScreenViewInitialActivity.java
public class FullScreenViewInitialActivity extends FragmentActivity {
ImageFragmentPagerAdapter imageFragmentPagerAdapter;
ViewPager viewPager;
static ArrayList<JsonURLFullModel> mValues;
static int position;
Button addToBagButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_view_initial);
addToBagButton = (Button) findViewById(R.id.b_add_to_bag);
Intent i = getIntent();
position=i.getIntExtra("position",0);
Log.d("Acposition",""+position);
mValues = (ArrayList<JsonURLFullModel>) getIntent().getSerializableExtra("values");
imageFragmentPagerAdapter = new ImageFragmentPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.intial_pager);
viewPager.setAdapter(imageFragmentPagerAdapter);
viewPager.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
CircleIndicator circleIndicator = (CircleIndicator) findViewById(R.id.imageIndicator);
circleIndicator.setViewPager(viewPager);
/*viewPager.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent(FullScreenViewInitialActivity.this, FullScreenViewActivity.class);
intent.putExtra("position", position);
intent.putExtra("values", (Serializable) mValues);
startActivity(intent);
}
});*/
final List<JsonURLFullModel> cart = ThirdFragment.getCart();
final JsonURLFullModel selectedProduct = mValues.get(position);
addToBagButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cart.add(selectedProduct);
Log.d("cart",""+cart.size());
//finish();
Button b_add_to_bag = (Button) findViewById(R.id.b_add_to_bag);
b_add_to_bag.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reviewOrderIntent = new Intent(FullScreenViewInitialActivity.this, FullScreenViewReviewActivity.class);
startActivity(reviewOrderIntent);
}
});
}
});
if(cart.contains(selectedProduct)) {
addToBagButton.setEnabled(false);
addToBagButton.setText("Item in Cart");
}
}
public static class ImageFragmentPagerAdapter extends FragmentPagerAdapter {
public ImageFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return mValues.size();
}
#Override
public Fragment getItem(int position) {
SwipeFragment fragment = new SwipeFragment();
return SwipeFragment.newInstance(position);
}
}
public static class SwipeFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View swipeView = inflater.inflate(R.layout.swipe_fragment, container, false);
ImageView imageView = (ImageView) swipeView.findViewById(R.id.imageView);
/*Bundle bundle = getArguments();
int position = bundle.getInt("position");*/
//JsonURLFullModel imageFileName = mValues.get(position);
try {
BitmapFactory.Options options = new BitmapFactory.Options();
/*options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;*/
URL url = new URL(mValues.get(position).getImage());
Log.d("position",""+position);
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream(),null, options);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else
System.out.println("The Bitmap is NULL");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), mValues.get(position).getMovie(), Toast.LENGTH_SHORT).show();
}
});
return swipeView;
}
static SwipeFragment newInstance(int position) {
SwipeFragment swipeFragment = new SwipeFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", position);
swipeFragment.setArguments(bundle);
return swipeFragment;
}
}
}
third_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
/>
<!--removed from recycler view
app:layout_behavior="#string/appbar_scrolling_view_behavior"-->
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
recycler_view_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
card_view:cardCornerRadius="#dimen/margin10"
card_view:cardElevation="#dimen/margin10"
card_view:cardMaxElevation="#dimen/margin10"
card_view:contentPadding="#dimen/margin10"
card_view:cardPreventCornerOverlap="false"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="center">
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="150dp"
android:scaleType="fitXY"
android:padding="5dp"
android:layout_alignParentTop="true"/>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textColor="#color/colorPrimary"
android:layout_marginTop="10dp"
android:layout_below="#+id/imageView1" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
activity_fullscreen_view_initial
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:orientation="vertical">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:layout_weight="1">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/cart_button_layout"
android:layout_alignParentTop="true"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/intial_pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<me.relex.circleindicator.CircleIndicator
android:id="#+id/imageIndicator"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_alignBottom="#+id/intial_pager"
android:layout_marginBottom="10dp" />
</LinearLayout>
</ScrollView>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
layout="#layout/full_screen_size_picker"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cart_button_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="bottom"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<Button
android:id="#+id/b_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_weight="1"
android:background="#D3D3D3"
android:text="save"
android:textColor="#000000" />
<Button
android:id="#+id/b_add_to_bag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:background="#color/colorPrimary"
android:text="add to bag"
android:textColor="#FFF" />
</LinearLayout>
</LinearLayout>
swipe_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/imageView"
android:layout_gravity="center_horizontal"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</LinearLayout>
Try setting the setting the RecyclerView with an empty Adapter before you execute your AsyncTask.
View rootView= inflater.inflate(R.layout.fragment_third, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
-->recyclerView.setAdapter(new RecyclerViewAdapter(getActivity(), new ArrayList<>(), null);
new JSONTask().execute(url, this);
Then create a method in the RecyclerViewAapter to load the the populated List<JsonURLFullModel> from the AsyncTask's onPostExecute.
public void loadJson(List<JsonURLFullModel> jsonList){
mValues = jsonList;
notifyDataSetChanged();
}
If that doesn't work trying loading on the Ui thread from Asynctask using runOnUiThread
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.loadJson(...)
}
});
Edit 1 Adding loadJson to your RecyclerViewAapter.class
#Override
public int getItemCount() {
return mValues.size();
}
public void loadJson(List<JsonURLFullModel> jsonList){
mValues = jsonList;
notifyDataSetChanged();
}
//Below interface implimentation can be found in ThirdFragment
// you can write below interface separetly or in you can write in this class like below
public interface ItemListener {
void onItemClick(int mPosition, List<JsonURLFullModel> mValues);
}
Call the method in your PostExecute
#Override
protected void onPostExecute(ThirdFragModel result) {
super.onPostExecute(result);
//jsonfull.setText(result);
//dialog.dismiss(); // closing dialog, before the content load in ListView(i.e until application lodading it will run, then dialog closes)
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.loadJson(result.getMovieModelList());
}
});
}
Also add your the Layout manager for the RecyclerView in onCreateView
View rootView= inflater.inflate(R.layout.fragment_third, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
-->recyclerView.setAdapter(new RecyclerViewAdapter(getActivity(), new ArrayList<>(), null);
layoutManager = new AutoFitGridLayoutManager(getActivity(), 500);
recyclerView.setLayoutManager(layoutManager);

Is there anyway I can change my code to recycleview for icons in android?

I have an activity where items are coming from database , and i want set icons for the same. I tried listview but heard about recyclerview , but I cant seem to find the solution as to how can I load it. kindly help
here is my listview:
public class TypeMenu extends AppCompatActivity {
private String TAG = TypeMenu.class.getSimpleName();
String bid;
private ProgressDialog pDialog;
private ListView lv;
private static final String TAG_BID = "bid";
// URL to get contacts JSON
private static String url = "http://cloud....com/brtemp/index.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_type_menu);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
HashMap<String, String> selected = contactList.get(position);
String selectedId= selected.get("id");
Intent in = new Intent(getApplicationContext(), SubMenu.class);
// sending pid to next activity
in.putExtra("id",selectedId);
startActivityForResult(in, 100);
Toast.makeText(getApplicationContext(),"Toast" +selectedId ,Toast.LENGTH_SHORT).show();
}
});
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(TypeMenu.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
// Toast.makeText(getApplicationContext(),"Toast",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonArry = new JSONArray(jsonStr);
for (int i = 0; i < jsonArry.length(); i++)
{
JSONObject c = jsonArry.getJSONObject(i);
String id = c.getString("id");
String type = c.getString("type");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("type", type);
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
TypeMenu.this, contactList,
R.layout.list_item, new String[]{ "type","id"},
new int[]{
R.id.type});
lv.setAdapter(adapter);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
here is my list_item.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:orientation="horizontal"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
/>
<TextView
android:id="#+id/type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ImageView
android:id="#+id/arrow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp"
/>
</LinearLayout>
</LinearLayout>
try this:
here is lsit_item.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:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp" />
<TextView
android:id="#+id/type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10dp" />
</LinearLayout>
<ImageView
android:id="#+id/arrow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp"/>
</LinearLayout>
initialize this in your activity;
int[] images = new int[]{
R.drawable.dropdown,
};
// Keys used in Hashmap
String[] from = { "image","id","type" };
// Ids of views in listview_layout
int[] to = { R.id.arrow1,R.id.id,R.id.type};
In your doInbanckground
for (int i = 0; i < jsonArry.length(); i++)
{
JSONObject c = jsonArry.getJSONObject(i);
String id = c.getString("id");
String type = c.getString("type");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("type", type);
contact.put("image", Integer.toString(images[0]) );
contactList.add(contact);
}
Also add this in your onPostExecute replacing above code:
ListAdapter adapter = new SimpleAdapter(
TypeMenu.this, contactList,
R.layout.list_item, from,to);
lv.setAdapter(adapter);
You need to create custom RecylerView adapter
Step 1: gradle:
dependencies {
...
compile "com.android.support:recyclerview-v7:23.0.1"
}
Step 2: layout/activity_name.xml
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
Step 3: Create Custom Adapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ArrayList<String> mDataset;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView txtHeader;
public TextView txtFooter;
public ViewHolder(View v) {
super(v);
txtHeader = (TextView) v.findViewById(R.id.firstLine);
txtFooter = (TextView) v.findViewById(R.id.secondLine);
}
}
public MyAdapter(ArrayList<String> myDataset) {
mDataset = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.rowlayout, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
final String name = mDataset.get(position);
holder.txtHeader.setText(mDataset.get(position));
holder.txtHeader.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
remove(name);
}
});
holder.txtFooter.setText("Footer: " + mDataset.get(position));
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.size();
}
}
Step 4: In your activity.java
setContentView(R.layout.my_activity);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
// specify an adapter (see also next example)
mAdapter = new MyAdapter(myDataset);
mRecyclerView.setAdapter(mAdapter);

Unable to set left and right conversation while using custom listview in android

Am developing a chat application.I have done them using smack library.Everything works fine,even the users also can chat with each other but am unable set the incoming messages to the right side of the ListView . I have tried to the gravity of the TextView to Right.But am unable to achieve it.I referred some these questions but i didn't helped me!
1.Left and Right alignment
2.Listview Row Layout
public class ChatRoom extends Activity {
private final static String SERVER_HOST = "talk.google.com";
private final static int SERVER_PORT = 5222;
private final static String SERVICE_NAME = "gmail.com";
private final static String LOGIN = "acd#gmail.com";
private final static String PASSWORD = "password";
private List<String> m_discussionThread;
private XMPPConnection m_connection;
private Handler m_handler;
private String mtemp_user_id;
private ProgressDialog p_dialog;
EditText mMsg;
ListView listview;
MyAdapter myadpter;
String fromName;
String mtempSpecial;
String SendMSg, RecievdMsg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_screen);
PrepareChat prechat = new PrepareChat(); //AsyncTask
m_handler = new Handler();
p_dialog = new ProgressDialog(ChatRoom.this);
m_discussionThread = new ArrayList<String>();
myadpter = new MyAdapter(m_discussionThread);
Bundle bundle = getIntent().getExtras();
mtemp_user_id = bundle.getString("USER");
prechat.execute();
listview = (ListView) findViewById(R.id.list_view_);
listview.setAdapter(myadpter);
mMsg = (EditText) findViewById(R.id.ed_msg);
findViewById(R.id.b_MSG_To).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
SendMSg = "SEND";
Message msg = new Message(mtemp_user_id, Message.Type.chat);
msg.setBody(mMsg.getText().toString());
m_connection.sendPacket(msg);
m_discussionThread.add(mMsg.getText().toString());
mMsg.setText("");
}
});
}
public class PrepareChat extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
p_dialog.setMessage("Preparing chat");
p_dialog.setCancelable(false);
p_dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
System.out.println("In do in back ...");
try {
initConnection();
} catch (XMPPException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
p_dialog.dismiss();
}
}
private void initConnection() throws XMPPException {
ConnectionConfiguration config = new ConnectionConfiguration(
SERVER_HOST, SERVER_PORT, SERVICE_NAME);
m_connection = new XMPPConnection(config);
m_connection.connect();
m_connection.login(LOGIN, PASSWORD);
System.out.println("After LOGInd");
Presence presence = new Presence(Presence.Type.available);
presence.setStatus("available");
m_connection.sendPacket(presence);
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
m_connection.addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
Message message = (Message) packet;
if (message.getBody() != null) {
String fromName = StringUtils.parseBareAddress(message
.getFrom());
String mtempSpecial = message.getBody().toString();
m_discussionThread.add(mtemp_user_id + mtempSpecial);
RecievdMsg = "RE";
m_handler.post(new Runnable() {
public void run() {
myadpter.notifyDataSetChanged();
listview.setSelection(myadpter.getCount() - 1);
}
});
}
}
}, filter);
}
public class MyAdapter extends BaseAdapter {
LayoutInflater layoutinflate;
List<String> list = new ArrayList<String>();
Context context;
public MyAdapter(List<String> m_discussionThread) {
list = m_discussionThread;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int items) {
return items;
}
#Override
public long getItemId(int posi) {
return posi;
}
#Override
public View getView(int position, View arg1, ViewGroup view_Group) {
View view_ = arg1;
LayoutInflater layout_inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (SendMSg.equals("SEND")) {
view_ = layout_inflater.inflate(R.layout.chat_b, view_Group,
false);
TextView tv_MyMsg = (TextView) view_
.findViewById(R.id.tv_mymsg);
System.out.println("in send loop");
// tv_MyMsg.setGravity(Gravity.RIGHT);
tv_MyMsg.setText(list.get(position)); //TextView not binding to the right.
SendMSg = "";
} else {
view_ = layout_inflater.inflate(R.layout.chat_ab, view_Group,
false);
TextView tv_FromMsg = (TextView) view_
.findViewById(R.id.tv_From_Msg);
tv_FromMsg.setText(list.get(position));
/*
* tv_ToMsg.setGravity(Gravity.LEFT);
* System.out.println("in else"); tv_FromMsg.setText("");
* tv_ToMsg.setText(list.get(position));
*/}
return view_;
}
}
}
UPDATE
Only chat_ab.xml getting populated but chat_b.xml which contains green text is ignored.
chat_ab.xml ...
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:background="#ffffff"
android:layout_gravity="left"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/tv_From_Msg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:gravity="left"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FF00FF" />
chat_b.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:background="#ffffff"
android:layout_gravity="right"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/tv_mymsg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#0000ff"
android:layout_alignParentRight="true"
android:gravity="right"
android:layout_alignParentTop="true"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
What i got so far is this
What am expecting is My Message(out going) to the right of the ListView And outgoing to the left of the screen.
Please Do suggest.
You can achieve this with using android:gravity and android:layout_gravity attributes in LinearLayout.
Please Refer Android Listview for chat application.
Use different layouts for textview inside list view. Every time the list view populates with a new entry (message), compare the current users Auth by the sender's Auth by using user.getEmail().
If they match, set layout gravity of aforementioned textview to right, else left.

Android - ArrayList<Integer> not displaying properly in custom listVIew

I have a custom listView with three textViews. The data comes from a class with three ArrayLists, two of which are strings and the last one is an Integer. I have no problems populating and adding items to the list as I saw that when I displayed the ArrayList values on logCat via log.d, all three ArrayLists had their respectful items.
It seems to me that there is something wrong with the way I display data.
Here are the files:
list_row_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/variant"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="variant" />
<TextView
android:id="#+id/quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="quantity" />
<TextView
android:id="#+id/unit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginRight="221dp"
android:layout_toLeftOf="#+id/quantity"
android:text="unit" />
</RelativeLayout>
Here is the part in my activity_order_form.xml that has the listView element.
<RelativeLayout
android:id="#+id/relativeLayout3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_below="#+id/relativeLayout2"
android:orientation="vertical" >
<TextView
android:id="#+id/textViewVariantB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="94dp"
android:text="Variant"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textViewUnit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="123dp"
android:text="Unit"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ListView
android:id="#+id/listViewProductOrder"
android:layout_width="match_parent"
android:layout_height="350dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textViewVariantB" >
</ListView>
</RelativeLayout>
Here is the class where the ArrayList are stored.
public class CurrentOrderClass {
private String productName;
//ArrayLists
private ArrayList<String> variantArray = new ArrayList<String>();
private ArrayList<String> unitArray = new ArrayList<String>();
private ArrayList<Integer> quantityArray = new ArrayList<Integer>();
//TODO ArrayList functions
public ArrayList<String> getUnitArray() {
return unitArray;
}
public void setUnitArray(ArrayList<String> unitArray) {
this.unitArray = unitArray;
}
public void addToUnitArray(String unit){
this.unitArray.add(unit);
}
public ArrayList<Integer> getQuantityArray() {
return quantityArray;
}
public void setQuantityArray(ArrayList<Integer> quantityArray) {
this.quantityArray = quantityArray;
}
public void addToQuantityArray(int quantity){
this.quantityArray.add(quantity);
}
public ArrayList<String> getVariantArray() {
return variantArray;
}
public void setVariantArray(ArrayList<String> variantArray) {
this.variantArray = variantArray;
}
public void addToVariantArray(String variantArray){
this.variantArray.add(variantArray);
}
}
Here is the CustomListAdapter.java file
public class CustomListAdapter extends BaseAdapter {
private ArrayList<CurrentOrderClass> listData;
private LayoutInflater layoutInflater;
public CustomListAdapter(Context context, ArrayList<CurrentOrderClass> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
holder = new ViewHolder();
holder.variantView = (TextView) convertView.findViewById(R.id.variant);
holder.unitView = (TextView) convertView.findViewById(R.id.unit);
holder.quantityView = (TextView) convertView.findViewById(R.id.quantity);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.variantView.setText(listData.get(position).getVariantArray().get(position).toString());
holder.unitView.setText(listData.get(position).getUnitArray().get(position).toString());
holder.quantityView.setText(String.valueOf(listData.get(position).getQuantityRow()));
return convertView;
}
static class ViewHolder {
TextView variantView;
TextView unitView;
TextView quantityView;
}
public void setListData(ArrayList<CurrentOrderClass> data){
listData = data;
}
}
This is part of my OrderForm.java activity, this shows the onCreate and the method that populates the listView.
public class OrderForm extends Activity {
public TextView tv;
private int variantPosition;
CustomListAdapter customListAdapter;
CurrentOrderClass currentOrder = new CurrentOrderClass();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_form);
tv = (TextView)findViewById(R.id.textViewProduct);
//set variants here
popolateItem();
//set current order listview here
ArrayList image_details = getListData();
final ListView lv1 = (ListView) findViewById(R.id.listViewProductOrder);
customListAdapter = new CustomListAdapter(this, image_details);
lv1.setAdapter(customListAdapter);
}
private ArrayList getListData() {
ArrayList results = new ArrayList();
if(currentOrder.getQuantityArray().size() > 10){
loopUntil = currentOrder.getQuantityArray().size();
for(int i = 0; i < loopUntil; i++){
currentOrder.getQuantityArray();
currentOrder.getUnitArray();
currentOrder.getVariantArray();
results.add(currentOrder);
}
}
else{
loopUntil = 10;
for(int i = 0; i < loopUntil; i++){
currentOrder.getQuantityArray().add(i);
currentOrder.getUnitArray().add("Sample text here." + i);
currentOrder.getVariantArray().add("Another sample text here" + i);
results.add(currentOrder);
}
}
return results;
}
}
When I execute a Log.d statement to display the contents of my ArrayLists, it shows that my quantityArray has elements [0, 1, 2, 3, 4, 5, 6, 7, 9].
I know I can just convert quantityArray to an ArrayList from an ArayList, but I don't want to do that.
I think there's something wrong with my CustomListAdapter.
Any thoughts?
There is no where that you actually set the view, as in, it doesn't do anything, if convertView is null, you can't call any methods of it, convertView, if its is not null, will be ViewHolder in your context, what you need to do is have an object which is extending some type of view, instantiate it, give it methods to set the values, things like that.
For example here is what I use in an adapter that displays simple messages:
public class MessageView extends RelativeLayout {
private TextView mBody;
private String mBodyString = "";
private boolean mDrawn = false;
private boolean mLocal = false;
public MessageView(Context context) {
super(context);
this.drawView();
}
public MessageView(Context context, String body) {
super(context);
mBodyString = body;
this.drawView();
}
public MessageView(Context context, String body, boolean local) {
super(context);
mBodyString = body;
mLocal = local;
this.drawView();
}
private void drawView() {
if (mDrawn)
return;
mDrawn = true;
this.removeAllViews();
LayoutInflater li = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
if(mLocal){
this.addView(li.inflate(R.layout.list_item_message_device, this, false),
params);
}else{
this.addView(li.inflate(R.layout.list_item_message_remote, this, false),
params);
}
mBody = (TextView) this.findViewById(R.id.tMessage);
mBody.setText(mBodyString);
}
public void setLocal(){
this.setLocal(true);
}
public void setLocal(boolean local){
mLocal = local;
mDrawn = false;
this.drawView();
}
public void setMessage(String body){
mBodyString = body;
mBody.setText(mBodyString);
}
}
I got it.
I changed
holder.quantityView.setText(String.valueOf(listData.get(position).getQuantityRow()));
to
holder.quantityView.setText(String.valueOf(listData.get(position).getQuantityArray().get(position)));

Categories

Resources