I'm working on a big program for Android and I'm trying to get the currency converter part of the program to work. For full disclosure: I found it from http://firstamong.com/building-android-currency-converter/, and it's a tutorial on how to build a real-time currency converter. I'll post the code in question followed by the logcat. The error that occurs is when I try to convert from one currency to another, the application says it was forced to stop. However, the "Invalid" portion works (the case where both currency fields are the same.) Any help would truly be appreciated:
Code:
public class currency_converter extends Activity {
public int to;
public int from;
public String [] val;
public String s;
public Handler handler;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_currency_converter);
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
Spinner s2 = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.name, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
val = getResources().getStringArray(R.array.value);
s1.setAdapter(adapter);
s2.setAdapter(adapter);
s1.setOnItemSelectedListener(new spinOne(1));
s2.setOnItemSelectedListener(new spinOne(2));
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
TextView t = (TextView) findViewById(R.id.textView4);
if(from == to)
{
Toast.makeText(getApplicationContext(), "Invalid", 4000).show();
}
else
{
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
t.setText(exResult);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
public String getJson(String url)throws ClientProtocolException, IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
private class spinOne implements OnItemSelectedListener
{
int ide;
spinOne(int i)
{
ide =i;
}
public void onItemSelected(AdapterView<?> parent, View view,
int index, long id) {
if(ide == 1)
from = index;
else if(ide == 2)
to = index;
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
class GetResponseData extends AsyncTask<String, String, String> {
private ProgressDialog dialog;
private ArrayList<String> titleList;
private TextView textView;
public GetResponseData(TextView textView) {
this.textView = textView;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(currency_converter.this, "", "Loading",
false);
}
#Override
protected String doInBackground(String... params) {
try {
String s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22" + val[from] + val[to] + "%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
return exResult;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog != null)
dialog.dismiss();
if (result != null) {
textView.setText(result);
}
}
}
}
}
Logcat:
10-30 00:59:48.164 20591-20591/com.example.travelapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:365)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:587)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:511)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:489)
at com.example.travelapplication.currency_converter.getJson(currency_converter.java:93)
at com.example.travelapplication.currency_converter$1.onClick(currency_converter.java:68)
at android.view.View.performClick(View.java:4222)
at android.view.View$PerformClick.run(View.java:17620)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5391)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Try this,,
Your performing a networking operation on its main thread. That why your getting NetworkOnMainThreadException
b.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
TextView t = (TextView) findViewById(R.id.textView4);
if(from == to)
{
Toast.makeText(getApplicationContext(), "Invalid", 4000).show();
}
else
{
GetResponseData abcd = GetResponseData(t);
abcd.execute();
}
}
});
You are getting:
NetworkOnMainThreadException
Issue is that you are calling your function getJson() in your Activity.
Use AsyncTask:
public class ProcessTask extends AsyncTask<Void, Integer, String>{
public ProcessTask() {
// TODO Auto-generated constructor stub
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
//your code of parsing
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url); //your yahooapi url goes here
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
It looks like you have strict mode on in your android manifest. Strict mode will complain when you are doing network calls on you main thread. You can just disable strict mode or a better approach is to put your network call into an async task. The network call in question is
HttpResponse response = client.execute(httpGet);
inside public String getJson(String url)
The async task you need is already there you just need to use it
Change this else statement
else
{
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
t.setText(exResult);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
To this
else {
new GetResponseData().execute("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
}
It will help use this :
public class CurrencyConverter extends Fragment {
public CurrencyConverter() {
}
TextView t;
public int to;
public int from;
public String[] val;
public String s;
String exResult;
public Handler handler;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.currency_converter, container, false);
t= (TextView) rootView.findViewById(R.id.textView4);
Spinner s1 = (Spinner) rootView.findViewById(R.id.spinner1);
Spinner s2 = (Spinner) rootView.findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this.getActivity(), R.array.name, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
val = getResources().getStringArray(R.array.value);
s1.setAdapter(adapter);
s2.setAdapter(adapter);
s1.setOnItemSelectedListener(new spinOne(1));
s2.setOnItemSelectedListener(new spinOne(2));
Button b = (Button) rootView.findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View View) {
if (from == to) {
Toast.makeText(getActivity().getApplicationContext(), "Invalid", 4000).show();
} else {
new calculate().execute();
}
}
});
return rootView;
}
public class calculate extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... args) {
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return exResult;
}
#Override
protected void onPostExecute(String exResult) {
t.setText(exResult);
}
}
public String getJson(String url)throws IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
public class spinOne implements AdapterView.OnItemSelectedListener
{
int ide;
spinOne(int i)
{
ide =i;
}
public void onItemSelected(AdapterView<?> parent, View view,
int index, long id) {
if(ide == 1)
from = index;
else if(ide == 2)
to = index;
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
}
Related
I tried to get help on this post without any luck, I played around with code but still no luck. My list for example is as follows: Blue, Red, Purple from Json remote server.
When I type B.. it returns Blue. OK
When I type X.. it returns no results because no color matched "X". OK
When I type R.. (or RE.. or RED) it returns Blue instead of returning Red.
Conclusion - The code always returns the first item on the list when filtered.
My code:
JSON:
private class JsonReadTask extends AsyncTask<String, Void, String> {
//Pending 01
private ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPreExecute() {
this.dialog.setMessage("Loading Rooms, Please Wait");
this.dialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getActivity(),"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
//Pending 02
if (dialog.isShowing()) {
dialog.dismiss();
}
adapter.notifyDataSetChanged();
try{
ListDrwaer(); //has ConnectionException (when it cannot reach server)
}catch (Exception e){
Toast.makeText(getActivity(), "Please check your connection..", Toast.LENGTH_LONG).show();
}
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { "http://www.website.com/file.php?psortby="+sortby});
}
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("room_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String request_title = jsonChildNode.optString("Title");
String request_members = jsonChildNode.optString("Members");
request_title_replaced = request_title.replace("room_", "");
arrRequest_Title.add(request_title_replaced);
arrRequest_Members.add(request_members);
}
} catch (JSONException e) {
System.out.println("Json Error Rooms" +e.toString());
//Toast.makeText(getApplicationContext(), "No Rooms To Load", Toast.LENGTH_SHORT).show();
}
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
Adapter:
class RoomsAdapter extends ArrayAdapter<String>
{
#Override
public void clear() {
super.clear();
arrRequest_Title.clear();
arrRequest_Members.clear();
}
Context context;
List<String> Request_Title;
List<String> Request_Members;
RoomsAdapter(Context c, List<String> Request_Title, List<String> Request_Members)
{
super(c, R.layout.activity_rooms_single, R.id.textTitle, Request_Title);
this.context=c;
this.Request_Title=Request_Title;
this.Request_Members=Request_Members;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row=convertView;
if(row==null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.activity_rooms_single, parent, false);
}
TextView txtTitle = (TextView) row.findViewById(R.id.textTitle);
TextView txtMembers = (TextView) row.findViewById(R.id.textMembers);
txtTitle.setText(Request_Title.get(position));
txtMembers.setText(Request_Members.get(position));
return row;
}
}
Fragment Class:
public class Fragment_01_Rooms extends Fragment
JSONParser.class
package com.example.diptiagravat.myapplication;
public class JSONParser {
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
public String sendHTTPData(String urlpath, String id) {
HttpURLConnection connection = null;
try {
URL url=new URL(urlpath);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
streamWriter.write(id);
streamWriter.flush();
StringBuilder stringBuilder = new StringBuilder();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(streamReader);
String response = null;
while ((response = bufferedReader.readLine()) != null) {
stringBuilder.append(response + "\n");
}
bufferedReader.close();
Log.d("test", stringBuilder.toString());
return stringBuilder.toString();
} else {
Log.e("test", connection.getResponseMessage());
return null;
}
} catch (Exception exception){
Log.e("test", exception.toString());
return null;
} finally {
if (connection != null){
connection.disconnect();
}
}
}
}
MainActivity.java
package com.example.diptiagravat.myapplication;
public class MainActivity extends AppCompatActivity {
private TextView txtid, txtcname;
Spinner spcnt, spstate;
public ArrayList<String> clist;
ArrayAdapter<String> cad;
public ArrayList<String> slist;
ArrayAdapter<String> sad;
public String strcnt;
private static String url = "http://urmiinfotech.com/demo/ifirst/app_api/get_country_list.php";
private static String stateUrl = "http://urmiinfotech.com/demo/ifirst/app_api/get_state_list.php";
private static final String TAG_USER = "country";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "country_name";
private ArrayList<Country> clistModels;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
CountryAsyncTask countryAsyncTask= new CountryAsyncTask();
countryAsyncTask.execute();
}
private void initViews() {
txtid = (TextView) findViewById(R.id.tvid);
txtcname = (TextView) findViewById(R.id.tvcname);
spcnt = (Spinner) findViewById(R.id.spcnt);
spstate = (Spinner) findViewById(R.id.spstate);
clist = new ArrayList<String>();
slist = new ArrayList<String>();
}
public class CountryAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = null;
try {
json = new JSONObject(jParser.getJSON(url, 5000));
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.i("Result Ravi", result);
try {
JSONObject obj = new JSONObject(result);
JSONArray cntArray = obj.getJSONArray("country");
if (cntArray.length() > 0) {
for (int i = 0; i < cntArray.length(); i++) {
final JSONObject temp = cntArray.getJSONObject(i);
// txtid.setText(temp.getString("id"));
// txtcname.setText(temp.getString("country_name"));
Country country = new Gson().fromJson(temp.toString(), Country.class);
clist = new ArrayList<String>();
clistModels = new ArrayList<Country>();
clistModels.add(new Country(temp.optString("id"), temp.optString("country_name"), "", null));
clist.add(temp.getString("country_name"));
cad = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, clist);
spcnt.setAdapter(cad);
spcnt.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
strcnt = clistModels.get(position).getId();
//strcnt = parent.getItemAtPosition(position).toString();
Log.i("id", strcnt);
new StatesAsyncTask().execute();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// txtid.setText(temp.getString(country.getId()));
// txtcname.setText(temp.getString(country.getCountryName()));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class StatesAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = null;
try {
json = new JSONObject(jParser.sendHTTPData(stateUrl, strcnt));
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject obj = new JSONObject(s);
JSONArray stArray = obj.getJSONArray("statelist");
if (stArray.length() > 0) {
for (int i = 0; i < stArray.length(); i++) {
final JSONObject temp = stArray.getJSONObject(i);
// txtid.setText(temp.getString("id"));
// txtcname.setText(temp.getString("country_name"));
Statelist stlist = new Gson().fromJson(temp.toString(), Statelist.class);
slist = new ArrayList<String>();
// clistModels = new ArrayList<Country>();
//clistModels.add(new Country(temp.optString("id"), temp.optString("country_name"), "", null));
slist.add(temp.getString("state_name"));
sad = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, slist);
spstate.setAdapter(sad);
spstate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// strcnt = clistModels.get(position).getId();
//strcnt = parent.getItemAtPosition(position).toString();
// Log.i("id", strcnt);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// txtid.setText(temp.getString(country.getId()));
// txtcname.setText(temp.getString(country.getCountryName()));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
My response is null?
HttpURLConnection is deprecated in Android Lollipop, so please try to use DefaultHttpClient instead. Also, check your logs, this is at your onPostExecute():
Log.i("Result Ravi", result);
For DefaultHttpClient check this post.
Another way is to try Retrofit
The following is the CODE I am using to get the data from Codeforces.com API as JSON response. If anyone can please help me improve this to convert them to clickable links and then attach a web link to them. :
public class Http extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://codeforces.com/api/user.status?handle=";
String m = "";
public static String[] sarr = new String[200];
public static String[] name = new String[200];
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.httpex);
httpStuff = (TextView)findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
new Read().execute("result");
}
public JSONObject lastSub(String username) throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
url.append(username);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if(status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONObject last = new JSONObject(data);
//JSONObject last = new JSONObject(data).getJSONArray("result").getJSONObject(0).getJSONObject("problem");
JSONArray array = new JSONObject(data).getJSONArray("result");
String m1=null, m2=null, m3=null;
String n1 = System.getProperty("line.separator");
int cnt=0, flag=0;
for(int k=0; k<array.length(); k++)
{
last = array.getJSONObject(k).getJSONObject("problem");
JSONObject v = array.getJSONObject(k);
if(v.getString("verdict").contentEquals("OK")) {
m1 = last.getString("name");
m2= last.getString("contestId");
m2= m2.concat("/");
m3= last.getString("index");
m2 = m2.concat(m3);
flag = 0;
for(int i=0; i<cnt; i++) {
if (sarr[i].equals(m1)) {
flag = 1;
}
}
if(flag == 0) {
m = m.concat(m1);
m= m.concat(n1);
sarr[cnt] = m1;
name[cnt] = m2;
cnt++;
}
}
}
return last;
}
else {
Toast.makeText(Http.this, "error", Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask <String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
json = lastSub("avm12&from=1&count=100");
return m;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
httpStuff.setText(result);
}
}
}
Make sure your main layout R.layout.httpex has a ListView.
(Should look like this)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Create a new layout list_item.xml representing the data you want to display :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/pTitle"
android:textAppearance="#android:style/TextAppearance.DeviceDefault.Medium"
android:padding="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/pUrl"
android:visibility="gone" />
</LinearLayout>
Then edit your code like this :
public class Http extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://codeforces.com/api/user.status?handle=";
String m = "";
ListView list;
public static ArrayList<HashMap<String, String>> problemdata= new ArrayList<HashMap<String, String>>();
//above ArrayList replacing sarr & name
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.httpex);
list=(ListView)findViewById(R.id.list);
httpStuff = (TextView)findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
new Read().execute("result");
}
public JSONObject lastSub(String username) throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
url.append(username);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONObject last = new JSONObject(data);
//JSONObject last = new JSONObject(data).getJSONArray("result").getJSONObject(0).getJSONObject("problem");
JSONArray array = new JSONObject(data).getJSONArray("result");
String n1 = System.getProperty("line.separator");
for (int k = 0; k < array.length(); k++) {
last = array.getJSONObject(k).getJSONObject("problem");
JSONObject v = array.getJSONObject(k);
if (v.getString("verdict").contentEquals("OK")) {
HashMap<String, String> d = new HashMap<String, String>();
d.put("NAME",last.getString("name"));
d.put("URL","http://codeforces.com/problemset/problem/"+last.getString("contestId")+"/"+last.getString("index"));
if(!problemdata.contains(d)) {
m = m.concat(last.getString("name")).concat(n1); //m+=last.getString("name")+"\r\n";
problemdata.add(d);
}
}
}
return last;
} else {
Toast.makeText(Http.this, "error", Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
json = lastSub("avm12&from=1&count=100");
return m;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
httpStuff.setText(result);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//get the url from the invisible TextView ad opens it on the default browser
TextView t=(TextView)view.findViewById(R.id.pUrl);
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(t.getText().toString())));
}
});
ListAdapter adapter = new SimpleAdapter(
Http.this, problemdata,
R.layout.list_item, new String[] { "NAME", "URL" }, new int[] { R.id.pTitle,
R.id.pUrl});
list.setAdapter(adapter);
}
}
}
below is my code there is a problem some where in getDataTask if i remove this class is work fine and print Toast message Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); but what is problem in my getDataTask im parsing below json file problem is some where in doinbackground method help me please
{"status":0,"message":"No such school found"}
public class thirdstep extends Activity {
ListView listCategory;
String status;
String message;
String MenuSelect;
ProgressBar prgLoading;
long Cat_ID;
String Cat_name;
String CategoryAPI;
int IOConnect = 0;
TextView txtAlert;
thirdstepAdapter cla;
static ArrayList<String> Category_ID = new ArrayList<String>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list2);
ImageButton btnback = (ImageButton) findViewById(R.id.btnback);
listCategory = (ListView) findViewById(R.id.listCategory2);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
cla = new thirdstepAdapter(thirdstep.this);
new getDataTask().execute();
listCategory.setAdapter(cla);
btnback.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
Intent iGet = getIntent();
Cat_ID = iGet.getLongExtra("category_id", 0);
Cat_name = iGet.getStringExtra("category_name");
Toast.makeText(this, Cat_ID + Cat_name, Toast.LENGTH_SHORT).show();
MenuSelect = Utils.MenuSelect;
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(thirdstep.this, fourthscreen.class);
iMenuList.putExtra("Cat_ID",Cat_ID);
iMenuList.putExtra("Menuitem", Category_ID.get(position));
startActivity(iMenuList);
}
});
}
void clearData() {
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void>{
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
prgLoading.setVisibility(8);
if((Category_ID.size() > 0) || IOConnect == 0){
listCategory.setVisibility(0);
listCategory.setAdapter(cla);
}else{
txtAlert.setVisibility(0);
}
}
}
public void parseJSONData() {
CategoryAPI = Utils.MenuList + Cat_ID;
clearData();
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
JSONObject json = new JSONObject(str);
JSONObject json2 = new JSONObject(str);
status = json2.getString("status");
message = json2.getString("message");
if (status.equals("1")) {
JSONObject data = json.getJSONObject("data");
JSONArray school = data.getJSONArray("menu_groups");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
Category_ID.add(object.getString("id"));
Category_name.add(object.getString("title"));
Category_image.add(object.getString("image"));
}
}
else
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You are calling parseJSONData() in doInbackground and you have this
Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); // in parseJSONData()
you cannot update ui from doInbackground. You need to update ui on the ui thread. Return result in doInbackground. In onPostExecute update ui.
I have a class extending listFragment. I have written code for fetching json response in a method which is called in oncreate of the class. For fetching json in background I have created new inner class which extends asyncTask. I can get the jsonarrays and strings in the json response in the logcat. But when I try to save them in a string array and pass them my custom baseadapter, I get a nullpointer exception.
public class OnlineInfo extends ListFragment {
public static String result;
public String[] Technologies1;
public String[] TechnologyDescription1;
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
downloadjsonresponse();
}
public class Download extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
StringBuilder stringbuilder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet url = new HttpGet(params[0]);
try
{
Log.d("in background", "in background");
HttpResponse response = client.execute(url);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line ;
while((line = reader.readLine()) != null)
{
stringbuilder.append(line);
}
}
catch(ClientProtocolException e)
{
Log.d("error in clientprotocol", "error");
e.printStackTrace();
}
catch(IOException e)
{
Log.d("error in IO", "error");
e.printStackTrace();
}
return stringbuilder.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
OnlineInfo.result = result;
try {
JSONObject jsonobject = new JSONObject(result);
JSONArray raja = jsonobject.getJSONArray("Technologies");
//String raja = jsonobject.getJSONArray("Technologies").getJSONObject(0).getString("desc");
//Log.d("desc:", raja);
for(int i=0; i<raja.length();i++)
{
Technologies1[i] = raja.getJSONObject(i).getString("name");
TechnologyDescription1[i] = raja.getJSONObject(i).getString("desc");
Log.d("technology :", raja.getJSONObject(i).getString("name"));
Log.d("technologydescription :", raja.getJSONObject(i).getString("desc"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("desc:", "error");
}
getListView().setAdapter(new AdapterForOnlineInfo(getActivity(), OnlineInfo.this.Technologies1, OnlineInfo.this.TechnologyDescription1));
}
}
public void downloadjsonresponse()
{
Download jsonresponse = new Download();
jsonresponse.execute("http://www.avantajsoftwares.com/result.json");
}
}
I could get the results in logcat whenever I comment these two lines in for-loop:
Technologies1[i] = raja.getJSONObject(i).getString("name");
TechnologyDescription1[i] = raja.getJSONObject(i).getString("desc");
Don't know what's going wrong. Please somebody provide me some insight....:-(
I think you need to allocate space in your string arrays to hold the new strings.
Just before your for loop, try putting something like this:
Technologies1 = new String[raja.length()];
TechnologyDescription1 = new String[raja.length()];