HttpURLConnection method empty when called - android

I'm calling a
(getData()
that should run HttpURLConnection and return a string (later to be casted as Long), the string should be the one line from this URL:
https://blockchain.info/tobtc?currency=USD&value=1
Trying to see if it is returning anything , I'm displaying the returned string in the layout.xml file and showing a toast. But both both show as blank
Please do not pay attention to the fact that I'm doing this on the main thread, I'm just trying to make it work first.
What I'm I doing wrong? why it's not returning the string value.
thanks
package app.com.cryptosudan.android.cryptosudan;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton sdg = (ImageButton) findViewById(R.id.imagesdg);
ImageButton btc = (ImageButton) findViewById(R.id.imagebtc);
final TextView display = (TextView) findViewById(R.id.display);
String price;
price = (getData());
display.setText(price);
Toast.makeText(this, price, Toast.LENGTH_LONG).show();
sdg.setOnClickListener(sdgpage);
btc.setOnClickListener(btcpage);
}
//to create an instance of button OnClickListener
View.OnClickListener sdgpage = new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, CalculateSdg.class));
}
};
//to create an instance of button OnClickListener
View.OnClickListener btcpage = new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, CalculateBtc.class));
}
};
public static String getData () {
BufferedReader reader = null;
try {
URL url = new URL("https://blockchain.info/tobtc?currency=USD&value=1");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while((line = reader.readLine()) !=null) {
sb.append (line + "/n");
} return sb.toString();
}catch (Exception e){
e.printStackTrace();
return null;
}finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
#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);
}
}

For http request on main thread change you onCreate method with StrictMode.ThreadPolicy.Builder().permitAll()
I Don't recommend Http request in main thread !!!!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton sdg = (ImageButton) findViewById(R.id.imagesdg);
ImageButton btc = (ImageButton) findViewById(R.id.imagebtc);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
final TextView display = (TextView) findViewById(R.id.display);
String price;
price = (getData());
display.setText(price);
Toast.makeText(this, price, Toast.LENGTH_LONG).show();
sdg.setOnClickListener(sdgpage);
btc.setOnClickListener(btcpage);
}

Related

Json don't update result in the seconde time

