java - 通过 REST API 检索结果并将其显示在新 Activity 的 ListView 中( ListView 出现小问题)

标签 java android listview android-studio android-intent

我正在通过 REST API 从作业站点检索数据。我能够检索数据,甚至可以在搜索按钮后的同一页面中显示该数据。但是,我想在新 Activity 中显示 ListView 。我正在使用 Intent 来做到这一点。但是,不幸的是,我无法证明这一点。一旦我点击它,我的应用程序就会崩溃并且不输出任何内容。

主要 Activity .java 公共(public)类 MainActivity 扩展 Activity {

    //private String url1 = "http://api.openweathermap.org/data/2.5/weather?q=";
    //private String url2 = "&mode=xml";

    EditText queryText;
    EditText locationText;
    EditText sortText;
    EditText fromAgeText;
    ListView responseView;
    // EditText radiusText;
    ProgressBar progressBar;
    EditText jtText;
    EditText chnlText;
    EditText countryText;
    EditText txText;
    static final String API_KEY = "298**70********4";
    static final String API_URL = "http://api.xyz.com/abc/apisearch?";

    ProgressDialog waitProgress;
    EditText startText;
    EditText limitRes;
    EditText filterText;
    EditText userIpText;   //="122.171.57.131";
    EditText radiusText;
    EditText browserText;
    EditText version;
    EditText stText;
    EditText latlongText;

    //private HandleXML obj;
    String finalUrl;
    ArrayList<Result> rList = null;
    ArrayList<Result> resultlist;
    String tempResponse;
    private PostBaseAdapter adapter;
    ListView list;
    Result result;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //initializeUI("java","bangalore","karnataka","date","25","jobsite","fulltime","0","15","14","1","1","india","null","122.172.176.113","chrome","2");
        initializeUI();
    }
    //responseView = (ListView) findViewById(R.id.responseView);
    private void initializeUI() {
        queryText = (EditText) findViewById(R.id.queryText);
        locationText = (EditText) findViewById(R.id.locationText);
        txText = (EditText) findViewById(R.id.txText);
        sortText = (EditText) findViewById(R.id.sortText);
        radiusText = (EditText) findViewById(R.id.radiusText);
        stText = (EditText) findViewById(R.id.stText);
        jtText = (EditText) findViewById(R.id.jtText);
        //startText = (EditText) findViewById(R.id.startText);
        limitRes = (EditText) findViewById(R.id.limitRes);
        fromAgeText = (EditText) findViewById(R.id.fromAgeText);
        //filterText = (EditText) findViewById(R.id.filterText);
        //latlongText = (EditText) findViewById(R.id.latlongText);
        countryText = (EditText) findViewById(R.id.countryText);
        //chnlText = (EditText) findViewById(R.id.chnlText);
        userIpText = (EditText) findViewById(R.id.userIpText);
        //browserText = (EditText) findViewById(R.id.browserText);
        //version = (EditText) findViewById(R.id.version);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        Button queryButton = (Button) findViewById(R.id.queryButton);
        //list = (ListView) findViewById(R.id.resultList);



        queryButton.setOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View v) {
                String query = queryText.getText().toString();
                String location = locationText.getText().toString();
                String tx = txText.getText().toString();
                String sort = sortText.getText().toString();
                String radius = radiusText.getText().toString();
                String st = stText.getText().toString();
                String jobtype = jtText.getText().toString();

                //String start = startText.getText().toString();
                String limit = limitRes.getText().toString();
                String fromAge = fromAgeText.getText().toString();
                //String filter = filterText.getText().toString();
                //String latlong = latlongText.getText().toString();
                String country = countryText.getText().toString();
                //String chnlTxt = chnlText.getText().toString();
                String userIp = userIpText.getText().toString();
                //String browser = browserText.getText().toString();
                //String versionTx = version.getText().toString();
                //ArrayList<String> arl= new ArrayList<String>();
                //arl.add(query);
                new RetrieveFeedTask().execute(query, location, tx, sort, radius, st, jobtype,"1",limit,fromAge,"1","1",country,"null",userIp, "chrome","2");
                //responseView.setText(url);
                Log.e("ERROR","In button call");
                Log.i("INFO","Inside Button call");
            }
        });

      list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

              @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // getting values from selected ListItem
                String name = ((TextView) view.findViewById(R.id.tvTitle)).getText().toString();
                // create intent to start another activity
                Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
                //Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(resultlist.get(position).getJobtitle()));
                // add the selected text item to our intent.
                intent.putExtra("title", name);
                startActivity(intent);
            }


        });
    }


    class RetrieveFeedTask extends AsyncTask<String, String, String> {
        private Exception exception;
        String tempResponse = "";


        protected void onPreExecute() {
            waitProgress = ProgressDialog.show(MainActivity.this, "", "Loading... please wait...");
           // progressBar.setVisibility(View.VISIBLE);
           // responseView.setAdapter(null);//.setText(" ");
            Log.e("ERROR","In onPreExecute call");
            Log.i("INFO","Inside onPreExecutecall");
        }


        protected String doInBackground(String... args) {

            // Do some validation here
            String query = args[0];
            String location = args[1];
            String tx = args[2];
            String sort = args[3];
            String radius = args[4];
            String st = args[5];
            String jobtype = args[6];
            String start = args[7];
            String limit = args[8];
            String fromAge = args[9];
            String filter = args[10];
            String latlong = args[11];
            String country = args[12];
            String chnlTxt = args[13];
            String userIp = args[14];
            String browser = args[15];
            String versionTx = args[16];
            finalUrl = API_URL + "publisher=" + API_KEY + "&q=" + query + "&l=" + location + "," + tx + "&sort=" + sort + "&radius=" + radius + "&st=" + st + "&jt=" + jobtype + "&start=" + start + "&limit=" + limit + "&fromage=" + fromAge + "&filter=" + filter + "&latlong=" + latlong + "&co=" + country + "&chnl=" + chnlTxt + "&userip=" + userIp + "&useragent=" + browser + "&v=" + versionTx;
            //finalUrl=  "http://api.xyz.com/ads/apisearch?publisher=2986470692413324&q=java&l=BANGALORE%2C+karnataka&sort=date&radius=25&st=jobsite&jt=fulltime&start=1&limit=10&fromage=14&filter=1&latlong=1&co=india&chnl=null&userip=122.166.158.225&useragent=Chrome&v=2";
            SAXParser();
            return "";
    }
    protected void onPostExecute(String response) {
          /*  if (response == null || response.trim().equals("")) {
                response = "THERE WAS AN ERROR";
            }*/

      /*  if (rList == null) {
            responseView.setAdapter(null);      //setText("Error");
            //return;
        }*/
       // progressBar.setVisibility(View.GONE);
        //Log.i("INFO", response);
        // getting values from selected ListItem
       // Bundle bundle= new Bundle();
        String name = ((TextView) findViewById(R.id.tvTitle)).getText().toString();
        Bundle bundle= new Bundle();
        // create intent to start another activity
        //bundle.putString("name",result.getJobtitle());
        Intent intent2 = new Intent(MainActivity.this, ResultListView.class);
        //Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(resultlist.get(position).getJobtitle()));
        // add the selected text item to our intent.
        //intent2.putExtra("title", name);
        bundle.putString("title",name);
        intent2.putExtra("pBundle",bundle);
        startActivity(intent2);
        //displayData();
        if (waitProgress != null) {
            waitProgress.dismiss();
        }

    }
      /*  protected void onPostExecute()
        {   progressBar.setVisibility(View.GONE);
            displayData();

            }*/


    private void SAXParser(){

        try {

            SAXParserFactory factory = SAXParserFactory.newInstance();
            // create a parser
            //XMLReader xmlreader = factory.getXMLReader();
            SAXParser parser = factory.newSAXParser();
            resultlist = new ArrayList<Result>();
            URL ul = new URL(finalUrl);
            URLConnection uc = ul.openConnection();
            ResultHandler resultHandler = new ResultHandler(resultlist);

            // assign our handler
            // xmlreader.setContentHandler(resultHandler);
            // perform the synchronous parse
            parser.parse(new InputSource(uc.getInputStream()), resultHandler);
            resultlist = resultHandler.getResultList();
            Log.e("ERROR","In SAXParser call");
            Log.i("INFO","Inside SAXParser");
        } catch (Exception e) {
            e.printStackTrace();

        }
        Log.e("ERROR","In doInBackground call");
        Log.i("INFO","Inside doInBackgr call");
        // SAXParser();

    }
    } 

