通过 REST API 检索结果并将其显示在新活动的列表视图中(列表视图出现小问题)

Posted

技术标签:

【中文标题】通过 REST API 检索结果并将其显示在新活动的列表视图中(列表视图出现小问题)【英文标题】:Retrieve result through REST API and show it in a LIST VIEW in a new activity (Minor issue arises with LIST VIEW) 【发布时间】:2016-10-19 12:06:56 【问题描述】:

我正在通过 REST api 从 JOB 站点检索数据。我能够检索数据,甚至可以在“搜索”按钮后的同一页面中显示该数据。但是,我想在新活动中显示列表视图。我正在使用 Intent 来执行此操作。但是,不幸的是,我无法证明这一点。一旦我点击它,我的应用程序就会崩溃并且什么也不输出。

主要活动.java 公共类 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_
    android:layout_>

    <LinearLayout
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_
        android:layout_
        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_
            android:layout_
            android:hint="Enter the Skill"/>
        <!--android:inputType="textEmailAddress"-->
        <EditText
            android:id="@+id/locationText"
            android:layout_
            android:layout_
            android:hint="Enter the Location"/>
        <EditText
            android:id="@+id/txText"
            android:layout_
            android:layout_
            android:hint="Enter the State"/>

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

   <!--    <EditText
            android:id="@+id/chnlText"
            android:layout_
            android:layout_
            android:hint="Enter the Group channel"/>-->

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


        <Button
            android:id="@+id/queryButton"
            android:layout_
            android:layout_
            android:layout_gravity="end"
            style="@style/Base.Widget.AppCompat.Button.Borderless"
            android:text="Search"/>
        <ProgressBar
            android:id="@+id/progressBar"
            android:layout_
            android:layout_
            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_
    android:layout_
    xmlns:android="http://schemas.android.com/apk/res/android" >



<ListView android:id="@+id/resultList"
    android:layout_
    android:layout_
    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 数据,因为它工作正常。问题很简单,我正在使用意图,但无法在列表视图中显示它。我在询问 postExecute(); 中的代码;

【问题讨论】:

【参考方案1】:

通过 Parcelable 接口实现 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 活动的 onCreate 中不要忘记初始化结果列表 -

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

希望对你有帮助:)

【讨论】:

其实我问的是onPostExecute();里面LIST VIEW相关的代码并且,list.setOnItemClickListener() 中的代码工作正常.. 谢谢

以上是关于通过 REST API 检索结果并将其显示在新活动的列表视图中(列表视图出现小问题)的主要内容,如果未能解决你的问题,请参考以下文章

将数据从列表视图(从 Rest Api 生成)传递到另一个活动并将其保存到 SQLite 数据库中

从列表视图中检索数据并将其显示在文本视图/图像视图中

单击 Listview 中的项目时,如何在新活动中从 Firebase 检索数据?

通过 PayPal REST API 示例打折?

通过 Camera API 2 捕获图片并将其保存为位图

通过 Gmail REST API 发送的电子邮件/草稿无法在新的 Gmail 用户界面中打开