I have an activity where I can do a search through URL json file, so the 3 parameters pass from EditText of MainActivity to the second activity (annonces), the URL Json recovers the three values ​​and the results is normally displayed , but the problem if I made a return to MainActivity and I change the value of EditTexts and I click search, the results do not change.
this is my project :
MainActivity.java
package com.example.dzweber.waslup;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
AutoCompleteTextView cat;
String[] categories={"informatique","infographie","mathématique","Génie civil","Biologie"};
#Override
protected void onCreate(Bundle savedInstanceState) {
if(annonces.instance != null) {
annonces.instance.finish();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
cat=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView2);
ArrayAdapter adapter = new
ArrayAdapter(this,android.R.layout.simple_list_item_1,categories);
cat.setAdapter(adapter);
cat.setThreshold(1);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.home) {
}
else if (id == R.id.login) {
Intent i = new Intent(this,login.class);
startActivity(i);
}
else if (id == R.id.avanced_search) {
Intent i = new Intent(this,avanced_search.class);
startActivity(i);
}
else if (id == R.id.annonces) {
Intent i = new Intent(this,avanced_search.class);
startActivity(i);
}else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void as(View view) {
EditText loc;
EditText key;
loc = (EditText)findViewById(R.id.a_loc);
key = (EditText)findViewById(R.id.a_keys);
Intent intent = new Intent(getBaseContext(), annonces.class);
intent.putExtra("ca", cat.getText().toString());
intent.putExtra("lo",loc.getText().toString());
intent.putExtra("ke", key.getText().toString());
startActivity(intent);
}
public void connect(View view) {
}
}
annonces.java
package com.example.dzweber.waslup;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.AsyncTask;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.androidquery.AQuery;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import org.json.JSONObject;
public class annonces extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public static ArrayList<annonce_item> Items = new ArrayList<annonce_item>();
public static TextView txtv;
public static String data = "";
String skey = "";
String sloc = "";
String scat = "";
String date="";
String loc="";
String cat="";
String vue="";
String titre="";
String id="";
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
public static annonces instance = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fetchD p = new fetchD();
//p.execute();
instance = this;
skey= getIntent().getStringExtra("ke");
sloc= getIntent().getStringExtra("lo");
scat= getIntent().getStringExtra("ca");
setContentView(R.layout.activity_annonces);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
new AsyncCaller().execute();
TextView t = (TextView) findViewById(R.id.testing);
t.setText(scat);
// String generate = "https://www.waslup.pw/generation-json";
// String myurl = "https://www.waslup.pw/wp-content/uploads/wpdata.json";
// new MyAsyncTaskgetNews().execute(generate);
// new MyAsyncTaskgetNews().execute(myurl);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public void finish() {
super.finish();
instance = null;
}
public void buclick(View view) {
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.annonces, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.home) {
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
finish();
}
else if (id == R.id.login) {
Intent i = new Intent(this,login.class);
startActivity(i);
}
else if (id == R.id.avanced_search) {
Intent i = new Intent(this,avanced_search.class);
startActivity(i);
}
else if (id == R.id.annonces) {
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
}else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
class MyCustomAdapter extends BaseAdapter {
ArrayList<annonce_item> Items = new ArrayList<annonce_item>();
MyCustomAdapter(ArrayList<annonce_item> Items) {
this.Items = Items;
}
#Override
public int getCount() {
return Items.size();
}
#Override
public String getItem(int position) {
return Items.get(position).ititre;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater linflater = getLayoutInflater();
View view1 = linflater.inflate(R.layout.activity_annonce_item, null);
TextView id1 = (TextView) view1.findViewById(R.id.id);
TextView date1 = (TextView) view1.findViewById(R.id.date);
TextView cat1 = (TextView) view1.findViewById(R.id.cat);
TextView loc1 = (TextView) view1.findViewById(R.id.loc);
TextView titre1 = (TextView) view1.findViewById(R.id.titre);
TextView vue1 = (TextView) view1.findViewById(R.id.vue);
date1.setText(Items.get(i).idate);
id1.setText(Items.get(i).iid);
cat1.setText(Items.get(i).icat);
loc1.setText(Items.get(i).iloc);
titre1.setText(Items.get(i).ititre);
vue1.setText(Items.get(i).ivue);
return view1;
}
}
/*
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
new AsyncCaller().execute();
}*/
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(annonces.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("/tChargement des annonces en cours ... ");
pdLoading.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("https://www.waslup.pw/wp-admin/admin-ajax.php?action=do_ajax&fn=get_posts&count=10&key="+skey+"&cat="+scat+"&loc="+sloc);
HttpURLConnection httpuc = (HttpURLConnection) url.openConnection();
InputStream inputstream = httpuc.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(inputstream));
String line ="";
while(line != null){
line = bf.readLine();
data= data + line;
}
JSONArray JA = null;
JA = new JSONArray(data);
annonces.Items.removeAll(annonces.Items);
for (int i=0 ; i<JA.length();i++){
JSONObject JO =(JSONObject) JA.get(i);
date =""+ JO.get("date");
loc =""+ JO.get("loc");
cat =""+ JO.get("Cat");
vue =""+ JO.get("vue");
titre =""+ JO.get("title");
id =""+ JO.get("Id");
annonces.Items.add(new annonce_item(id,date,loc,cat,vue,titre));
}
} catch (MalformedURLException e) {
} catch (JSONException e) {
} catch (IOException e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//this method will be running on UI thread
pdLoading.dismiss();
final MyCustomAdapter myadpter = new MyCustomAdapter(Items);
ListView ls = (ListView) findViewById(R.id.listannonce);
ls.setAdapter(myadpter);
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView titre = (TextView) view.findViewById(R.id.titre);
Toast.makeText(getApplicationContext(), titre.getText(), Toast.LENGTH_LONG).show();
myadpter.notifyDataSetChanged();
TextView id2 = (TextView) view.findViewById(R.id.id);
Intent intent = new Intent(getBaseContext(), annonce_details.class);
intent.putExtra("id_from_annonces_activity", id2.getText());
startActivity(intent);
}
});
}
}
}
I reviewed your code and solved your problem.
There are two things need to discuss.
Your API providing the results according to localisation.If we change first two fields results will remain same and web service is fetching only one item with localisation 'oran'. But if we change localisation from 'oran' to 'alger' web service is displaying 4 results.
Here is the problem in your code.You are not concatenating your results properly in your data string. I have updated your code and now your code of AsyncCaller in announces Activity should be like:
Here is the code
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(annonces.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("/tChargement des annonces en cours ... ");
pdLoading.show();
}
#SuppressLint("NewApi")
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("https://www.waslup.pw/wp-admin/admin-ajax.php?action=do_ajax&fn=get_posts&count=10&key="+skey+"&cat="+scat+"&loc="+sloc);
HttpURLConnection httpuc = (HttpURLConnection) url.openConnection();
InputStream inputstream = httpuc.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(inputstream));
StringBuilder total = new StringBuilder();
String line;
while ((line = bf.readLine()) != null) {
total.append(line).append('\n');
}
JSONArray JA = null;
JA = new JSONArray(total.toString());
annonces.Items.removeAll(annonces.Items);
for (int i=0 ; i<JA.length();i++){
JSONObject JO =(JSONObject) JA.get(i);
date =""+ JO.get("date");
loc =""+ JO.get("loc");
cat =""+ JO.get("Cat");
vue =""+ JO.get("vue");
titre =""+ JO.get("title");
id =""+ JO.get("Id");
annonces.Items.add(new annonce_item(id,date,loc,cat,vue,titre));
}
} catch (MalformedURLException e) {
} catch (JSONException e) {
Log.d("js_ex:",e.toString());
} catch (IOException e) {
Log.d("io_ex:",e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//this method will be running on UI thread
pdLoading.dismiss();
final MyCustomAdapter myadpter = new MyCustomAdapter(Items);
ListView ls = (ListView) findViewById(R.id.listannonce);
ls.setAdapter(myadpter);
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView titre = (TextView) view.findViewById(R.id.titre);
Toast.makeText(getApplicationContext(), titre.getText(), Toast.LENGTH_LONG).show();
myadpter.notifyDataSetChanged();
TextView id2 = (TextView) view.findViewById(R.id.id);
Intent intent = new Intent(getBaseContext(), annonce_details.class);
intent.putExtra("id_from_annonces_activity", id2.getText());
startActivity(intent);
}
});
}
}
In this code i added this part
StringBuilder total = new StringBuilder();
String line;
while ((line = bf.readLine()) != null) {
total.append(line).append('\n');
}
JSONArray JA = null;
JA = new JSONArray(total.toString());