activity_main.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillViewport="true"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

    <LinearLayout
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        tools:context="portfolio.first_app.practice.com.simplewebapi3.xyzJobActivity">

        <EditText
            android:id="@+id/queryText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter the Skill"/>
        <!--android:inputType="textEmailAddress"-->
        <EditText
            android:id="@+id/locationText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter the Location"/>
        <EditText
            android:id="@+id/txText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter the State"/>

        <EditText
            android:id="@+id/sortText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter the Date"/>
        <EditText
            android:id="@+id/radiusText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter the Radius"/>
        <EditText
            android:id="@+id/stText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter the Site Type"/>
        <EditText
            android:id="@+id/jtText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter the Job Type"/>
     <!--  <EditText
            android:id="@+id/startText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter the Start Index of the Result"/>-->
       <EditText
            android:id="@+id/limitRes"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter the Result Limit"/>
        <EditText
            android:id="@+id/fromAgeText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter the Age"/>
   <!--     <EditText
            android:id="@+id/filterText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter the Duplicate filter value"/>
       <EditText
            android:id="@+id/latlongText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter the value 1 or 0"/>-->
        <EditText
            android:id="@+id/countryText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter the Country"/>

   <!--    <EditText
            android:id="@+id/chnlText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter the Group channel"/>-->

        <EditText
            android:id="@+id/userIpText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter the User IP address"/>
   <!--     <EditText
            android:id="@+id/browserText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter the Browser"/>
        <EditText
            android:id="@+id/version"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter the Version:"/>-->


        <Button
            android:id="@+id/queryButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end"
            style="@style/Base.Widget.AppCompat.Button.Borderless"
            android:text="Search"/>
        <ProgressBar
            android:id="@+id/progressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:indeterminate="true"
            android:layout_centerHorizontal="true"
            android:visibility="gone" />







    </LinearLayout>
