Android ListView displaying one item per page - java

I have a listview that uses an adapter who receives a string array as an argument. When I look at the listview it displays 1 item then it shows a lot of blank space behind it that is followed by the next item if I scroll down. What could be the problem?
class CustomAdapter extends ArrayAdapter<String> {
CustomAdapter(Context context, String[] camere) {
super(context, R.layout.custom_row, camere);
}
boolean parola = true;
boolean intra = true;
String player_id, room_id;
String siteul = "some_site";
String site;
HashMap<String, String> hash;
static class ViewHolder {
TextView camera;
TextView players;
TextView max_players;
ImageView privata;
Button Buton;
String room_id, nume;
}
ViewHolder ceva;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
String variabile[] = getItem(position).split("\\s+");
if(convertView == null)
{
LayoutInflater linflater = LayoutInflater.from(getContext());
convertView = linflater.inflate(R.layout.custom_row, parent, false);
holder = new ViewHolder();
holder.camera = (TextView) convertView.findViewById(R.id.Nume);
holder.players = (TextView) convertView.findViewById(R.id.players);
holder.max_players = (TextView) convertView.findViewById(R.id.max_players);
holder.privata = (ImageView) convertView.findViewById(R.id.privata);
holder.Buton = (Button) convertView.findViewById(R.id.Buton);
holder.camera.setText(variabile[0]);
if (!variabile[1].equals("true")) {
parola = false;
holder.privata.setVisibility(View.INVISIBLE);
}
holder.players.setText(variabile[2]);
holder.max_players.setText(variabile[3]);
holder.room_id = variabile[4];
holder.nume = variabile[5];
holder.Buton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int playeri = Integer.parseInt(holder.players.getText().toString());
int maximi = Integer.parseInt(holder.max_players.getText().toString());
if(playeri < maximi)
{
hash = new HashMap<String, String>();
hash.put("name", holder.nume);
hash.put("room", holder.room_id);
if (intra) {
holder.Buton.setText("Iesi");
site = siteul + "/join";
intra = false;
} else {
holder.Buton.setText("Intra");
site = siteul + "/leave";
intra = true;
}
new ATask((ViewHolder) v.getTag()).execute(site);
}
}
});
convertView.setTag(holder);
holder.Buton.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
return convertView;
}
public void CheckStart()
{
site = siteul + "/checkstart";
hash = new HashMap<String, String>();
hash.put("room", room_id);
new ATask(ceva).execute(site);
}
public void CheckPlayers()
{
site = siteul + "/checkplayers";
hash = new HashMap<String, String>();
hash.put("room", room_id);
new ATask(ceva).execute(site);
}
public void openGame(String litera)
{
Intent incercare = new Intent(getContext(), Game.class);
incercare.putExtra("nume", player_id);
incercare.putExtra("room", room_id);
incercare.putExtra("litera", litera);
incercare.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getContext().startActivity(incercare);
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
public class ATask extends AsyncTask<String, Void, String> {
String rez = "";
ViewHolder myHolder;
public ATask(ViewHolder view) {
myHolder = view;
ceva = myHolder;
room_id = myHolder.room_id;
}
#Override
protected String doInBackground(String... urls) {
//try {
try {
Log.e("rasp", site);
URL obj = new URL(site);
try {
Log.e("rasp", obj.toString());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
//con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(getPostDataString(hash).getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
Log.e("rasp", "response code-ul e " + Integer.toString(responseCode));
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
rez = response.toString();
}
else {
Log.e("rasp", "POST request not worked");
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
Log.e("naspa", "E corupt!");
}
//} catch (Exception e) {
// Log.e("rasp", "aia e");
//}
return rez;
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
if (rez.charAt(0) == 'Y')
openGame(rez.substring(2));
else if (rez.charAt(0) == 'V' && !intra)
{
TextView players_mare = myHolder.players;
players_mare.setText(rez.substring(2));
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 1s = 1000ms
CheckStart();
}
}, 1000);
}
else if(rez.charAt(0) == 'G')
CheckPlayers();
else if(rez.charAt(0) == 'Z')
{
TextView players_mare = myHolder.players;
players_mare.setText(rez.substring(2));
}
else if (rez.charAt(0) == 'D')
{
player_id = rez.substring(2);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 1s = 1000ms
CheckStart();
}
}, 400);
}
}
}
}
Here is the xml of "custom_row.xml":
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background_joc">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:id="#+id/scrollView">
<LinearLayout
android:background="#color/grey"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_marginTop="10dp"
android:layout_marginLeft="7dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Nume camera"
android:id="#+id/Nume"
android:textSize="25dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Runde:"
android:layout_marginTop="-7dp"
android:layout_marginLeft="3dp"
android:id="#+id/textView15" />
<TextView
android:layout_marginTop="15dp"
android:layout_marginLeft="-30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="5"
android:id="#+id/runde"
android:textSize="25dp" />
<ImageView
android:layout_marginTop="18dp"
android:layout_marginLeft="20dp"
android:background="#drawable/buton_lock"
android:layout_width="15dp"
android:layout_height="20dp"
android:id="#+id/privata" />
<TextView
android:layout_marginTop="10dp"
android:layout_marginLeft="7dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="0"
android:id="#+id/players"
android:textSize="30dp" />
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="? android:attr/textAppearanceMedium"
android:text="/"
android:id="#+id/nu_trebuia_sa_aiba_id"
android:textSize="30dp" />
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="5"
android:id="#+id/max_players"
android:textSize="30dp" />
<Button
android:layout_marginTop="10dp"
android:layout_width="90dp"
android:layout_height="40dp"
android:text="Intra"
android:id="#+id/Buton"
android:layout_marginLeft="5dp" />
<TextView
android:layout_marginLeft="50dp"
android:layout_marginTop="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text=""
android:id="#+id/e_sa_pacaleasca_match_parentu_de_la_linear_layout"
/>
</LinearLayout>
</ScrollView>

