Search code examples
javaandroidlistviewtextviewcustom-adapter

Getting text from Textview in listview with custom adapter


I have a Listview with 3 Textviews, and I want to retrieve the specific data from these textviews on the clicked Item. For now I'm trying to get the data from the first textview. The problem is, it doesn't matter if I click on Item 1, 2, 3 or etc because I'll always get the text from first Item on the listview. I think the problem is because I don't know how to specific which data I want, from which Item. This is my code: estoque.java:

package com.example.asus.mingausfashionmoda;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;

public class estoque extends ListActivity {
    String qntES;
    String pcES;
    String pvES;
    //list
    protected List<ParseObject> mObject;
    String variable = "camisa";
    // declare class variables
    private ArrayList<Item> m_parts = new ArrayList<Item>();
    private Runnable viewParts;
    private ItemAdapter m_adapter;


    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.estoque_main);

        // instantiate our ItemAdapter class
        m_adapter = new ItemAdapter(this, R.layout.list_item, m_parts);
        setListAdapter(m_adapter);

        // here we are defining our runnable thread.
        viewParts = new Runnable(){
            public void run(){
                handler.sendEmptyMessage(0);
            }
        };

        // here we call the thread we just defined - it is sent to the handler below.
        Thread thread =  new Thread(null, viewParts, "MagentoBackground");
        thread.start();
    }



    private Handler handler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            // create some objects
            // here is where you could also request data from a server
            // and then create objects from that data.

            ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(variable);
            query.findInBackground(new FindCallback<ParseObject>() {
                @Override
                public void done(List<ParseObject> statuslist, ParseException e) {
                    if(e != null){
                        //data successfully retrieved
                        Toast.makeText(estoque.this, "Houve um erro inesperado, tente novamente mais tarde", Toast.LENGTH_LONG).show();
                    }else{
                        //something went wrong
                        mObject = statuslist;
                        for(int i = 0; i<mObject.size(); i++) {
                            ParseObject statusObject = mObject.get(i);
                            String username = statusObject.getString("user");
                            Number qntE = statusObject.getNumber("qnt");
                            qntES = String.valueOf(qntE);
                            Number pcE = statusObject.getNumber("precoC");
                            pcES = String.valueOf(pcE);
                            Number pvE = statusObject.getNumber("precoV");
                            pvES = String.valueOf(pvE);

                            m_parts.add(new Item(qntES, pvES, pcES));

                            m_adapter = new ItemAdapter(estoque.this, R.layout.list_item, m_parts);
                            setListAdapter(m_adapter);
                        }
                    }
                }
            });

            final ListView lv = (ListView) findViewById(android.R.id.list);
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
                    TextView ttd = (TextView)findViewById(R.id.toptextdata);
                    System.out.println(ttd.getText().toString());
                    }
            });
        }
    };
}

ItemAdapter.java:

package com.example.asus.mingausfashionmoda;

/**
 * Created by ASUS on 21/12/2015.
 */