</ScrollView>

ResultListView.java

/** * 由 SouRAV 于 2016 年 6 月 15 日创建。 */

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by SouRAV on 6/15/2016.
 */
public class ResultListView extends Activity {
    TextView textView;
    ListView list;
    ArrayList<Result> resultlist;
    private PostBaseAdapter adapter;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result_list_view);
        list = (ListView) findViewById(R.id.resultList);
        textView = (TextView) findViewById(R.id.textView);
        // get the intent from which this activity is called.
         Intent intent2 = getIntent();
         Bundle bundle= intent2.getBundleExtra("pBundle");
         String text =  bundle.getString("title");
         textView.setText(text);
         displayData1();
        // fetch value from key-value pair and make it visible on TextView.
        //Bundle intent2 = getIntent().getExtras();
        //String   list_data = intent2.getString("list");
       // textView.setText(list_data);


    }
    private void displayData1() {
        adapter = new PostBaseAdapter(ResultListView.this, resultlist);
        adapter.notifyDataSetChanged();
        list.setAdapter(adapter);
        Log.e("ERROR","In displayData call");
        Log.i("Info","Inside displaydata");
        //Log.i("INFO", response);
        // responseView.setText(response);
        // ProgressBar.dismiss();
    }
}

result_list_view.xml

<LinearLayout android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android" >



<ListView android:id="@+id/resultList"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
</ListView>
</LinearLayout>

结果.java

包portfolio.first_app.practice.com.xyzjobactivity3;

/**
 * Created by SouRAV on 4/29/2016.
 */
import java.util.ArrayList;

import java.util.ArrayList;

public class Result {

