So I've been trying to Save a website's code, (This website contains only html/php), into a String inside android.
Now, I've tried ASyncTask, and Couldn't get it to work. I've read the whole documentary..
I have to admit, I'm a starter in Android.
Still, for some reason, Everything I've tried either made it crash or didn't work.
Now, I'm asking you for a simple example, how to get a website's code, and set it as a String.
Thanks in advance!
Edit:
MainTabView.java
package com.example.projectnova;
import java.net.URL;
import com.example.projectnova.R.string;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.TabHost.TabSpec;
public class MainTabView extends Activity implements OnClickListener{
TabHost th;
TabSpec specs;
Button search;
EditText searchText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_tab_view);
search = (Button)findViewById(R.id.searchButton);
searchText = (EditText)findViewById(R.id.searchInputText);
th = (TabHost)findViewById(R.id.tabhost);
search.setOnClickListener(this);
th.setup();
specs = th.newTabSpec("tag1");
specs.setContent(R.id.Search);
specs.setIndicator("Search");
th.addTab(specs);
specs = th.newTabSpec("tag2");
specs.setContent(R.id.Download);
specs.setIndicator("Downloads");
th.addTab(specs);
/*
*
* Example in (I believe)PHP
*
function streaminfo($file,$port) {
global $src;
$fp = #fsockopen ($file, $port, &$errno, &$errstr, 5);
if (!$fp) {
echo "Could not connect to <b>{$file}:{$port}</b> ({$errno}) - {$errstr}\n";
} else {
fputs ($fp, "GET /7 HTTP/1.1\r\nUser-Agent:Mozilla\r\n\r\n");
while (!feof($fp)) {
$stream = fgets($fp,1024);
}
list(,$stream) = explode("<body>",$stream);
list($stream) = explode("</body>",$stream);
list($user, $status, $user_peak, $user_max,$filler ,$bitrate, $song) = explode(",",$stream);
if($status== 0 ) {
} else {
$arr = array('nameofsong' => $song);
echo json_encode($arr);
}
fclose($fp);
}
}
streaminfo("188.138.79.175",8030);
*/
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId()){
case R.id.searchButton:
int i = searchText.getText().toString().length();
if(i == 0){
Context context = getApplicationContext();
CharSequence text =("The search box is empty");
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else{
String s = searchText.getText().toString();
String htmlText = s.replace(" ","_"); // Works
String link = "WebsiteUrl.com/" + htmlText + ".html"; //Works
// searchText.setText(link); Test Purposes
}
}
}
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
}
Can I ask why you need to do that?
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
Related
I am trying to use android studio to access a streaming/internet API. My API call works in Eclipse without using AsyncTask so I'm trying to use AsyncTask in Android Studio to call the API but I'm not sure why it's not working. The way I use the buffered reader and input stream are the same as the way I used them in eclipse when the call works. I also have permission to use internet in my AndroidManifest.xml.
Note: I took out my API key for obvious reasons.
import android.content.Intent;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.os.AsyncTask;
import android.view.View;
import android.widget.EditText;
import android.view.View.OnClickListener;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG_DEBUG = MainActivity.class.getName();
public static final String TAG_ID = "id";
public static final String TAG_CURRENTTEMP = "currenttemp";
public static final String TAG_MAXTEMP = "maxtemp";
public static final String TAG_MINTEMP = "mintemp";
private EditText enteredzip;
private String zip;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enteredzip = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
public void onClick(View v) {
zip = enteredzip.getText().toString();
new RetrieveFeedTask().execute();
}
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
}
protected String doInBackground(Void... urls) {
String BASE_URL = "http://api.openweathermap.org/data/2.5/weather?zip=";
String API_CALL = "&APPID=key";
// Do some validation here
HttpURLConnection con = null;
InputStream is = null;
String bufferedOutput = "";
try {
con = (HttpURLConnection) (new URL(BASE_URL + zip + API_CALL)).openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
StringBuffer buffer = new StringBuffer();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while((line = br.readLine()) != null)
buffer.append(line + "\r\n");
is.close();
con.disconnect();
bufferedOutput = buffer.toString();
return bufferedOutput;
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
} finally {
try{
is.close();
}catch(Throwable T){}
try{
con.disconnect();
}catch(Throwable T){}
}
}
protected void onPostExecute(String response) {
if(response == null) {
//response = "THERE WAS AN ERROR";
//Toast.makeText(MainActivity.this, getResources().getString(R.string.error_et), Toast.LENGTH_LONG).show();
return;
}
//Log.i("INFO", response);
// TODO: check this.exception
// TODO: do something with the feed
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
String id = "";
String currenttemp = "";
String maxtemp = "";
String mintemp = "";
for (int i = 0; i < response.length(); i++) {
if (response.substring(i, i + 2).equals("id")) {
id = response.substring(i + 4, i + 7);
break;
}
}
for (int i = 0; i < response.length(); i++) {
if (response.substring(i, i + 4).equals("temp")) {
currenttemp = response.substring(i + 6, i + 9);
break;
}
}
for (int i = 0; i < response.length(); i++) {
if (response.substring(i, i + 8).equals("temp_min")) {
mintemp = response.substring(i + 10, i + 13);
break;
}
}
for (int i = 0; i < response.length(); i++) {
if (response.substring(i, i + 8).equals("temp_max")) {
maxtemp = response.substring(i + 10, i + 13);
break;
}
}
launchMain2Activity(id, currenttemp, maxtemp, mintemp);
}
}
private void launchMain2Activity(String id, String currenttemp, String maxtemp, String mintemp) {
Intent Main2Activity = new Intent(MainActivity.this, Main2Activity.class);
Main2Activity.putExtra(TAG_ID, id);
Main2Activity.putExtra(TAG_CURRENTTEMP, currenttemp);
Main2Activity.putExtra(TAG_MAXTEMP, maxtemp);
Main2Activity.putExtra(TAG_MINTEMP, mintemp);
startActivity(Main2Activity);
}
try to use this :
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")) ;
UTF-8 is a method for encoding Unicode characters using 8-bit sequences.
Like title says, my variable is not updated on AsyncTask onPostExecute()
Here is the code
public class Search extends AppCompatActivity {
ArrayList<paire> Sectors = new ArrayList<paire>();//paire is my proper class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Rechercher rech = new Rechercher();
rech.execute();
//PRINTING SIZE OF Sectors HERE TELLS ME EXACTLY THE SIZE OF 0
/*
*
*
BLA BLA BLA BLA
*
*
*/
}
public class Rechercher extends AsyncTask<String, Void, ArrayList<paire>>{
#Override
protected ArrayList<paire>doInBackground(String... strings) {
/*
*
Process of creating the arrayList myArray
*
*/
onPostExecute(myArray);//I put this desesperatly xD it doesn't change anything
return myArray;
}
protected void onPostExecute(ArrayList<paire>myArray) {
for (int u = 0; u < myArray.size(); u ++){
paire r = myArray.get(u);
Sectors.add(r);
}
//PRINTING SIZE OF Sectors HERE TELLS ME EXACTLY THE SIZE OF myArray
}
}
}
Well myArray is created from data gotten from dataBase (HTTP connection, JSON result ...) and the result is a very acceptable JSON output; there's no problem here, it's just that Sectors is not updated if I try to use it on Main.
I don't know if I really understand the onPostExecute; or there's a problem !
Thank you
onPostExcecute will call automatically just return your array in doBackground and pass ArrayList instead of void in AsyncTask<String, Void, ArrayList<paire>> and change return type of doInBackground to ArrayList<paire>
try this:
public class Rechercher extends AsyncTask<String, Void, ArrayList<paire>>{
#Override
protected ArrayList<paire> doInBackground(String... strings) {
/*
*
Process of creating the arrayList myArray
*
*/
//onPostExecute(myArray); // remove this line no need to add . this will call automatically.
return myArray;
}
protected void onPostExecute(ArrayList<paire> myArray) {
for (int u = 0; u < s.size(); u ++){
Sectors.set(u, s.get(u));
}
//PRINTING SIZE OF Sectors HERE TELLS ME EXACTLY THE SIZE OF myArray
}
}
hope this help.
Is this building without errors? I dont believe that you can call onPostExecute from doInBackground and I dont see anywhere in the code where there is a variable called "s" but s.size() is what is controlling the number of times the for loop iterates. So in the current code, Sectors.set would never be called.
you should read careful about asyncTask again.
Modify you asynTask as below
public class Rechercher extends AsyncTask<String, Void, ArrayList<paire>>{
#Override
protected Void doInBackground(String... strings) {
/*
*
Process of creating the arrayList myArray
*
*/
/* don't need to call this function, asynctask will call it automatically
onPostExecute(myArray);
*/
return myArray;
}
protected void onPostExecute(ArrayList<paire>myArray) {
if (Selector.size() > 0) {
Selector.clear();
}
for (int u = 0; u < s.size(); u ++){
Sectors.add(s.get(u));
}
//PRINTING SIZE OF Sectors HERE TELLS ME EXACTLY THE SIZE OF myArray
}
}
package caci.elmouchir;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.ArrayList;
import android.util.Log;
import android.widget.*;
import android.widget.Spinner;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Search extends AppCompatActivity {
private void setSectors(String[] lesSec){
Spinner sec = (Spinner) findViewById(R.id.spinnerSecteur);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lesSec);
sec.setAdapter(adapter);
sec.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
ArrayList<paire> Sectors = new ArrayList<paire>();
ArrayList<paire> Branchs = new ArrayList<paire>();
ArrayList<paire> SBranchs = new ArrayList<paire>();
ArrayList<paire> Activities = new ArrayList<paire>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
String Code = "X.XX.XX.XXX";
Rechercher rech = new Rechercher();
rech.execute();
Log.e("log_tag", Integer.toString(Sectors.size()));
//Log.e("log_tag", Integer.toString(Sectors.size()));
Button search = (Button)findViewById(R.id.buttonSearch);
search.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
EditText motcle = (EditText)findViewById(R.id.editMotCle);
if (motcle.getText().toString().isEmpty())
motcle.setError("Entrez un mot clé");
}
});
/*
*
*
*
*
C O N N E X I O N A L A B A S E D E D O N N E E S
*
*
*
*
*/
}
public class Rechercher extends AsyncTask<String, Void, ArrayList<paire>>{
#Override
protected ArrayList<paire> doInBackground(String... strings) {
String result = "";
ArrayList<paire> s = new ArrayList<paire>();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.145/test/getActivities.php");
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
//convert response to string
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
//Log.e("log_tag", result);
try{
JSONArray jArray = new JSONArray(result);
ArrayList<paire> b = new ArrayList<paire>();
ArrayList<paire> sous = new ArrayList<paire>();
ArrayList<paire> a = new ArrayList<paire>();
for(int i=0;i<jArray.length();i++){
JSONObject json_data = (JSONObject)jArray.getJSONObject(i);
if (json_data.getString("friendly_url").toString().length() == 2){
paire p = new paire(json_data.getString("title").toString(),json_data.getString("friendly_url").toString());
s.add(p);
}
else if(json_data.getString("friendly_url").toString().length() == 3){
b.add(new paire(json_data.getString("title").toString(),json_data.getString("friendly_url").toString()));
}
else if(json_data.getString("friendly_url").toString().length() == 4){
sous.add(new paire(json_data.getString("title").toString(),json_data.getString("friendly_url").toString()));
}
else{
a.add(new paire(json_data.getString("title").toString(),json_data.getString("friendly_url").toString()));
}}
//Log.e("log_tag", Integer.toString(s.size()));
// onPostExecute(s, b, sous, a);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
return s;
}
protected void onPostExecute(ArrayList<paire>s) {
/*Sectors = s;
Branchs = b;
SBranchs = sous;
Activities = a;*/
for (int u = 0; u < s.size(); u ++){
paire r = s.get(u);
Sectors.add(r);
}
Log.e("log_tag", "loool: "+Integer.toString(Sectors.size()));
}
}
public class paire{
String title;
String url;
paire(String p, String u){
this.title = p;
this.url = u;
}
String getTitle(){
return this.title;
}
String getUrl(){
return this.url;
}
}
}
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);
}
}
});
I do not understand why my app crashes in this code, and there is no error or stacktrace in logcat.
package org.concordacademy.hangman;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class PlayScreen extends Activity {
// The String Below will tell Console/LogCat the processes of The PlayScreen Activity
private final String PS = "Play Screen";
private char[] secretWord;
private char[] displayedWord;
// Below is an array of the Letters already guessed.
private ArrayList<Character> chosenLetters = new ArrayList<Character>();
Random random = new Random();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playscreen);
Log.i(PS, "Loading Play Screen.");
startGame();
}
// Read Text File entitled wordsEn.txt
public String readFromFile() {
String words = "";
// Array List That Words being added to
ArrayList<String> wordLineArray = new ArrayList<String>();
try {
InputStream inputstream = openFileInput("wordsEn.txt");
if (inputstream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputstream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
wordLineArray.add(receiveString);
stringBuilder.append(receiveString);
}
inputstream.close();
// Possible pointless code below
words = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
//R Generator for Strings in wordLineArray
//String secretWordString = wordLineArray.get(getRandomNumber(0, wordLineArray.size()));
String secretWordString = "HelloWorld";
secretWord = secretWordString.toCharArray();
for (int i = 0; i < secretWord.length; i++) {
displayedWord[i] = '-';
}
return words;
}
// Choose a random number that is assigned to a corresponding String in ArrayList
public int getRandomNumber(int min, int max) {
int number = min + (int)(Math.random() * ((max - min) + 1));
return number;
}
public void startGame() {
readFromFile();
String secretWordString = "HelloWorld";
secretWord = secretWordString.toCharArray();
displayedWord = new char[secretWord.length];
for (int i = 0; i < secretWord.length; i++) {
displayedWord[i] = '-';
}
}
public void findLetters(String guess) {
for (int i = 0; i < secretWord.length; i++) {
// Change Guess to CharArray and 0 Index.
if (!guess.isEmpty()) {
if (guess.toCharArray()[0] == secretWord[i]) {
Log.i(PS, "Correct Guess");
displayedWord[i] = guess.toCharArray()[0];
}
}
}
// Add Guess to the already chosen letter array
if (!guess.isEmpty()) {
chosenLetters.add(guess.toCharArray()[0]);
}
}
public boolean checkWin() {
if (displayedWord == secretWord) {
return true;
} else {
return false;
}
}
public void guessButtonClick(View v) {
TextView displayText = (TextView) findViewById(R.id.displayedWord);
displayText.setText(displayedWord.toString());
EditText inputGuess = (EditText) findViewById(R.id.textField);
String guess = inputGuess.getText().toString();
findLetters(guess);
}
}
Secondly, When I use the text view to display dashes, instead, it doesn't display anything and when i submit a letter it shows a memory location. I know I am not providing much information, but I am deeply confused. I am also reading a txt file and storing it into an array, and it vital I need it.
You have a problem with the displayedWord variable. It is being initialized after you use it in startGame()
readFromFile(); // here you use it
//...
displayedWord = new char[secretWord.length]; // here you initialize it
You need to initialize it first, and THEN used it!
I am trying to show progress dialog while the json is being parsed in background (using Async Task),but whenever i try that,I get Force Close,the json works properly whenever i use it wihout async task.
Here is my code for it :
package com.Parsing.SOAPParsing;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String SOAP_ACTION = "http://tempuri.org/testService";
private static final String METHOD_NAME = "testService";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://testService/webservice.asmx";
TextView tv, optionA, optionB, optionC, optionD, optionE;
ArrayList<HashMap<String, String>> testList = new ArrayList<HashMap<String, String>>();
private String result;
int j = 0;
int k;
String questions[] = new String[12];
String opA[] = new String[12];
String opB[] = new String[12];
String opC[] = new String[12];
String opD[] = new String[12];
String opE[] = new String[12];
ListView list;
Button next;
Button previous;
int i;
String v;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.questions);
Fetch fetch = new Fetch(); // Calling async task
fetch.execute();
}
public class Fetch extends AsyncTask<String, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(MainActivity.this);
#Override
public void onPreExecute() {
this.dialog
.setMessage("Loading database. Please wait..."
+ "\n\n\n\n This will will only load for once when you install the application");
this.dialog.show();
}
#Override
public Void doInBackground(String... params) {
for (k = 1; k <= 10; k++) {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("QuestionId", Long.valueOf(k));
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive) envelope
.getResponse();
result = response.toString();
try {
JSONObject o = new JSONObject(result);
Iterator<String> it = o.keys();
while (it.hasNext()) {
JSONArray ja = o.optJSONArray(it.next());
if (ja != null) {
for (i = 0; i <= ja.length(); i++) {
String v = ja.get(i).toString();
Log.i("value", i + " = " + v);
if (i == 0) {
opA[k - 1] = v;
}
if (i == 1) {
opB[k - 1] = v;
}
if (i == 2) {
opC[k - 1] = v;
}
if (i == 3) {
opD[k - 1] = v;
}
if (i == 4) {
opE[k - 1] = v;
}
if (i == 7) {
questions[k - 1] = v;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
tv.setText(e.getMessage());
}
}
return null;
}
public void onPostExecute(final Void unsed) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
Toast.makeText(MainActivity.this, opB[k], Toast.LENGTH_LONG)
.show();
}
}
}
}
Am stuck at this,sorry if the error is silly as i am really new to this.
Thanks for help in advance.
because your are accessing UI elements from doInBackground
#Override
public Void doInBackground(String... params) {
//YOUR CODE....
} catch (Exception e) {
tv.setText(e.getMessage()); //HERE YOU ARE ACCESSING TEXTVIEW FROM doInBackground
}
//YOUR CODE...
what you can do is :
Change the return type of Asynctask to String
Return the necessary string from doInBackground method
Update this string to your textview in onPostExecute method
i have updated your code as below.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.qualstream.telfaz.R;
public class MainActivity extends Activity {
private static final String SOAP_ACTION = "http://tempuri.org/LoadQuestionDetail";
private static final String METHOD_NAME = "LoadQuestionDetail";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://www.beyyondcareers.com/webservice.asmx";
TextView tv, optionA, optionB, optionC, optionD, optionE;
ArrayList<HashMap<String, String>> testList = new ArrayList<HashMap<String, String>>();
private String result;
int j = 0;
int k;
String questions[] = new String[12];
String opA[] = new String[12];
String opB[] = new String[12];
String opC[] = new String[12];
String opD[] = new String[12];
String opE[] = new String[12];
ListView list;
Button next;
Button previous;
int i;
String v;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
tv = (TextView) findViewById(R.id.textview123);
Fetch fetch = new Fetch(); // Calling async task
fetch.execute();
}
public class Fetch extends AsyncTask<Void, Void, String> {
private ProgressDialog dialog = new ProgressDialog(MainActivity.this);
#Override
public void onPreExecute() {
this.dialog
.setMessage("Loading database. Please wait..."
+ "\n\n\n\n This will will only load for once when you install the application");
this.dialog.show();
}
#Override
public String doInBackground(Void... params) {
for (k = 1; k <= 10; k++) {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("QuestionId", Long.valueOf(k));
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive) envelope
.getResponse();
result = response.toString();
try {
JSONObject o = new JSONObject(result);
Iterator<String> it = o.keys();
while (it.hasNext()) {
JSONArray ja = o.optJSONArray(it.next());
if (ja != null) {
for (i = 0; i <= ja.length(); i++) {
String v = ja.get(i).toString();
Log.i("value", i + " = " + v);
if (i == 0) {
opA[k - 1] = v;
}
if (i == 1) {
opB[k - 1] = v;
}
if (i == 2) {
opC[k - 1] = v;
}
if (i == 3) {
opD[k - 1] = v;
}
if (i == 4) {
opE[k - 1] = v;
}
if (i == 7) {
questions[k - 1] = v;
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
return e.getMessage();
}
}
return "";
}
#Override
public void onPostExecute(String result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
tv.setText(result);
Toast.makeText(MainActivity.this, opB[k], Toast.LENGTH_LONG)
.show();
}
}
}
}
You can't access UI elements from the doInBackground method, and the tv variable is a UI element.
tv.setText(e.getMessage());
Instead you can use the onProgressUpdate method to access UI elements. If you make a call to publishProgress in your doInBackground the onProgressUpdate method is automatically invoked.