import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class ItemAdapter extends ArrayAdapter<Item> {

    // declaring our ArrayList of items
    private ArrayList<Item> objects;

    /* here we must override the constructor for ArrayAdapter
    * the only variable we care about now is ArrayList<Item> objects,
    * because it is the list of objects we want to display.
    */
    public ItemAdapter(Context context, int textViewResourceId, ArrayList<Item> objects) {
        super(context, textViewResourceId, objects);
        this.objects = objects;
    }

    /*
     * we are overriding the getView method here - this is what defines how each
     * list item will look.
     */
    public View getView(int position, View convertView, ViewGroup parent){

        // assign the view we are converting to a local variable
        View v = convertView;
        /** v.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        System.out.println("CARALHO VC CRICOU" + objects);
        }
        }); */
        // first check to see if the view is null. if so, we have to inflate it.
        // to inflate it basically means to render, or show, the view.
        if (v == null) {
            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = inflater.inflate(R.layout.list_item, null);
        }

        /*
         * Recall that the variable position is sent in as an argument to this method.
         * The variable simply refers to the position of the current object in the list. (The ArrayAdapter
         * iterates through the list we sent it)
         *
         * Therefore, i refers to the current Item object.
         */
        Item i = objects.get(position);

        if (i != null) {

            // This is how you obtain a reference to the TextViews.
            // These TextViews are created in the XML files we defined.

            TextView tt = (TextView) v.findViewById(R.id.toptext);
            TextView ttd = (TextView) v.findViewById(R.id.toptextdata);
            TextView mt = (TextView) v.findViewById(R.id.middletext);
            TextView mtd = (TextView) v.findViewById(R.id.middletextdata);
            TextView bt = (TextView) v.findViewById(R.id.bottomtext);
            TextView btd = (TextView) v.findViewById(R.id.desctext);

            // check to see if each individual textview is null.
            // if not, assign some text!

            if (tt != null){
                tt.setText("Quantidade: ");
            }
            if (ttd != null){
                ttd.setText(i.getName());
            }
            if (mt != null){
                mt.setText("Preco compra: ");
            }
            if (mtd != null){
                mtd.setText("$" + i.getPrice());
            }
            if (bt != null){
                bt.setText("Preco venda: ");
            }
            if (btd != null){
                btd.setText(i.getDetails());
            }
        }

        // the view must be returned to our activity
        return v;
    }
}

Item.java:

package com.example.asus.mingausfashionmoda;

import android.widget.TextView;

public class Item {
    private String details;
    private String name;
    private String price;


    public Item(){

    }

    public Item(String i, String d, String p){
        this.details = d;
        this.name = i;
        this.price = p;

    }

    public String getDetails() {
        return details;
    }

    public void setDetails(String details) {
        this.details = details;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }
}

estoque_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btnSelecionarQuery"
        android:text="ROUPA"
        />
    <ListView
        android:id="@+id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:clickable="true"
        />
    <TextView
        android:id="@+id/android:empty"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="No items to display."/>

</LinearLayout>

list_item.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="?android:attr/listPreferredItemHeight"

    android:padding="6dip">
    <!-- Item Name -->
    <TextView
        android:id="@+id/toptext"

        android:layout_width="wrap_content"
        android:layout_height="26dip"

        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"

        android:textStyle="bold"
        android:singleLine="true"
        android:ellipsize="marquee"
        />

    <!-- Actual Item Name Data -->
    <TextView
        android:id="@+id/toptextdata"

        android:layout_width="fill_parent"
        android:layout_height="wrap_content"

        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@id/toptext"

        android:singleLine="true"
        android:ellipsize="marquee"
        />

    <!-- Price Tag -->
    <TextView
        android:id="@+id/middletext"

        android:layout_width="wrap_content"
        android:layout_height="26dip"

        android:layout_alignParentLeft="true"
        android:layout_below="@id/toptext"

        android:textStyle="bold"
        android:gravity="center_vertical"
        />

    <!-- Actual Price Data -->
    <TextView
        android:id="@+id/middletextdata"

        android:layout_width="fill_parent"
        android:layout_height="26dip"

        android:layout_alignParentRight="true"
        android:layout_below="@id/toptext"
        android:layout_toRightOf="@id/middletext"

        android:gravity="center_vertical"
        />

    <!-- Description Tag -->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"

        android:layout_alignParentRight="true"
        android:layout_below="@id/middletext"

        android:textStyle="bold"
        android:id="@+id/bottomtext"
        android:singleLine="false"
        />
    <!-- This is the actual description -->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"

        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_below="@id/bottomtext"


        android:id="@+id/desctext"
        android:singleLine="false"
        />
</RelativeLayout>

To make it easier for your understanding, this is where I get the clicked item from the listview and try to get it's first textview text(This is on estoque.java):

final ListView lv = (ListView) findViewById(android.R.id.list);
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
                    TextView ttd = (TextView)findViewById(R.id.toptextdata);
                    System.out.println(ttd.getText().toString());
                    }
            });

Thanks.


Solution

  • Want to access View from clicked row layout of ListView, use second parameter of onItemClick to call findViewById like:

    TextView ttd = (TextView) myView.findViewById(R.id.toptextdata);