Toast未显示自定义列表视图

时间:2016-04-24 09:28:17

标签: android listview toast

我正在编写将从网站获取json数组的应用程序。该json数组包括标题,描述和图像。我编写代码和自定义列表视图适配器。列表正在显示但现在我需要显示toast以获取单击哪个列表项。我尝试了很多并搜索但没有得到解决方案。

请帮忙。

  

ViewCampaigns.java(作为Main.java处理)

package com.therightsol.saveasoul.saveasoul;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class viewcampaigns extends AppCompatActivity {

    // Progress Dialog
    private ProgressDialog pDialog;
    private ProgressBar progress;
    ListView lv = null;
    MyData arrData[] = null;
    ArrayList<String> arrlist = null;
    // url to get all products list
    private static String url_all_campaigns = "http://therightsol.com/saveasoul125/mobile/get_all_campaigns_jsonArr";
    private AlertDialog alert;
    // products JSONArray
    String response = "";
    JSONArray jsonArr = null;
    ArrayAdapter<String> campaignAdapter;
    ListAdapter la;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_campaigns);



        progress = (ProgressBar) findViewById(R.id.progressBar1);
        lv = (ListView) findViewById(R.id.listView);

        ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (mWifi.isConnected()) {
            // Do whatever
            // Loading campaigns in Background Thread
            LoadAllCampaigns task = new LoadAllCampaigns();
            task.execute();

        }else {
            /*new AlertDialog.Builder(viewcampaigns.this)
                    .setTitle("Your Alert")
                    .setMessage("Your Message")
                    .setCancelable(false)
                    .setPositiveButton("ok", new OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // Whatever...
                        }
                    }).create().show();*/
        }



        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String t = (String) la.getItem(position);
                Toast.makeText(getApplicationContext(),"HIIII", Toast.LENGTH_SHORT).show();
            }
        });


    }

    class MyData{
        public String imgpath;
        public String title;
        public String shrtdes;

        public MyData(){
            super();
        }

        public MyData(String path, String t, String desc){
            this.imgpath = path;
            this.title = t;
            this.shrtdes = desc;
        }
    }




    /**
     * Background Async Task to Load all campaigns by making HTTP Request
     * */
    class LoadAllCampaigns extends AsyncTask<String, Void, String> {




        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
         protected void onPreExecute() {
            //Log.i("save a soul", "I am in preexecute.");
            super.onPreExecute();
            pDialog = new ProgressDialog(viewcampaigns.this);
            pDialog.setMessage("Loading Campaigns. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All campaigns from url
         * */
        protected String doInBackground(String... params) {
            Log.i("save a soul", "I am in doinbackground");
            //http post
            try{
                //System.out.println("The output of : doInBackground " +params[0]);
                URL url = new URL(url_all_campaigns);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.setConnectTimeout(10000);
                conn.setReadTimeout(10000);
                System.out.println("The output of getResponsecode: " + conn.getResponseCode());
                conn.connect();

                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                while ((line = br.readLine()) != null) {
                     response += line;

                }
                return response;
            } catch (IOException e) {

                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            pDialog.hide();
            // updating UI from Background Thread

            Log.i("Save Test", s);

            try {
                jsonArr = new JSONArray(response);


                int l = jsonArr.length();
                arrData = new MyData[l];

                for (int i = 0; i < jsonArr.length(); i++)
                {
                    JSONObject jsonObj = jsonArr.getJSONObject(i);

                    System.out.println(jsonObj);
                    String path = String.valueOf(jsonObj.getString("campaign_image_path"));
                    String title = String.valueOf(jsonObj.getString("campaign_title"));
                    String shrtdes = String.valueOf(jsonObj.getString("campaign_short_description"));

                    path = "http://therightsol.com/saveasoul125/" + path;

                    Log.i("save a soul", "I am in onPostExecute");

                    arrData[i] = new MyData(path, title, shrtdes);
                }


                la = new campaigns_customAdapter(viewcampaigns.this, R.layout.campaignslist, arrData );


                /*ListAdapter la = new campaigns_customAdapter(
                  viewcampaigns.this, title, camp
                );*/


                lv.setAdapter(la);

                lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        String t = (String) la.getItem(position);
                        Toast.makeText(getApplicationContext(),position, Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
  

广告系列自定义适配器

package com.therightsol.saveasoul.saveasoul;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;


public class campaigns_customAdapter extends ArrayAdapter<viewcampaigns.MyData> {


    viewcampaigns.MyData [] obj;
    Context context;
    int resourse;


    public campaigns_customAdapter(Context context, int resource, viewcampaigns.MyData[] objects) {

        super(context, resource, objects);

        this.context=context;
        this.resourse=resource;
        this.obj=objects;

    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        //View v = inflater.inflate(R.layout.campaignslist, parent, false);

        View row=inflater.inflate(resourse,parent,false);


        // Getting Views
        TextView title = (TextView) row.findViewById(R.id.campaignTitle);
        TextView shrtDesc = (TextView) row.findViewById(R.id.shortDescription);
        ImageView campaignimg = (ImageView) row.findViewById(R.id.campaignimage);


        title.setText( obj[position].title );
        shrtDesc.setText( obj[position].shrtdes);

        // Inflating Image
        try {
            URL url = new URL(obj[position].imgpath);

            new DownloadImageTask(campaignimg)
                    .execute(url.toString());

        }  catch (MalformedURLException e) {
            e.printStackTrace();
        } 
        return row;
    }


    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }
}
  

活动广告系列.xml(具有列表视图的XML文件)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:indeterminate="false"
        android:max="10"
        android:padding="4dip" >
    </ProgressBar>

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        />
</RelativeLayout>
  

广告系列列表(列表项的自定义布局的XML)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="100dp"
        android:layout_height="100dp"
        android:id="@+id/campaignimage"
        android:backgroundTintMode="src_over"
        android:clickable="false"
        android:cropToPadding="false"
        android:layout_alignTop="@+id/campaignTitle"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="6dp"
        android:layout_marginRight="6dp"
        android:maxLength="4"
        android:ellipsize="end"
        android:layout_marginBottom="0dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Title"
        android:id="@+id/campaignTitle"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/campaignimage"
        android:layout_alignEnd="@+id/campaignimage"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true"
        android:capitalize="words"
        android:textStyle="bold"
        android:layout_marginLeft="112dp"
        android:layout_marginRight="12dp"
        android:layout_marginTop="6dp"
        android:typeface="monospace"
        android:textColor="#1f6b88"
        android:textSize="16dp"
        android:layout_marginBottom="4dp"
        android:padding="3dp" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="66dp"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Small Text"
        android:id="@+id/shortDescription"
        android:typeface="sans"
        android:textStyle="normal"
        android:textSize="12dp"
        android:paddingLeft="3dp"
        android:textColor="#2586a9"
        android:layout_below="@+id/campaignTitle"
        android:layout_alignLeft="@+id/campaignTitle"
        android:layout_alignStart="@+id/campaignTitle"
        android:maxLength="14"
        android:ellipsize="end"
        android:layout_marginRight="12dp"
        android:paddingTop="2dp"
        android:paddingRight="3dp"
        android:paddingBottom="3dp" />

</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

不要在Toast语句中使用getApplicationContext(),而是使用ViewCampaigns.this。它应该可以解决你的问题。