0

I have searched on google for a long time but I can't figure out how to do it.

I am filling a listview with an item containing 3 textview (1 to get a data) and 2 imagebutton

I would like to get the 3rd textview text when clicking the 1st button, here is my code until now:

Search.java

 public class Search extends ListActivity {

    private TextView mTextView;
     private ListView mListView;
     private String query;
     private String queryencoded;
     private static Context mContext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search);

        mTextView = (TextView) findViewById(R.id.text);
        mListView = (ListView) findViewById(android.R.id.list);

        mContext = getApplicationContext();

        // Get the intent, verify the action and get the query
        Intent intent = getIntent();
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
          query = intent.getStringExtra(SearchManager.QUERY);
        try {
            queryencoded = URLEncoder.encode(query, "utf-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
          Log.w("myApp", "aaaaa");
          Toast.makeText(Search.this, (query), Toast.LENGTH_LONG).show();


          mTextView.setText("testing connexion");

          if(isConnected()){
              mTextView.setText("Loading...");
              new HttpAsyncTask().execute("my json url");
          }
          else{
              mTextView.setBackgroundColor(0xffcc0000);
              mTextView.setText("You are NOT connected");
          }
        }
    }

    public boolean isConnected(){
         ConnectivityManager connMgr = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
             NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
             if (networkInfo != null && networkInfo.isConnected()) 
                 return true;
             else
                 return false;   
     }

    public static String GET(String url){
         InputStream inputStream = null;
         String result = "";
         try {

             // create HttpClient
             HttpClient httpclient = new DefaultHttpClient();

             // make GET request to the given URL
             HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

             // receive response as inputStream
             inputStream = httpResponse.getEntity().getContent();

             // convert inputstream to string
             if(inputStream != null)
                 result = convertInputStreamToString(inputStream);
             else
                 result = "Did not work!";

         } catch (Exception e) {
             Log.d("InputStream", e.getLocalizedMessage());
         }

         return result;
     }

    private static String convertInputStreamToString(InputStream inputStream) throws IOException{
         BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
         String line = "";
         String result = "";
         while((line = bufferedReader.readLine()) != null)
             result += line;

         inputStream.close();
         return result;
     }

     private class HttpAsyncTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... urls) {

                return GET(urls[0]);
            }
            // onPostExecute displays the results of the AsyncTask.
            @Override
            protected void onPostExecute(String result) {
                Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();

                try {
                    JSONObject jsonobject = new JSONObject(result);
                    mTextView.setText((String) jsonobject.get("count"));

                    Integer count = Integer.parseInt((String) jsonobject.get("count"));

                    if (count == 0) {
                        // There are no results
                        mTextView.setText(getString(R.string.no_results, query));
                    } else {
                        // Display the number of results
                        String countString = getResources().getQuantityString(R.plurals.search_results,
                                count, new Object[] {count, query});
                        mTextView.setText(countString);



                        // Specify the columns we want to display in the result
                        String[] from = new String[] { "title",
                                                       "artist",
                                                       "duration",
                                                       "url"};

                        // Specify the corresponding layout elements where we want the columns to go
                        int[] to = new int[] { R.id.title,
                                               R.id.artist,
                                               R.id.duration,
                                               R.id.url};

                        // -- container for all of our list items
                        List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();

                        // -- list item hash re-used
                        Map<String, String> group;

                        //create audio json array
                        JSONArray audios = jsonobject.getJSONArray("audio");

                        for (int i = 0; i < audios.length(); i++) {
                            JSONObject audio = audios.getJSONObject(i);

                            //get info
                            String title = audio.getString("title");
                            String artist = audio.getString("artist");
                            String duration = audio.getString("duration");
                            String durationformated = getDurationString(Integer.parseInt(duration));
                            String url = audio.getString("url");

                            // -- create record
                            group = new HashMap<String, String>();

                            group.put( "title", title );
                            group.put( "artist",  artist );
                            group.put( "duration",  durationformated );
                            group.put( "url",  url );

                            groupData.add(group);
                        }

                        SimpleAdapter adapter = new SimpleAdapter(mContext , groupData, R.layout.result, 
                                from,
                                 to );

                        setListAdapter( adapter );
                    }
                } 

                catch (JSONException e)           
                 {                
                    // TODO Auto-generated catch block
                    Log.w("myApp", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");   
                    Log.w("myApp", e);    
                    Log.w("myApp", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); 
                 }
           }
        }

        private String getDurationString(int seconds) {

            int hours = seconds / 3600;
            int minutes = (seconds % 3600) / 60;
            seconds = seconds % 60;

            return twoDigitString(minutes) + ":" + twoDigitString(seconds);
        }

        private String twoDigitString(int number) {

            if (number == 0) {
                return "00";
            }

            if (number / 10 == 0) {
                return "0" + number;
            }

            return String.valueOf(number);
        }
 }