In your custom_row.xml :
change the layout_height of the RelativeLayout, ScrollView and the LinearLayout from fill_parent to wrap_content.

From the R.layout.custom_row we can see that you make the root view(RelativeLayout) fill parent and make the height of ScrollView match_parent. So the Scrollview occupy the full screen. The blank space belongs to scrollview. I think you can remove the scrollview and make the root view(RelativeLayout) wrap content.
Try codes below:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/background_joc">
<ScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/grey"
android:orientation="horizontal">
<TextView
android:id="#+id/Nume"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:layout_marginTop="10dp"
android:text="Nume camera"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="25dp"/>
<TextView
android:id="#+id/textView15"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_marginTop="-7dp"
android:text="Runde:"
android:textAppearance="?android:attr/textAppearanceSmall"/>
<TextView
android:id="#+id/runde"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="-30dp"
android:layout_marginTop="15dp"
android:text="5"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textSize="25dp"/>
<ImageView
android:id="#+id/privata"
android:layout_width="15dp"
android:layout_height="20dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="18dp"
android:background="#drawable/buton_lock"/>
<TextView
android:id="#+id/players"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:layout_marginTop="10dp"
android:text="0"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="30dp"/>
<TextView
android:id="#+id/nu_trebuia_sa_aiba_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="/"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="30dp"/>
<TextView
android:id="#+id/max_players"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="5"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="30dp"/>
<Button
android:id="#+id/Buton"
android:layout_width="90dp"
android:layout_height="40dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:text="Intra"/>
<TextView
android:id="#+id/e_sa_pacaleasca_match_parentu_de_la_linear_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="50dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</ScrollView>
</RelativeLayout>

Related

How to get total of all items in recycler view

