Vidit Shah Vidit Shah - 2 months ago 18
Android Question

App Crashes while switching from one Activity to another

Aim: Building app on Google API to fetch the data about the books the user searches

Problem Explanation:

Whenever I hit the submit Button, my app crashes.

This is my first approach in making a network request app and I need guidance.

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);

}
});
}
}


Second Class

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 Class:

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;

}

}


Showing error in statement:

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


Need guidance

Answer

Showing error in statement : String text = i.getStringExtra ("text"); Request for Guidance

Well you need to get the data passed inside onCreate like below.

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;

}

And although you have the asyncTask class i can't see where exactly you execute the class. You need to do that inside onCreate as well.