search.xml:

 <?xml version="1.0" encoding="utf-8"?>
 <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"
     tools:context=".Search" >

     <TextView
             android:id="@+id/text"
             android:textColor="?android:textColorPrimary"
             android:background="@android:drawable/title_bar"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content" />

     <ListView
             android:id="@android:id/list"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:layout_below="@id/text"
              />

 </RelativeLayout>

result.xml:

 <?xml version="1.0" encoding="utf-8"?>

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:orientation="vertical"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:padding="5dp">

      <TextView
         android:id="@+id/url"
         android:layout_width="0dp"
         android:layout_height="0dp"
         android:visibility="gone"/>

     <TextView
         android:id="@+id/title"
         style="@android:style/TextAppearance.Large"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentLeft="true"
         android:layout_toLeftOf="@+id/play"
         android:singleLine="true"
         android:text="title"
         android:textColor="#000000" />

     <TextView
         android:id="@+id/artist"
         style="@android:style/TextAppearance.Small"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentLeft="true"
         android:layout_below="@id/title"
         android:layout_toLeftOf="@+id/play"
         android:singleLine="true"
         android:text="artist"
         android:textColor="#7D7D7D" />

     <TextView
         android:id="@+id/duration"
         style="@android:style/TextAppearance.Small"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignLeft="@+id/artist"
         android:layout_alignParentBottom="true"
         android:layout_below="@id/artist"
         android:layout_toLeftOf="@+id/play"
         android:singleLine="true"
         android:text="03:24"
         android:textColor="#7D7D7D" />

        <ImageButton
            android:id="@+id/play"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_toLeftOf="@+id/download"
            android:src="@drawable/play" />

        <ImageButton
            android:id="@+id/download"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:layout_alignParentRight="true"
            android:src="@drawable/download" />

 </RelativeLayout>

I have tested the onclick attribute on the image button but it didn t worked: url to my thread

So i searched about the setOnItemClickListener but all I succeed to do is to get a nullpointerexeption.

Please let me know if you have a solution, thank you.

Community
  • 1
  • 1
user3119384
  • 329
  • 4
  • 23
  • Why are you extending `ListActivity`? – hichris123 Jan 02 '14 at 01:14
  • hichris123: I have a searchform on my mainactivity, using the search widget (http://developer.android.com/guide/topics/search/search-dialog.html#UsingSearchWidget) Following android doc, the new activity should extent listactivity – user3119384 Jan 02 '14 at 01:20
  • Post the logcat from the crash so we can see what and where the error is. That is a lot of code for us to search for your error. – codeMagic Jan 02 '14 at 01:20
  • codeMagic: this is the code with that is not giving any error, I would like to know how to implement an onclicklistener for my first imagebutton on result.xml (with id "play") I had error when using the code from my other question but someone told me i was on the wrong way: http://stackoverflow.com/questions/20832685/android-could-not-find-a-method-playaudioview-in-the-activity-class-android – user3119384 Jan 02 '14 at 01:21

1 Answers1

0

You will have to use a custom ListAdapter. Inside the getView() method, find the view you want to watch and attach a listener to it.

A good tutorial on how to implement a custom ListAdapter can be found here: http://www.vogella.com/articles/AndroidListView/article.html. You'll want to look at the example implementation of an ArrayAdapter. Basically, you have to create an object to represent each row of data. Pass an array of those objects to the adapter, which will then populate the views in each list item with that data in the getView() method.

Nathan Walters
  • 4,116
  • 4
  • 23
  • 37
  • Excuse my ignorance, but where exactly is, or should be, the bindView() method? can you give me an example? – user3119384 Jan 02 '14 at 01:29
  • Thank you, it's very late here so I'll check this better tomorow, but I've fastly read the example, and if I am right, I should completly remove the way i'm filling my listview using my simpleadapter and replace it with the arrayadapter? thank you for the help :) – user3119384 Jan 02 '14 at 01:46
  • That is correct! If you run into any problems with this send me a message or add a comment here, I'll do my best to help you out. – Nathan Walters Jan 02 '14 at 01:47
  • I am completly lost. I have started a new "clear" project with a searchview, and textview and a listview inside a fragment. In my json I have an array "audio" containing all the audio information, and my result.xml is still the same, I have created a json object from my http request, and I fill the textview with the count object of my json, now how can I fill the listview from my json audio object following my result.xml layout? Thank you – user3119384 Jan 03 '14 at 00:52