I have recycler view and spinner in activity depending on spinner value post request has been sent to server after which recycler view populated in which every row have some cost. I want to add this cost of every row.
Screenshot is given below:
In screenshot we can see No. of quantities are 2 which cost 40 like this other row also have some value.SO I want to add all these costs from each row and showing it in lower left area where ToTAL is written.
Here is my code:
activity_select_pack.xml
<?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=".SelectPack">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progress"
android:layout_centerInParent="true"/>
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="100dp"
app:cardUseCompatPadding="true"
app:cardCornerRadius="3dp"
android:layout_margin="16dp"
android:id="#+id/marketCard"
app:cardBackgroundColor="#color/colorPrimary">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#fff"
android:textSize="15sp"
android:id="#+id/textMarket"
android:text="Select Market Name"/>
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:layout_below="#+id/textMarket"
android:id="#+id/marketSpinner"
android:layout_marginTop="25dp"
android:background="#drawable/spinner_back"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:id="#+id/products"
android:layout_below="#+id/marketCard"
android:visibility="invisible"
android:layout_above="#+id/totalLayout"
android:layout_marginBottom="3dp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:background="#color/colorPrimary"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:id="#+id/totalLayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="40dp"
android:padding="10dp"
android:background="#drawable/spinner_back"
android:text="Total:00.00"
android:layout_centerVertical="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="40dp"
android:padding="8dp"
android:background="#drawable/login_but"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:text="Generate bill"
android:textSize="12sp"
android:textColor="#fff"/>
</RelativeLayout>
</RelativeLayout>
selectpack_layout.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"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="3dp"
app:cardUseCompatPadding="true"
app:cardBackgroundColor="#fff">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Crown"
android:layout_margin="10dp"
android:id="#+id/marketName"
android:textSize="18sp"
android:textColor="#color/colorPrimary"/>
<View
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:id="#+id/view1"
android:layout_below="#+id/marketName"
android:background="#adadad"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Product No."/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="300"
android:id="#+id/productNo"
android:textColor="#color/colorPrimary"
android:layout_alignParentRight="true"/>
<View
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:layout_marginTop="10dp"
android:layout_below="#+id/productNo"
android:background="#adadad"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Page"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="300"
android:id="#+id/page"
android:textColor="#color/colorPrimary"
android:layout_alignParentRight="true"/>
<View
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:layout_marginTop="10dp"
android:layout_below="#+id/page"
android:background="#adadad"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MRP"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="300"
android:id="#+id/mrp"
android:textColor="#color/colorPrimary"
android:layout_alignParentRight="true"/>
<View
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:layout_marginTop="10dp"
android:layout_below="#+id/mrp"
android:background="#adadad"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Inner pack"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="300"
android:id="#+id/innerPack"
android:textColor="#color/colorPrimary"
android:layout_alignParentRight="true"/>
<View
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:layout_marginTop="10dp"
android:layout_below="#+id/innerPack"
android:background="#adadad"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Outer pack"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="300"
android:id="#+id/outerPack"
android:textColor="#color/colorPrimary"
android:layout_alignParentRight="true"/>
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:layout_marginTop="10dp"
android:layout_below="#+id/innerPack"
android:background="#adadad"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp">
<Spinner
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:id="#+id/qtySpinner"
android:background="#drawable/qty_spinner"
android:layout_weight="1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TOTAL"
android:id="#+id/total"
android:layout_weight="1"/>
<Button
android:layout_width="50dp"
android:layout_height="30dp"
android:text="ORDER"
android:id="#+id/order"
android:textColor="#fff"
android:background="#drawable/login_but"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
SelectPack.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_pack);
fAuth = FirebaseAuth.getInstance();
ActionBar ab = getSupportActionBar();
assert ab!= null;
ab.setTitle("Select Pack");
ab.setDisplayHomeAsUpEnabled(true);
marketSpinner = findViewById(R.id.marketSpinner);
progress = findViewById(R.id.progress);
products = findViewById(R.id.products);
products.setHasFixedSize(true);
products.setLayoutManager(new LinearLayoutManager(this));
productList = new ArrayList<>();
List<String> categories = new ArrayList<String>();
categories.add("Select market");
categories.add("Crown");
categories.add("Long Book A4");
categories.add("Long Book");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
marketSpinner.setAdapter(dataAdapter);
marketSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String item = adapterView.getItemAtPosition(i).toString();
if(item.equals("Select market")){
progress.setVisibility(View.INVISIBLE);
}
else{
getData(item);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void getData(String item){
progress.setVisibility(View.VISIBLE);
products.setVisibility(View.INVISIBLE);
productList.clear();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20,TimeUnit.SECONDS)
.writeTimeout(20,TimeUnit.SECONDS)
.build();
RequestBody formBody = new FormBody.Builder()
.add("name",item)
.build();
Request request = new Request.Builder().post(formBody).url(URL).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(#NotNull Call call, #NotNull final Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONArray jsonArray = new JSONArray(response.body().string());
if(jsonArray.length() > 0){
products.setVisibility(View.VISIBLE);
progress.setVisibility(View.INVISIBLE);
}
for(int i=0;i<jsonArray.length();i++){
progress.setVisibility(View.INVISIBLE);
JSONObject object = jsonArray.getJSONObject(i);
String str1 = object.getString("market");
String str2 = object.getString("product_no");
String str3 = object.getString("page");
String str4 = object.getString("mrp");
String str5 = object.getString("inner_pack");
String str6 = object.getString("outer_pack");
Log.d("prod",str2);
ProductsModel model = new ProductsModel(str1,str2,str3,str4,str5,str6);
productList.add(model);
}
ProductAdapter adapter = new ProductAdapter(getApplicationContext(),productList);
products.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onFailure(#NotNull Call call, #NotNull final IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
progress.setVisibility(View.INVISIBLE);
products.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
});
}
ProductAdapter.java
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> {
private Context context;
private List<ProductsModel> productList;
public ProductAdapter(Context context, List<ProductsModel> productList) {
this.context = context;
this.productList = productList;
}
#NonNull
#Override
public ProductAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.selectpack_layout,parent,false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ProductAdapter.ViewHolder holder, int position) {
final ProductsModel model = productList.get(position);
holder.marketName.setText(model.getMarketName());
holder.productNo.setText(model.getProductNo());
holder.page.setText(model.getPage());
holder.mrp.setText(model.getMrp());
holder.innerPack.setText(model.getInnerPack());
holder.outerPack.setText(model.getOuterPack());
List<String> qty = new ArrayList<>();
qty.add("Select qty");
qty.add("1");
qty.add("2");
qty.add("3");
qty.add("4");
qty.add("5");
qty.add("6");
qty.add("7");
qty.add("8");
qty.add("9");
qty.add("10");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, qty);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.qtySpinner.setAdapter(dataAdapter);
holder.qtySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String item = adapterView.getItemAtPosition(i).toString();
if(!item.equals("Select qty")){
int qty = Integer.parseInt(item);
int cost = Integer.parseInt(model.getMrp());
int val = cost * qty;
holder.total.setText(String.valueOf(val));
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView marketName,productNo,page,mrp,innerPack,outerPack,total;
Spinner qtySpinner;
Button order;
public ViewHolder(#NonNull View itemView) {
super(itemView);
order = itemView.findViewById(R.id.order);
qtySpinner = itemView.findViewById(R.id.qtySpinner);
marketName = itemView.findViewById(R.id.marketName);
productNo = itemView.findViewById(R.id.productNo);
page = itemView.findViewById(R.id.page);
mrp = itemView.findViewById(R.id.mrp);
innerPack = itemView.findViewById(R.id.innerPack);
outerPack = itemView.findViewById(R.id.outerPack);
total = itemView.findViewById(R.id.total);
}
}
}
Someone please let me know how can I get and add total cost from each row and show it in lower left area. Any help would be appreciated.
THANKS
You can use array and append the value of each cell in it and never clear it, then create a function in your adapter that return with this array, here you cal add it's items.

