应用程序从一个Activity切换到另一个Activity时崩溃

时间:2016-09-13 16:54:16

标签: android

目标:在Google API上构建应用以获取有关用户搜索的图书的数据

问题说明:

每当我点击提交按钮时,我的应用程序崩溃 这是我制作网络请求应用程序的第一种方法,我需要指导。

MainActivityClass

package com.example.vidit.books;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

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

    final EditText query = (EditText) findViewById(R.id.query);
    Button submit= (Button) findViewById(R.id.submit);

            submit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Intent intent= new Intent(MainActivity.this,Request.class);
                    intent.putExtra ( "text", query.getText().toString() );
                    startActivity(intent);

                }
            });
}
}

第二课

package com.example.vidit.books;

import android.content.Intent;

public class Request {


Intent i = getIntent();
String text = i.getStringExtra ("text"); 

public static final String LOG_TAG = Request.class.getSimpleName();


String APIURL="https://www.googleapis.com/books/v1/volumes?q= " + text;


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



}

public void UpdateUi(Book book)
{

    BookAdapter bookAdapter = new BookAdapter(this,book);

    ListView listView= (ListView) findViewById(R.id.listview_all);

}


private class  BookAsyncTask extends AsyncTask<URL,Void,Book>
{

    @Override
    protected Book doInBackground(URL... urls) {
        URL url = createUrl(APIURL);
        String jsonResponse = "";
        try {
            jsonResponse = makeHttpRequest(url);
        } catch (IOException e) {
            // TODO Handle the IOException
        }
        final Book book = extractFeatureFromJson(jsonResponse);

        return book;

    }

    /**
     * Make an HTTP request to the given URL and return a String as the response.
     */
    private String makeHttpRequest(URL url) throws IOException {
        String jsonResponse = "";
        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setReadTimeout(10000 /* milliseconds */);
            urlConnection.setConnectTimeout(15000 /* milliseconds */);
            urlConnection.connect();
            if(urlConnection.getResponseCode()==200) {
                inputStream = urlConnection.getInputStream();
                jsonResponse = readFromStream(inputStream);
            }
        } catch (IOException e) {
            // TODO: Handle the exception
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (inputStream != null) {
                // function must handle java.io.IOException here
                inputStream.close();
            }
        }
        return jsonResponse;
    }

    /**
     * Convert the {@link InputStream} into a String which contains the
     * whole JSON response from the server.
     */
    private String readFromStream(InputStream inputStream) throws IOException {
        StringBuilder output = new StringBuilder();
        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = reader.readLine();
            while (line != null) {
                output.append(line);
                line = reader.readLine();
            }
        }
        return output.toString();
    }


    /**
     * Returns new URL object from the given string URL.
     */
    private URL createUrl(String stringUrl) {
        URL url = null;
        try {
            url = new URL(stringUrl);
        } catch (MalformedURLException exception) {
            Log.e(LOG_TAG, "Error with creating URL", exception);
            return null;
        }
        return url;
    }

    private Book extractFeatureFromJson(String bookJSON) {
        try {
            JSONObject baseJsonResponse = new JSONObject(bookJSON);
            JSONArray items = baseJsonResponse.getJSONArray("items");

            // If there are results in the features array
            for(int i=0;i<10;i++)
            {
                JSONObject firstFeature = items.getJSONObject(i);
                JSONArray author=firstFeature.getJSONArray("author");

                for(int j=0;j<author.length();j++)
                {
                    JSONObject authorFeature=author.getJSONObject(j);
                }

                String title = items.getString(Integer.parseInt("title"));
                // Create a new {@link Event} object
                return new Book(title,author);

            }
        } catch (JSONException e) {
            Log.e(LOG_TAG, "Problem parsing the earthquake JSON results", e);
        }
        return null;
    }
}

}

BookAdapter类:

package com.example.vidit.books;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;

public class BookAdapter extends ArrayAdapter<Book> {

public BookAdapter(Activity context, Book book)
{
    super(context,0, (List<Book>) book);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View listItemView = convertView;
    if(listItemView == null) {
        listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.list_item, parent, false);
    }
    Book cbook=getItem(position);

    TextView title = (TextView) listItemView.findViewById(R.id.title);
    title.setText(cbook.getmTitle());

    TextView author=(TextView) listItemView.findViewById(R.id.author);
    author.setText((CharSequence) cbook.getmAuthor());


    return listItemView;

}

}

在声明中显示错误:

 String text = i.getStringExtra ("text");

需要指导

3 个答案:

答案 0 :(得分:1)

当您在Request类中覆盖onCreate()并且Request类没有扩展Activity或AppCompatActivity时,我不知道您的代码是如何编译的。 其次,这一行:

Intent i = getIntent();
String text = i.getStringExtra ("text");

应该在onCreate()方法内。

答案 1 :(得分:0)

  

在语句中显示错误:String text = i.getStringExtra(“text”);   请求指导

你需要在onCreate中传递数据,如下所示。

String APIURL;

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

    Bundle bundle = getIntent().getExtras();
    String text = bundle.getString("text"); 

    APIURL="https://www.googleapis.com/books/v1/volumes?q= " + text;

}

虽然你有asyncTask类,但我无法确定你在哪里执行该类。你也需要在onCreate里面这样做。

答案 2 :(得分:0)

尝试将此代码移至onCreate方法

Intent i = getIntent();
String text = i.getStringExtra ("text"); 

您的Request类的构造函数中没有intent extras。