why MainActivity have ListaPaises=null and why setOnItemSelectedListener doesnt work?

This app try to receive a .csv from a url. then we get a list of countries and try to show it on a spinner. i cant understand why ListaPaises is null in MainActivity and why setonitemselectedlistener doesnt work.
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Toast;
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.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private static final String UPDATE_URL = "http://download.finance.yahoo.com/d/quotes.csv?s=EURUSD=X&f=sl1d1t1ba&e=.csv.";
private static final String UPDATE_PAISES = "http://www.atc.uniovi.es/grado/4at/misc/currencies.csv";
private Button button;
private Button button2;
public double mEuroToDollar = 1.34;
public static List<String> ListaPaises = new ArrayList<String>();
EditText mEditTextEuros;
EditText mEditTextDollars;
public String PaisSEL1;
public String PaisSEL2;
String [] datos = {"OPC1", "OPC2","OPC3"};
Spinner sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetPaises().execute(UPDATE_PAISES);
List<String> pruebas = ListaPaises;
sp = (Spinner) findViewById(R.id.spinner);
// Spinner sp2 = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter <String> adapter= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item,ListaPaises);
sp.setAdapter(adapter);
//sp2.setAdapter(adapter);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent,View v,int position, long id){
PaisSEL1 = parent.getItemAtPosition(position).toString();
}
public void onNothingSelected(AdapterView<?> parent){
}
});
mEditTextEuros = (EditText) findViewById(R.id.editText);
mEditTextDollars = (EditText) findViewById(R.id.editText2);
button = (Button) findViewById(R.id.button);
//button2 = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Conversion realizada",
Toast.LENGTH_SHORT).show();
ConvertToDollars(mEditTextEuros, mEditTextDollars, mEuroToDollar);
}
});
/*button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Convierte a Euros",
Toast.LENGTH_SHORT).show();
ConvertToEuros(mEditTextEuros, mEditTextDollars, mEuroToDollar);
}
});*/
}
#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;
}
// Se llama cuando el usuario pulsa el botón
#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);
}
public void ConvertToDollars(EditText mEditTextEuros, EditText mEditTextDollars,
double mEuroToDollar) {
String StringSource = mEditTextEuros.getText().toString();
double NumberSource;
try {
NumberSource = Double.parseDouble(StringSource);
} catch (NumberFormatException nfe) {
return;
}
double NumberDestination = NumberSource * mEuroToDollar;
String StringDestination = Double.toString(NumberDestination);
mEditTextDollars.setText(StringDestination);
}
public void ConvertToEuros(EditText mEditTextDollars, EditText mEditTextEuros,
double mEuroToDollar) {
String StringSource = mEditTextDollars.getText().toString();
double NumberSource;
try {
NumberSource = Double.parseDouble(StringSource);
} catch (NumberFormatException nfe) {
return;
}
double NumberDestination = NumberSource / mEuroToDollar;
String StringDestination = Double.toString(NumberDestination);
mEditTextEuros.setText(StringDestination);
}
public class GetPaises extends AsyncTask<String, List<String>, List<String>> {
public void onPostExecute(List<String> result) {
}
public List<String> doInBackground(String... urls) {
List<String> ListaMonedas= getCurrencyRateUsdRate(urls[0]);
//return String.valueOf(getCurrencyRateUsdRate(urls[0]));
return ListaMonedas;
}
private List<String> getCurrencyRateUsdRate(String url) {
String auxiliar = null;
try {
auxiliar = readStream(openUrl("http://www.atc.uniovi.es/grado/4at/misc/currencies.csv"));
} catch (IOException e) {
e.printStackTrace();
}
List<String> auxiliar2 = parseDataFromNetwork(auxiliar);
return auxiliar2;
}
protected String readStream(InputStream urlStream) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(urlStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
return total.toString();
}
protected InputStream openUrl(String urlString) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
return conn.getInputStream();
}
private List<String> parseDataFromNetwork(String data) {
String[] lineDataaux = data.split("country");
String lineDataaux2 = lineDataaux[1];
String[] lineData = lineDataaux2.split(",");
List<String> CodigosMonedas=new ArrayList();
for (int i=2 ; i<lineData.length ; i=i+4){
ListaPaises.add(lineData[i]);
}
//if (lineData.length != CSV_FIELDS) {
// return null;
//}
return CodigosMonedas;
}
}
}
In this point of MainActivity, ListaPaises should be and array of 730 elements but is null and setonitemselected doesnt work:
new GetPaises().execute(UPDATE_PAISES);
List<String> pruebas = ListaPaises;
sp = (Spinner) findViewById(R.id.spinner);
// Spinner sp2 = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter <String> adapter= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item,ListaPaises);
sp.setAdapter(adapter);
//sp2.setAdapter(adapter);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent,View v,int position, long id){
PaisSEL1 = parent.getItemAtPosition(position).toString();
}
public void onNothingSelected(AdapterView<?> parent){
}
});
The csv file is this:
http://gyazo.com/657f5dffc5092cc6d623fb94de3c87ba
ListaPaises was initialized in a wrong place. It should be initialized in AsyncTask class.