How to call a map fragment from another class

My content view is a Listview named as ftagment top and it displaying to another xml named SinglePackageActivity. There is a mapfragment inside the SinglePackageActivity and I need to set the lat and long to it.
How can I call the map fragment inside the SinglePackageActivity .
My code is below:
Fragment_toplist
<RelativeLayout
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:orientation="vertical"
android:id="#+id/fri"
android:background="#fff">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lvMovies" />
<FrameLayout
android:id="#+id/maincontainer"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
activity_singlepackage
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
android:fitsSystemWindows="true"
app:itemBackground="#drawable/list_item_bg_pressed"
app:itemIconTint="#fff"
app:layout_collapseParallaxMultiplier="1.0"
tools:context="com.panenviron.dtpcthrissur.activity.SinglePackageActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbara"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"
android:weightSum="1"/>
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:id="#+id/lat"/>
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:id="#+id/Long"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/list_item_bg_pressed">
<!-- Let's add fragment -->
<FrameLayout
android:id="#+id/framei"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!---
Navigation view to show the menu items
-->
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#drawable/list_item_bg_pressed">
<FrameLayout
android:id="#+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true">
<RelativeLayout
android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<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:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.panenviron.nav_smp.Bottom_Navigation">
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<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:background="#fff"
android:orientation="horizontal">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/slider"
android:layout_width="match_parent"
android:layout_height="210dp"
android:scaleType="fitXY"
android:background="#drawable/thrissur_head" />
<ImageView
android:id="#+id/imageView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView16"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/slider"
android:layout_marginTop="8dp"
android:src="#drawable/thrissur_bmap" />
<LinearLayout
android:id="#+id/l1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/textView18"
android:orientation="horizontal">
</LinearLayout>
<LinearLayout
android:id="#+id/l2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/l1"
android:orientation="horizontal">
</LinearLayout>
<LinearLayout
android:id="#+id/l3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/l2"
android:orientation="horizontal">
<fragment
android:id="#+id/glmap"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:layout_marginTop="25dp"/>
<TextView
android:id="#+id/textView21"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/book"
android:layout_marginBottom="10dp"
android:layout_marginTop="22dp"
android:fontFamily="cursive"
android:gravity="center"
android:paddingTop="10dp"
android:text="Be Share With"
android:textAllCaps="false"
android:textColor="#android:color/background_dark"
android:textSize="16sp"
android:textStyle="bold" />
<ImageButton
android:id="#+id/imageButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView21"
android:layout_toLeftOf="#+id/imageButton5"
android:layout_toStartOf="#+id/imageButton5"
android:background="#fff"
app:srcCompat="#mipmap/facebook" />
<ImageButton
android:id="#+id/imageButton5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView21"
android:layout_centerHorizontal="true"
android:background="#fff"
app:srcCompat="#mipmap/google" />
<ImageButton
android:id="#+id/imageButton8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView21"
android:layout_toEndOf="#+id/imageButton5"
android:layout_toRightOf="#+id/imageButton5"
android:background="#fff"
app:srcCompat="#mipmap/twitter" />
<Button
android:id="#+id/button14"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/imageButton5"
android:layout_marginTop="24dp"
android:background="#android:color/background_dark"
android:text="SEE MORE ON DTPCThrissur.COM"
android:textColor="#android:color/background_light"
android:textStyle="bold" />
<ImageButton
android:id="#+id/book"
android:layout_width="wrap_content"
android:layout_height="110dp"
android:layout_below="#+id/textView19"
android:layout_centerHorizontal="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#drawable/bb" />
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/l4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/l3"
android:orientation="horizontal">
</LinearLayout>
<Button
android:id="#+id/find_kuttanad"
android:layout_width="match_parent"
android:layout_height="25dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView18"
android:background="#color/cardview_shadow_start_color"
android:fontFamily="serif"
android:gravity="center"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:text="Find more about Thrissur"
android:textAllCaps="false"
android:textColor="#075070"
android:textSize="15sp"
android:textStyle="bold" />
<ProgressBar
android:id="#+id/progressBars"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/slider"
android:layout_centerHorizontal="true"
android:layout_marginBottom="78dp" />
</RelativeLayout>
</ScrollView>
</LinearLayout>
</FrameLayout>
</LinearLayout>
</RelativeLayout>
</FrameLayout>
<TextView
android:id="#+id/coders"
android:layout_width="0dp"
android:layout_height="0dp" />
</RelativeLayout>
</FrameLayout>
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_toplist);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
dialog = new SpotsDialog(this, R.style.Custom);
dialog.setCancelable(false);
dialog.setMessage("Loading. Please wait...");
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(glmap);
// mapFragment.getMapAsync(SinglePackageActivity.this);
Bundle bundle = getIntent().getExtras();
String str = bundle.getString("my_string");
int a = Integer.parseInt(str);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config); // Do it on Application start
lvMovies = (ListView) findViewById(R.id.lvMovies);
final String URL_TO_HIT = "http://softwaresolution.com/ItemDetailsApi.aspx?code=" + a;
new JSONTask().execute(URL_TO_HIT);
}
public class JSONTask extends AsyncTask<String, String, List<ItemModel>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
#Override
protected List<ItemModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("Item");
List<ItemModel> movieModelList = new ArrayList<>();
Gson gson = new Gson();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
ItemModel DModel = gson.fromJson(finalObject.toString(), ItemModel.class); // a single line json parsing using Gson
//
movieModelList.add(DModel);
}
return movieModelList;
} 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(final List<ItemModel> result) {
super.onPostExecute(result);
dialog.dismiss();
if (result != null) {
MovieAdapter adapter = new MovieAdapter(getApplicationContext(), R.layout.activity_singlepackage, result);
lvMovies.setAdapter(adapter);
}
}
}
public class MovieAdapter extends ArrayAdapter {
private List<ItemModel> movieModelList;
private int resource;
private LayoutInflater inflater;
public MovieAdapter(Context context, int resource, List<ItemModel> objects) {
super(context, resource, objects);
movieModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(resource, null);
holder.url = (ImageView) convertView.findViewById(R.id.slider);
holder.Name = (TextView) convertView.findViewById(R.id.textView14);
holder.fdetail = (TextView) convertView.findViewById(R.id.textView20);
holder.LAT = (TextView) convertView.findViewById(R.id.lat);
holder.Lng = (TextView) convertView.findViewById(R.id.Long);
holder.sdeta = (TextView) convertView.findViewById(R.id.textView16);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final ProgressBar progressBar = (ProgressBar) convertView.findViewById(R.id.progressBars);
// Then later, when you want to display image
final ViewHolder finalHolder = holder;
ImageLoader.getInstance().displayImage(movieModelList.get(position).getUrl(), holder.url, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
progressBar.setVisibility(View.VISIBLE);
finalHolder.url.setVisibility(View.INVISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
progressBar.setVisibility(View.GONE);
finalHolder.url.setVisibility(View.INVISIBLE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
progressBar.setVisibility(View.GONE);
finalHolder.url.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
progressBar.setVisibility(View.GONE);
finalHolder.url.setVisibility(View.INVISIBLE);
}
});
holder.Name.setText("" + movieModelList.get(position).getName());
holder.fdetail.setText("" + movieModelList.get(position).getDetails());
holder.LAT.setText("" + movieModelList.get(position).getLAT());
holder.Lng.setText("" + movieModelList.get(position).getlong1());
holder.sdeta.setText("" + movieModelList.get(position).getDetails() + "...");
Button button = (Button) convertView.findViewById(R.id.b_map);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Opening Google Map", Toast.LENGTH_SHORT).show();
Uri gmmIntentUri = Uri.parse("http://maps.google.com/maps?=" + "saddr=" + movieModelList.get(position).getLAT() + "," +
movieModelList.get(position).getlong1() + "&daddr=" + movieModelList.get(position).getLAT() + "," + movieModelList.get(position).getlong1());
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
if (mapIntent.resolveActivity(ItemActivity.this.getPackageManager()) != null)
{
startActivity(mapIntent);
} else
{
Toast.makeText(getContext(), "Google Map Not Available", Toast.LENGTH_SHORT).show();
}
}
});
return convertView;
}
class ViewHolder {
private ImageView url;
private TextView Name;
private TextView fdetail;
private TextView LAT;
private TextView Lng;
private TextView sdeta;
}
}