    public String jobtitle;
    public String company;
    public String city;
    public String state;
    public String country;
    public String formattedLocation;
    public String source;
    public String date;
    public String snippet;
    public String url;
    public String onmousedown;
    public String lattitude;
    public String longitude;
    public String jobkey;
    public String sponsored;
    public String expired;
    public String formattedLocationFull;
    public String formattedRelativeTime;
    public String getJobtitle() {
        return jobtitle;
    }
    public void setJobtitle(String jobtitle) {
        this.jobtitle = jobtitle;
    }
    public String getCompany() {
        return company;
    }
    public void setCompany(String company) {
        this.company = company;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getState() {
        return state;
    }
    public void setState(String state) {
        this.state = state;
    }
    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }
    public String getFormattedLocation() {
        return formattedLocation;
    }
    public void setFormattedLocation(String formattedLocation) {
        this.formattedLocation = formattedLocation;
    }
    public String getSource() {
        return source;
    }
    public void setSource(String source) {
        this.source = source;
    }
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
    public String getSnippet() {
        return snippet;
    }
    public void setSnippet(String snippet) {
        this.snippet = snippet;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getOnmousedown() {
        return onmousedown;
    }
    public void setOnmousedown(String onmousedown) {
        this.onmousedown = onmousedown;
    }
    public String getLattitude() {
        return lattitude;
    }
    public void setLattitude(String lattitude) {
        this.lattitude = lattitude;
    }
    public String getLongitude() {
        return longitude;
    }
    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }
    public String getJobkey() {
        return jobkey;
    }
    public void setJobkey(String jobkey) {
        this.jobkey = jobkey;
    }
    public String getSponsored() {
        return sponsored;
    }
    public void setSponsored(String sponsored) {
        this.sponsored = sponsored;
    }
    public String getExpired() {
        return expired;
    }
    public void setExpired(String expired) {
        this.expired = expired;
    }
    public String getFormattedLocationFull() {
        return formattedLocationFull;
    }
    public void setFormattedLocationFull(String formattedLocationFull) {
        this.formattedLocationFull = formattedLocationFull;
    }
    public String getFormattedRelativeTime() {
        return formattedRelativeTime;
    }
    public void setFormattedRelativeTime(String formattedRelativeTime) {
        this.formattedRelativeTime = formattedRelativeTime;
    }
    public String getDetails() {
        String result = jobtitle + ": " + company + "\n" + city + "-" + state
                + "\n" + country + "\n" + formattedLocation +"\n" + source+"\n"+date+
                "\n"+snippet+"\n"+url+"\n"+onmousedown+"\n"+lattitude+"\n"+longitude+"\n"
                +jobkey+"\n"+sponsored+"\n"+expired+"\n"+formattedLocationFull+"\n"+formattedRelativeTime;
        return result;
    }
}

我没有显示解析 XML 数据,因为它工作正常。问题很简单,我正在使用 Intent ,但无法在 ListView 中显示它。我问的是 postExecute(); 内的代码

最佳答案

通过Parcelable接口(interface)实现Result。现在从服务器获取数据后,只需将 ArrayList 放入 Intent 中,然后在 ResultActivity 中检索它们即可。

在 list.setItemClickListener 中 -

                Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
                intent.putParcelableArrayListExtra("RESULT", resultlist);
                intent.putExtra("title", name);
                startActivity(intent);

再次在 Result Activity 的 onCreate 中不要忘记初始化结果列表 -

                resultlist = getIntent().getParcelableArrayExtra("RESULT");

希望对你有帮助:)

关于java - 通过 REST API 检索结果并将其显示在新 Activity 的 ListView 中( ListView 出现小问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37885178/

相关文章:

java - libGDX Box2D 在从地面掉落之前转身

java - 如何获取正在运行的C程序的stdin和stdout

android - 具有复杂数据和每行复杂布局的复杂 ListView 示例?

android - BaseAdapter Listview 过滤 Android

java - 不使用数组查找给定整数的第二大数目

java - 通过 "Reference Value"?需要一些说明

java - Android OpenCV 查找轮廓

android - DownloadManager.ACTION_DOWNLOAD_COMPLETE 广播接收器在 Android 中多次接收相同的下载 ID,但下载状态不同

android - 如何在后台加载布局?

android - 为什么 Android 中的项目高度不包裹内容?