I have a scenario in which I have a form with four fields. In which one field will take same input only 5 times. On entering in 6th times activity will not go to another activity on button click. Please somebody help me as I have spent so many hours.
Here is my code
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
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.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class LoginFragment extends Fragment {
private EditText phone, emailId, doctorName, doctorUniqueNumber;
private Button submitButton;
private String code;
public LoginFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
phone = (EditText) rootView.findViewById(R.id.phoneNumber);
emailId = (EditText) rootView.findViewById(R.id.emailId);
doctorName = (EditText) rootView.findViewById(R.id.doctorName);
doctorUniqueNumber = (EditText) rootView.findViewById(R.id.doctorUniqueNumber);
submitButton = (Button) rootView.findViewById(R.id.button);
submitButton.setOnClickListener(click);
return rootView;
}
View.OnClickListener click = new View.OnClickListener() {
#Override
public void onClick(View v) {
if ((!phone.getText().toString().isEmpty()) && (!doctorName.getText().toString().isEmpty())
&& (!emailId.getText().toString().isEmpty()) && (!doctorUniqueNumber.getText().toString().isEmpty())){
AuthenticateDoctor doctor = new AuthenticateDoctor();
doctor.execute();
}
}
};
private void setPrefs(String key, int value){
SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(key, value);
editor.apply();
}
private int getPrefs(String key, int defaultValue){
SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
return preferences.getInt(key, defaultValue);
}
private void setStringPrefs(String key, String value){
SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value);
editor.apply();
}
private String getStringPrefs(String key, String defaultValue){
SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
return preferences.getString(key, defaultValue);
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
private class AuthenticateDoctor extends AsyncTask<Void, Void, String>{
private final String LOG_TAG = AuthenticateDoctor.class.getSimpleName();
#Override
protected String doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String data;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
URL url = new URL("http://spirantcommunication.com/andriod/grl/show.php?" + "code=" +
doctorUniqueNumber.getText().toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
data = buffer.toString();
Log.v("Data", data);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject object = new JSONObject(result);
JSONArray array = object.getJSONArray("Message");
code = array.getString(0);
Log.v("Code", code);
}catch (JSONException e){
e.printStackTrace();
}
if (code.equals("success")){
int numberOfTimes = getPrefs("Number of Times", 0);
if (numberOfTimes > 5){
Toast.makeText(getActivity(), "Exceed value", Toast.LENGTH_SHORT).show();
setStringPrefs("Doctor Unique Number", " ");
}else {
numberOfTimes++;
setPrefs("Number of Times", numberOfTimes);
setStringPrefs("Doctor Unique Number", doctorUniqueNumber.getText().toString());
Intent intent = new Intent(getActivity(), DoctorDashboardActivity.class);
startActivity(intent);
}
}else if (code.equals("Faliure")){
Toast.makeText(getActivity(), "This unique number is not present", Toast.LENGTH_SHORT).show();
}
}
}
}
First, you will have an int member in LoginFragment which will store the attempts. Then, in onClick you will check: if(attempts > 5) return; attempts++;
View.OnClickListener click = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(attempts > 5) return;
attempts++;
if ((!phone.getText().toString().isEmpty()) && (!doctorName.getText().toString().isEmpty())
&& (!emailId.getText().toString().isEmpty()) && (!doctorUniqueNumber.getText().toString().isEmpty())){
attempts = 0;
AuthenticateDoctor doctor = new AuthenticateDoctor();
doctor.execute();
}
}
};
Hope it helps
Related
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
I don't know how your code gets compiled when you have overridden onCreate() in Request class and the Request class isn't extending Activity or AppCompatActivity.
Secondly, this line :
Intent i = getIntent();
String text = i.getStringExtra ("text");
should be inside the onCreate() method.
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.
Try moving this code to your onCreate method
Intent i = getIntent();
String text = i.getStringExtra ("text");
The intent extras is not available in the constructor for your Request class.
My data is not inserting to database of webhost.
Here is my ActionActivity.java from where I will send data to the database.
import android.app.Activity;
import android.content.Context;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.InputStream;
public class ActionActivity extends Activity {
private String t;
TextView timer;
EditText e1,e2;
Button save;
static InputStream is = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_action);
Bundle time = getIntent().getExtras();
t = (String) time.get("com.example.masba.timemanagement.MESSAGE");
e1 = (EditText) findViewById(R.id.editText);
e1.setText(t, TextView.BufferType.EDITABLE);
e2 = (EditText) findViewById(R.id.editText2);
save = (Button) findViewById(R.id.save);
}
public void insert(View view){
String actionName = e1.getText().toString();
String time = e2.getText().toString();
Toast.makeText(this, "Data Inserting...", Toast.LENGTH_SHORT).show();
new SignupActivity(this).execute(actionName, time);
e1.setText("");
e2.setText("");
}
#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);
}
}
Now my SignupActivity.java Which extends Asynctask.
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String actionName = arg0[0];
String time = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?actioname=" + URLEncoder.encode(actionName, "UTF-8");
data += "&time=" + URLEncoder.encode(time, "UTF-8");
link = "http://masumalmasba.comli.com/insertdata.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Data inserted successfully.", Toast.LENGTH_SHORT).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Data could not be inserted.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
Now my insertdata.php code is:
<?php
$servername="mysql6.000webhost.com";
$username = "a1871724_masum";
$password = "almasba012";
$dbname = "a1871724_actiont";
$conn = new mysqli($servername , $username , $password , $dbname);
if($conn->connect_error)
{
die("Connection Failed: ".$conn->connect_error);
}
$action = $_GET['actionname'];
$time = $_GET['time'];
$sql = "INSERT INTO actiontime (name,time) VALUES ('($action)','($time)')";
if($conn->query($sql)===TRUE){
echo "New record created succesfully";
}
else{
echo "Error";
mysql_close($conn);
}
?>
I have been trying too hard to get around this problom, when I tap the refresh button in my app, the images doesn't load on the screen.
This the DataFragment file, when i build this app there are no errors.
package com.example.popularmovis;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.jar.JarException;
/**
* A placeholder fragment containing a simple view.
*/
public class DataFragment extends Fragment {
public ImageAdapter display;
public DataFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.datafragment_menu, menu);
}
#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_refresh) {
FetchMovieData movieData = new FetchMovieData();
movieData.execute();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
display = new ImageAdapter(rootView.getContext());
GridView gridView = (GridView) rootView.findViewById(R.id.gridView_movies);
gridView.setAdapter(display); // uses the view to get the context instead of getActivity().
return rootView;
}
public class FetchMovieData extends AsyncTask<Void, Void, String[]>{
private final String LOG_TAG = FetchMovieData.class.getSimpleName();
private String[] extractdisplayFromJason(String jasnData)
throws JSONException{
//These jason display need to be extracted
final String movie_results = "results";
final String movie_poster = "poster_path";
JSONObject movieData = new JSONObject(jasnData);
JSONArray movieArray = movieData.getJSONArray(movie_results);
String[] posterAddreess = new String[movieArray.length()];
//Fill ther posterAddreess with the URL to display
for(int j=0; j < movieArray.length(); j++){
String posterPath;
JSONObject movieArrayItem = movieArray.getJSONObject(j);
posterPath = movieArrayItem.getString(movie_poster);
posterAddreess[j] = "http://image.tmdb.org/t/p/w185/" + posterPath;
}
for (String s : posterAddreess) {
Log.v(LOG_TAG, "Thumbnail Links: " + s);
}
return posterAddreess;
}
#Override
protected String[] doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String JsonData = null;
String country = "US";
String rating = "R";
String sort = "popularity.desc";
String apiKey = "";
//building the URL for the movie DB
try {
//building the URL for the movie DB
final String MovieDatabaseUrl = "https://api.themoviedb.org/3/discover/movie?";
final String Country_for_release = "certification_country";
final String Rating = "certification";
final String Sorting_Order = "sort_by";
final String Api_Id = "api_key";
Uri buildUri = Uri.parse(MovieDatabaseUrl).buildUpon()
.appendQueryParameter(Country_for_release, country)
.appendQueryParameter(Rating, rating)
.appendQueryParameter(Sorting_Order, sort)
.appendQueryParameter(Api_Id, apiKey)
.build();
//Converting URI to URL
URL url = new URL(buildUri.toString());
Log.v(LOG_TAG, "Built URI = "+ buildUri.toString());
//Create the request to the Movie Database
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
//Read the input from the database into string
InputStream inputStream = urlConnection.getInputStream();
//StringBuffer for string Manipulation
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
JsonData = buffer.toString();
Log.v(LOG_TAG,"Forecaast Jason String" + JsonData );
} catch (IOException e) {
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
try {
return extractdisplayFromJason(JsonData);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String[] posterAddreess) {
for (String poster : posterAddreess) {
display.addItem(poster);
}
}
}
}
This the ImageAdapter code
package com.example.popularmovis;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.example.popularmovis.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ArrayList<String> images = new ArrayList<String>();
public ImageAdapter(Context c){
mContext = c;
}
#Override
public int getCount(){
return images.size();
}
#Override
public Object getItem(int position){
return images.get(position);
}
public long getItemId(int position){
return 0;
}
public View getView(int position, View convertView, ViewGroup parent){
ImageView imageview;
if (convertView == null){
imageview = new ImageView(mContext);
imageview.setPadding(0, 0, 0, 0);
//imageview.setLayoutParams(new GridLayout.MarginLayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
imageview.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageview.setAdjustViewBounds(true);
} else {
imageview = (ImageView) convertView;
}
Picasso.with(mContext).load(images.get(position)).placeholder(R.mipmap.ic_launcher).into(imageview);
return imageview;
}
/*
Custom methods
*/
public void addItem(String url){
images.add(url);
}
public void clearItems() {
images.clear();
}
}
When you use this in your onCreate method like this, it means that the object is local to the method and can't be use in other methods.
ImageAdapter display = new ImageAdapter(rootView.getContext());
First create a global class member variable
private ImageAdapter display;
then inside your onCreate method do this
display = new ImageAdapter(rootView.getContext());
I have a form having one edittext and an autocompleteview. And a button to search things based on this form. In this form I can either give value in edittext and autocompleteview may be empty and vice versa. On this basis I have passed value of these view to another activity where I made a webservice call and then fetch result.
This is activity where these view are presents:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patient_section);
getSupportActionBar().hide();
searchByNameEditText = (EditText) findViewById(R.id.searchByNameEditText);
searchByAddressEditText = (EditText) findViewById(R.id.searchByAddressEditText);
searchButton = (Button) findViewById(R.id.searchButton);
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.selectStateSpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_dropdown_item_1line,
getResources().getStringArray(R.array.state_arrays));
autoCompleteTextView.setAdapter(adapter);
patientUtilityButton = (Button) findViewById(R.id.patientUtilityButton);
patientUtilityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(PatientSectionActivity.this, patientUtilityButton);
popupMenu.getMenuInflater().inflate(R.menu.patient_utility_button_popmenu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
String patientUtilityMenuItem = item.toString();
patientUtilityButton.setText(patientUtilityMenuItem);
return true;
}
});
popupMenu.show();
}
});
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedStateValue = (String) parent.getItemAtPosition(position);
}
});
doctorName = searchByNameEditText.getText().toString();
// Search Button
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!selectedStateValue.equals(" ") || doctorName.equals(" ")){
Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
intent.putExtra("State Name", selectedStateValue);
startActivity(intent);
} else if (!doctorName.equals(" ") || selectedStateValue.equals(" ")){
Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
intent.putExtra("Name", doctorName);
startActivity(intent);
}
}
});
}
And in other activity, I get these extras from intent and make webservice call in AsyncTask but my app is crashing. Please any one help me as I am new in android.
This is my other activity
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class DoctorNameActivity extends ActionBarActivity {
ArrayAdapter<String> doctorAdapter;
ListView listView;
ProgressBar progressBar;
String doctorName;
String selectedStateValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_name);
progressBar = (ProgressBar) findViewById(R.id.progress);
listView = (ListView) findViewById(R.id.listView);
Intent intent = getIntent();
selectedStateValue = intent.getStringExtra("State Name");
doctorName = intent.getStringExtra("Name");
if (!selectedStateValue.equals(" ") || doctorName.equals(" ")){
FetchDoctorName fetchDoctorName = new FetchDoctorName();
fetchDoctorName.execute(selectedStateValue);
}else if (!doctorName.equals(" ") || selectedStateValue.equals(" ")){
FetchDoctorName fetchDoctorName = new FetchDoctorName();
fetchDoctorName.execute(doctorName);
}
}
private class FetchDoctorName extends AsyncTask<String, Void, String[]>{
private final String LOG_TAG = FetchDoctorName.class.getSimpleName();
public String[] parseDoctorName(String jsonString) throws JSONException{
final String DOCTOR_NAME_ARRAY = "name";
JSONObject object = new JSONObject(jsonString);
JSONArray array = object.getJSONArray(DOCTOR_NAME_ARRAY);
String[] doctorNamesResult = new String[array.length()];
for (int i = 0 ; i < array.length(); i++){
String doctorName = array.getString(i);
Log.v(LOG_TAG, doctorName);
doctorNamesResult[i] = doctorName;
}
return doctorNamesResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(ProgressBar.VISIBLE);
}
#Override
protected String[] doInBackground(String... params) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String doctorJsonString = null;
try {
final String BASE_URL = "http://mycityortho.com/display_result.php";
final String NAME_PARAM = "name";
final String STATE_PARAM = "state";
URL url = null;
if (params[0].equals(doctorName)){
Uri uri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(NAME_PARAM, params[0])
.build();
url = new URL(uri.toString());
Log.v(LOG_TAG, url.toString());
}else if (params[0].equals(selectedStateValue)){
Uri uri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(STATE_PARAM, params[0])
.build();
url = new URL(uri.toString());
Log.v(LOG_TAG, url.toString());
}
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
doctorJsonString = buffer.toString();
Log.v(LOG_TAG, doctorJsonString);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return parseDoctorName(doctorJsonString);
}catch (JSONException e){
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
progressBar.setVisibility(ProgressBar.GONE);
if (result != null){
doctorAdapter = new ArrayAdapter<>(DoctorNameActivity.this, android.R.layout.simple_list_item_1, result);
listView.setAdapter(doctorAdapter);
}
}
}
As per your code you are sending only one value in intent that is "State Name" or "Name" but in other activity you are trying to receive both value, that why you get null pointer exception.
So use the following code to solve this error.
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!selectedStateValue.equals(" ") || doctorName.equals(" ")){
Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
intent.putExtra("State Name", selectedStateValue);
intent.putExtra("Name", " ");
startActivity(intent);
} else if (!doctorName.equals(" ") || selectedStateValue.equals(" ")){
Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
intent.putExtra("State Name", " ");
intent.putExtra("Name", doctorName);
startActivity(intent);
}
}
});
package com.example.m2mai;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class RetrieveActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrieve);
}
public void getStream(View v)
{
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<String, Void, String>
{
ArrayList<String> mNameList = new ArrayList<String>();
public ArrayList<String> atList=new ArrayList<String>();
public ArrayList<String> dataList=new ArrayList<String>();
protected String doInBackground(String... params)
{
return getData();
}
public long getDateTo()
{
EditText toText = (EditText)findViewById(R.id.dateTo);
String To = toText.getText().toString();
DateFormat dateFormatTo = new SimpleDateFormat("dd/MM/yyyy");
Date dateTo = null;
try {
dateTo = dateFormatTo.parse(To);
} catch (java.text.ParseException e) {
.runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
long timeTo = dateTo.getTime();
new Timestamp(timeTo);
return timeTo/1000;
}
protected String getData()
{
String toTS = ""+getDateTo();
String decodedString="";
String returnMsg="";
String request = "http://api.carriots.com/devices/defaultDevice#eric3231559.eric3231559/streams/?order=-1&max=10&at_to="+toTS;
URL url;
HttpURLConnection connection = null;
try {
url = new URL(request);
connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("carriots.apikey", "1234567");
connection.addRequestProperty("Content-Type", "application/json");
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((decodedString = in.readLine()) != null)
{
returnMsg+=decodedString;
}
in.close();
connection.disconnect();
JSONObject nodeRoot = new JSONObject(returnMsg);
JSONArray res = nodeRoot.getJSONArray("result");
for (int i = 0; i < res.length(); i++)
{
JSONObject childJSON = res.getJSONObject(i);
if (childJSON.get("data")!=null)
{
String value = childJSON.getString("data");
dataList.add(value);
JSONObject node=new JSONObject(value);
atList.add(node.get("temperature").toString());
}
}
}
catch (Exception e)
{
e.printStackTrace();
returnMsg=""+e;
}
return returnMsg;
}
protected void onPostExecute(String result)
{
for(int i = 0; i < atList.size(); i++)
{
ListView mainListView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> mArrayAdapter = new ArrayAdapter<String>(RetrieveActivity.this,android.R.layout.simple_list_item_1,mNameList);
mainListView.setAdapter(mArrayAdapter);
mNameList.add(atList.get(i).toString());
mArrayAdapter.notifyDataSetChanged();
}
Toast.makeText(getApplicationContext(),result, Toast.LENGTH_SHORT).show();
EditText myData1=(EditText)findViewById(R.id.editText1);
myData1.setText(atList.get(0));
}
}
}
How can I actually display a toast without stoping it? Whenever it falls into the catch it is not responding.
............................................................................................................................................................................................................................................................................
If you are using try-catch in a worker thread and want to display Toast, then I am afraid it is not going to work. You will have to do it in Main(UI) thread.
Try following:
try {
dateTo = dateFormatTo.parse(To);
}
catch (java.text.ParseException e) {
your_activity_context.runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
}
Try following:
In getDateTo():
try {
dateTo = dateFormatTo.parse(To);
} catch (java.text.ParseException e) {
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(),"Please key in the correct input", Toast.LENGTH_LONG).show();
}
});
e.printStackTrace();
return -1L; // attention here
}
In getData():
long dateTo = -1L;
if((dateTo = getDateTo()) == -1L){
return null;
}
String toTS = "" + getDateTo();
In onPostExecute:
if(result == null) {
return;
}
Make boolean flag = false; globally.
Inside catch block make flag = true;
Run Toast inside an if block like
if (flag) {
Toast.makeText(this, "Sorry, Couldn't find anything!", Toast.LENGTH_LONG).show();
}
inside your onclick method.