Get Value from editText in Fragment to Send With Asynctask

i have fragment for send data to server, but my edit Text always null, no error in application only cannot get the value from edit text
this is my XML
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
<Button
android:text="Submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/submit_laporan"
android:layout_below="#+id/desc_masalah"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp" />
<TextView
android:text="Judul"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView5"
android:textSize="18sp"
android:layout_alignParentTop="true"
android:layout_marginTop="14dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:paddingLeft="10dp" />
<TextView
android:text="Deskripsi Masalah"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="19dp"
android:id="#+id/textView4"
android:textSize="18sp"
android:layout_below="#+id/judul_masalah"
android:layout_alignLeft="#+id/textView5"
android:layout_alignStart="#+id/textView5"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:paddingLeft="10dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:layout_marginTop="13dp"
android:id="#+id/desc_masalah"
android:layout_below="#+id/textView4"
android:layout_alignLeft="#+id/textView4"
android:layout_alignStart="#+id/textView4"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:paddingLeft="10dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/judul_masalah"
android:layout_marginTop="13dp"
android:layout_below="#+id/textView5"
android:layout_alignLeft="#+id/textView5"
android:layout_alignStart="#+id/textView5"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:paddingLeft="10dp" />
</RelativeLayout>
and this is my JAVA
public class Report extends Fragment{
EditText judul_masalah, desc_masalah;
Button submit_laporan;
//public Report(){}
//RelativeLayout view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.laporan, container, false);
getActivity().setTitle("Pelaporan");
/*submit_laporan.setOnClickListener(new View.OnClickListener(){
String newJudul = judul_masalah.getText().toString();
String newDeskripsi = desc_masalah.getText().toString();
#Override
public void onClick(View v){
Toast.makeText(getActivity(), newJudul,
Toast.LENGTH_LONG).show();
new sendData().execute(newJudul,newDeskripsi);
}
});*/
return V;
}
public void onViewCreated(View V, Bundle savedInstanceState){
judul_masalah = (EditText) V.findViewById(R.id.judul_masalah);
desc_masalah = (EditText) V.findViewById(R.id.desc_masalah);
submit_laporan = (Button) V.findViewById(R.id.submit_laporan);
submit_laporan.setOnClickListener(new View.OnClickListener(){
String newJudul = judul_masalah.getText().toString();
String newDeskripsi = desc_masalah.getText().toString();
#Override
public void onClick(View v){
Toast.makeText(getActivity(), newJudul,
Toast.LENGTH_LONG).show();
//new sendData().execute(newJudul,newDeskripsi);
}
});
}
public class sendData extends AsyncTask<String, String, JSONObject>{
HttpURLConnection conn;
URL url = null;
JSONParser jsonParser = new JSONParser();
private static final String TAG_INFO = "info";
private static final String LAPORAN_URL = "URL";
#Override
protected JSONObject doInBackground(String... args) {
try {
HashMap<String, String> params = new HashMap<>();
params.put("judul", args[0]);
params.put("deskripsi", args[1]);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LAPORAN_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
String info = "";
if (json != null) {
//Toast.makeText(LoginActivity.this, json.toString(),
//Toast.LENGTH_LONG).show();
try {
info = json.getString(TAG_INFO);
} catch (JSONException e) {
e.printStackTrace();
}
}
if(info.equals("Success")) {
Toast.makeText(getActivity(), "Data Berhasil Disimpan",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getActivity(), "Data Gagal Disimpan",
Toast.LENGTH_LONG).show();
}
}
}
}
anyone can help me whats wrong with my code
You have to place your getText() inside the methode onClick(). Now it's outside and doesn't work.
The line :
"String newJudul = judul_masalah.getText().toString();"
after the line:
"public void onClick(View v){"