getting text from EditText in android

I have written this code for searching a text file for a string. The problem is, it says that the string is not found even if it is present. Process is to receive the text from the EditText and then start the searching process. But it shows that string is found every time.
package com.example.demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button;
final EditText obedittext;
button =(Button)findViewById(R.id.button1);
obedittext =(EditText)findViewById(R.id.editText1);
button.setOnClickListener(
new View.OnClickListener()
{
boolean textfound;
public void onClick(View view)
{
textfound = searchtext(obedittext.getText().toString());
if(textfound)
maketoast(obedittext.getText().toString());
else
maketoast("Unsuccessfull");
}
});
}
protected boolean searchtext(String string) {
// TODO Auto-generated method stub
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new InputStreamReader(getAssets().open("mneumo.txt")));
while ((sCurrentLine = br.readLine()) != null) {
if(sCurrentLine.equals(string)) {
return true;
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
finally{
}
return false;
}
private void maketoast(String string) {
// TODO Auto-generated method stub
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, string , Toast.LENGTH_SHORT);
toast.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
So when i tried to give the string inside the code itself instead of getting it from the edittext,it works fine. Like this,
string = "SPINAL ANESTHESIA AGENTS";
The sample text file is,
SPINAL ANESTHESIA AGENTS
XYLOCAINE: WHERE NOT TO USE WITH EPINEPHRINE
GENERAL ANAESTHESIA: EQUIPMENT CHECK PRIOR TO INDUCING
So how can i rectify this problem? Can anyone say why i am getting this problem?
Should i any other method to compare the strings?
The text file is correctly placed in the assets folder. And i accessed it using the assetmanager. And i am a total newbie to android development.
May be your editText contain some white space already, To get text from your editText try this:
obedittext.getText().toString().trim();
and inside your searchtext() method, replace your if condition with:
if(sCurrentLine.equalsIgnoreCase(string))

java.lang.NullPointerException when I'm trying to make button invisible

This method works fine.
public void onClick(View view) {
btn = (Button) findViewById(R.id.trytogetin);
progr = (ProgressBar) findViewById(R.id.progressBar);
btn.setVisibility(View.INVISIBLE);
progr.setVisibility(View.VISIBLE);
EditText login = (EditText) findViewById(R.id.loginfld);
EditText passw = (EditText) findViewById(R.id.passfld);
String logincmd = "CheckLogin*" + login.getText() + "*" + passw.getText() + "*";
ss.senddata(logincmd, 1);
}
In this method java.lang.NullPointerException appears (on btn.setVisibility(View.VISIBLE);
public void geturdata(String answer) {
if (answer != null)
{
System.out.println("true");
btn.setVisibility(View.VISIBLE);
}
else
{
System.out.println("false");
}
}
Please tell me how can I call button in this method? Also I can't use StartActivity(intent) in this method.(same error). Both metods placed in one activity.
Here is full code
This is activity
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.content.Intent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
public class Login extends Activity {
SocketServer ss = new SocketServer();
Button btn;
ProgressBar progr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn = (Button) findViewById(R.id.trytogetin);
progr = (ProgressBar) findViewById(R.id.progressBar);
try {
ss.setserver();
} catch (Exception ex) {
System.out.println("------- " + ex);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
menu.add("menu1");
getMenuInflater().inflate(R.menu.login, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClick(View view) {
btn.setVisibility(View.INVISIBLE);
progr.setVisibility(View.VISIBLE);
EditText login = (EditText) findViewById(R.id.loginfld);
EditText passw = (EditText) findViewById(R.id.passfld);
String logincmd = "CheckLogin*" + login.getText() + "*" + passw.getText() + "*";
ss.senddata(logincmd, 1);
}
public void geturdata(String answer) {
if (answer != null)
{
System.out.println("true");
btn.setVisibility(View.VISIBLE);
}
else
{
System.out.println("false");
}
}
}
And this is class that call >geturdata
import android.os.Looper;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketServer {
private Socket socket;
private static final int SERVERPORT = 11000;
private static String SERVER_IP = "192.168.2.222";
String answer;
private static String cmdtext;
private static int caller;
class ClientThread implements Runnable
{
public void run() {
if (cmdtext.equals("setserver"))
{
try
{
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
}
catch (Exception ex)
{System.out.println(ex);}
}
else {
try {
String str = cmdtext;
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println(str);
out.flush();
byte[] data = new byte[256];
InputStream inp = socket.getInputStream();
inp.read(data);
answer = new String(data, "UTF-8");
Looper.prepare();
handledata(answer);
Looper.loop();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
////////////////////////////////////////
public void setserver ()
{
new Thread(new ClientThread()).start();
cmdtext = "setserver";
}
private void handledata(String answer)
{
switch (caller) {
case 1:
{
Login lgn = new Login();
lgn.geturdata(answer);
}
}
}
public void senddata(String cmd, int callerid)
{
this.cmdtext = cmd;
this.caller = callerid;
new Thread(new ClientThread()).start();
}
}
btn is null when you call geturdata(). You should call btn = (Button) findViewById(R.id.trytogetin); directly after setContentView(R.layout.activity_main); in public void onCreate(Bundle b)
private Button btn;
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.trytogetin);
...
}
EDIT:
But, seeing your code now, thats not the problem. There are two problems here
Login lgn = new Login();
lgn.geturdata(answer);
You try to instantiate an Activity. You should start activities through intents, so that they are instanciated in the normal Activity lifecycle: through onCreate.
But there's more: You try to set the Button from another Thread than the one which created the Button (the UI-thread)
You can try to get a handle from the context in the thread, and call context.runOnUiThread(Runnable). That way you can update the UI from other Threads.
So the NPE is caused by the fact that you instantiate Login (which has to be done by Android), and call a method, but theres no ContentView inflated, so the Button is not found anyway, findViewById returns null
You are getting id of button inside click method. So to solve the problem , get your button id in oncreate() method. So you can access button anywhere. But declare button globaly
Declare this in OnCreate()
btn = (Button) findViewById(R.id.trytogetin);
progr = (ProgressBar) findViewById(R.id.progressBar);
public void onClick(View view) {
btn.setVisibility(View.INVISIBLE);
progr.setVisibility(View.VISIBLE);
}
String logincmd = "CheckLogin*" + login.getText().toString() + "*" + passw.getText().toString() + "*";
So reference to this method geturdata where you used object of Button btn returns null, since you used inside onClick button.
public void geturdata(String answer) {

Android Voice input without click

I am new to android development. I need a solution for the new app I am developing which takes voice input and gives output in voice by mapping with a mapping database. Current program takes voice input with onlick on button . I need a soultion which can take voice input without clicking of any button simliar to Talking Tom application . Here is my code.My main code is in speakToMe which is method called on onclick & onActivityResult
package com.example.secondprog;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
import com.example.secondprog.*;
//import com.example.secondprog.DatabaseHelper;
public class MainActivity extends Activity {
private static final int VOICE_RECOGNITION_REQUEST = 0;
//private static final int VOICE_RECOGNITION_REQUEST = 0x10101;
TextToSpeech ttobj;
String resulttxt ;
TestDBClass db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new TestDBClass(this, null, null, 1);
try {
db.loadWords();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ttobj=new TextToSpeech(getApplicationContext(),
new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
ttobj.setLanguage(Locale.UK);
Toast.makeText(getApplicationContext(), "No error",
Toast.LENGTH_LONG).show();
}
}
});
//DatabaseHelper db = DatabaseHelper(this);
//dbdtls dbdtlsresult = new dbdtls();
//String message3 = db.getdtls("how are");
//String output = dbdtlsresult.new_name();
//EditText editText = (EditText) findViewById(R.id.edit_message);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void sendMessage(View view) {
EditText editText = (EditText) findViewById(R.id.edit_message);
String txt = editText.getText().toString();
// Toast.makeText(getApplicationContext(), txt.toUpperCase(),
// Toast.LENGTH_LONG).show();
DictonaryDAO dictonaryDAO =
db.findname(txt.toUpperCase());
if (dictonaryDAO != null) {
resulttxt = String.valueOf(dictonaryDAO.getnewname());
Toast.makeText(getApplicationContext(), resulttxt.toUpperCase(),
Toast.LENGTH_LONG).show();
}
ttobj.speak(resulttxt, TextToSpeech.QUEUE_FLUSH, null);
}
/*#Override
public void onPause(){
if(ttobj !=null){
ttobj.stop();
ttobj.shutdown();
}
super.onPause();
}
*/
**public void speakToMe(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Please speak slowly and enunciate clearly.");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST && resultCode == RESULT_OK) {
ArrayList<String> matches = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
// TextView textView = (TextView) findViewById(R.id.speech_io_text);
String firstMatch = matches.get(0);
// textView.setText(firstMatch);
DictonaryDAO dictonaryDAO =
db.findname(firstMatch.toUpperCase());
if (dictonaryDAO != null) {
resulttxt = String.valueOf(dictonaryDAO.getnewname());
Toast.makeText(getApplicationContext(), resulttxt.toUpperCase(),
Toast.LENGTH_LONG).show();
ttobj.speak(resulttxt, TextToSpeech.QUEUE_FLUSH, null);
}
}
}**
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
Voice Recognition not working for talking tom app so you try to use noise detection with sound meter. below here link for voice/ noise detection with audio recording without click.
http://androidexample.com/Detect_Noise_Or_Blow_Sound_-_Set_Sound_Frequency_Thersold/index.php?view=article_discription&aid=108&aaid=130
Please change SoundMeter.java File
mRecorder.setOutputFile(Environment.getExternalStorageDirectory().
getAbsolutePath() + "/test.3ggp");

Categories

Resources