How to change my chat layout output as like whatsapp chat layout?

I am developing an android application, In that i have a chat window layout at present my chat window ouput is looking below (when i am send the message to others)
but i am expected my output as,
My layout code is below,
<?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"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:paddingLeft="10dp">
<TextView
android:id="#+id/txtInfo"
android:layout_width="wrap_content"
android:layout_height="30sp"
android:layout_gravity="right"
android:layout_marginRight="50dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:textSize="12sp"
android:textColor="#color/lightred"
android:textStyle="italic"
/>
<TextView
android:id="#+id/txtMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp"
android:layout_marginRight="200dp"
android:background="#color/grey"
android:textColor="#color/white"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:textStyle="italic|bold"
/>
</LinearLayout>
My programming code is below,
public class MessagesListAdapter extends BaseAdapter {
private Context context;
private List<ChatMessageObjects> messagesItems;
public MessagesListAdapter(Context context, List<ChatMessageObjects> navDrawerItems) {
this.context = context;
this.messagesItems = navDrawerItems;
}
#Override
public int getCount() {
return messagesItems.size();
}
#Override
public Object getItem(int position) {
return messagesItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ChatMessageObjects m = messagesItems.get(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (messagesItems.get(position).getMessage_type() == Constants.IS_TYPE_CHAT_IMAGE) {
convertView = mInflater.inflate(R.layout.chat_image,
null);
ImageView imageView = (ImageView) convertView.findViewById(R.id.imgView);
TextView imageLabel = (TextView) convertView.findViewById(R.id.lblImage);
if (messagesItems.get(position).isSelf() == 0) {
Log.i(Constants.TAG, " the value is from others");
try {
URL url = new URL(messagesItems.get(position).getMessage());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
imageView.setImageBitmap(BitmapFactory.decodeStream(input));
} catch (IOException e) {
Log.i(Constants.TAG, e.toString());
}
} else if (messagesItems.get(position).isSelf() == 1) {
Log.i(Constants.TAG, " the value is itself");
imageView.setImageURI(Uri.fromFile(imgFile));
imageLabel.setText(messagesItems.get(position).getFromName());
}
} else if (messagesItems.get(position).getMessage_type() == Constants.MESSAGE_TYPE_MSG) {
// message belongs to you, so load the right aligned layout
if (messagesItems.get(position).isSelf() == 1) {
convertView = mInflater.inflate(R.layout.chat_message_right,
null);
TextView txtMsg = (TextView) convertView.findViewById(R.id.txtMsg);
//date and time declared on date here
TextView date = (TextView) convertView.findViewById(R.id.txtInfo);
try {
//actualDate contains date "(i.e)27-Aug-2015 6:20:25 am/pm" in this format
String actualDate = m.getDate();
Date FormatDate = new SimpleDateFormat("dd-MMM-yyyy h:mm:ss a").parse(actualDate);
//actualDate converted from "(i.e)27-Aug-2015 6:20:25 am/pm" to "6:20 pm" in this
//format for display the chat time for every chat message .
dateResult = new SimpleDateFormat("h:mm a").format(FormatDate);
} catch (ParseException e) {
e.printStackTrace();
}
date.setText(dateResult);//date display as like this"6:20pm"
txtMsg.setText(m.getMessage());
} else if (messagesItems.get(position).isSelf() == 0) {
// message belongs to other person, load the left aligned layout
convertView = mInflater.inflate(R.layout.chat_message_left,
null);
TextView lblFrom = (TextView) convertView.findViewById(R.id.lblMsgFrom);
TextView txtMsg = (TextView) convertView.findViewById(R.id.txtMsg);
//date and time added here
TextView date = (TextView) convertView.findViewById(R.id.txtInfo);
txtMsg.setText(m.getMessage());
date.setText(m.getDate());
}
}
return convertView;
}
}
}
how can i achieve my output as i am expected. Please suggest me what i am need to change.
Try this.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:emojicon="http://schemas.android.com/apk/res-auto"
android:id="#+id/view_send_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:gravity="end"
android:layout_margin="10dp"
android:orientation="vertical"
android:visibility="visible">
<TextView
android:id="#+id/txt_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="3dp"
android:layout_marginEnd="20dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="20dp"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:lineSpacingExtra="1dp"
android:minWidth="150dp"
android:padding="5dp"
android:textColor="#color/lightred"
android:singleLine="false"
android:textSize="18sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_marginEnd="30dp"
android:layout_marginRight="30dp"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingBottom="7dp">
<TextView
android:id="#+id/txt_send_timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="15dp"
android:layout_marginStart="15dp"
android:background="#color/grey"
android:textColor="#color/white"
android:textSize="13sp" />
</LinearLayout>

How to show data from DB as a checkbox list in android

I have a DB in mysql, I want to show all the data in the DB as a list of chkbox with the data from the DB . and after selection of few checkbox i can fire query to DB for certain data about the selected ones. I have tried using listView below is my JAVA file and xml
here is JAVA file
public class BdaySelect extends Activity {
private String jsonResult;
private String url = "http://10.0.2.2/markit/login.php";
private ListView listView;
private TextView textv1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bday_select);
listView = (ListView) findViewById(R.id.listView1);
textv1=(TextView)findViewById(R.id.textView1);
accessWebService();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.getString("emp_name");
String number = jsonChildNode.getString("emp_no");
//String chkBoxNo = Integer.toString(i);
//String chkBoxName = "chk"+chkBoxNo;
//CheckBox chkBoxName = new CheckBox(this);
String outPut = name + "-" + number;
employeeList.add(createEmployee("employees", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
android.R.layout.simple_list_item_1,
new String[] { "employees" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createEmployee(String name, String number) {
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(name, number);
return employeeNameNo;
}
}
XML file
<?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="vertical" >
<TableRow
android:id="#+id/tableRow2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#29001F"
android:gravity="center" >
<ImageView
android:id="#+id/imageView2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/bck" />
<Space
android:layout_width="100dp"
android:layout_height="30dp"
android:layout_weight="2" />
<ImageButton
android:id="#+id/imageButton1"
android:paddingRight="10dp"
android:background="#29001F"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/setting2" />
</TableRow>
<TableRow
android:background="#29001F"
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center" >
<TextView
android:id="#+id/textView1"
android:layout_width="0dp"
android:gravity="center"
android:textColor="#FFFFFF"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="SELECT"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="0dp"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#94808F"
android:text="DISCOUNT"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:layout_width="0dp"
android:gravity="center"
android:layout_height="wrap_content"
android:textColor="#94808F"
android:layout_weight="1"
android:text="SEND"
android:textAppearance="?android:attr/textAppearanceMedium" />
</TableRow>
<Space
android:layout_width="match_parent"
android:layout_height="20dp" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TableRow
android:id="#+id/tableRow6"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="102dp"
android:gravity="right"
android:paddingRight="30dp" >
<Button
android:id="#+id/butBdaySelectNext"
android:layout_width="80dp"
android:layout_height="35dp"
android:layout_gravity="center"
android:background="#drawable/arrownext"
android:paddingRight="15dp"
android:text="Next"
android:textColor="#FFFFFF" />
</TableRow>
</LinearLayout>
The basic concept to create a custom list view in android starts with a custom view .xml that will correspond to the layout of how each individual item will look like. For example if you want each item to have a textview for the name and a checkbox your custom layout will only contain a linear (horizontal) layout with a textview and a check box in. After that on your activity you'll need to create a class that extends Base Adapter. The main roll of this class is to get the data you want (from an array for example) and inflate that info to the layout that you created. I found this tutorial that may help you:
http://androidexample.com/How_To_Create_A_Custom_Listview_-_Android_Example/index.php?view=article_discription&aid=67&aaid=92

Categories

Resources