OnClick() is not working for currency converter. - android

I want to add currency converter in side menu of my app. But i am unable to get conversion after on click().
On click "calculate" i am not getting conversion.
Please see the code why i am not able to click . I have used yahoo api.
CurrencyConverter.java
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
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 info.androidhive.customlistviewvolley.R;
public class CurrencyConverter extends Fragment {
public CurrencyConverter() {
}
TextView t;
public int to;
public int from;
public String[] val;
public String s;
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 rootView) {
//t.setText(exResult);
if (from == to) {
Toast.makeText(getActivity().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();
}
}
}
});
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);
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();
}
return s;
}
#Override
protected void onPostExecute(String exResult) {
// t = (TextView) rootView.findViewById(R.id.textView4);
// t.setText(exResult);
}
}
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();
}
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
}
}
}
CurrencyConverter.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF"
>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#FFFFFF">
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/one"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/in"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/equal"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="122dp"
android:gravity="center"
android:background="#ffffff">
<RelativeLayout
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="120dp"
android:gravity="center"
android:background="#ffffff">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/result"
android:textSize="35dp"
/>
</RelativeLayout>
</RelativeLayout>
<Button
android:id="#+id/button1"
android:layout_marginTop="10dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/calculate" />
</LinearLayout>
</ScrollView>
Error:
05-09 17:33:30.425 2238-2238/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: info.androidhive.customlistviewvolley, PID: 2238
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:156)
at org.json.JSONObject.<init>(JSONObject.java:173)
at info.androidhive.customlistviewvolley.model.CurrencyConverter$1.onClick(CurrencyConverter.java:74)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-09 17:33:30.430 1233-1513/? W/ActivityManager: Force finishing activity info.androidhive.customlistviewvolley/.MainActivity

You are trying to invoke String from UI thread that has no connection to it. As one of the possible workarounds you can create global variable and assign to it at
#Override
protected void onPostExecute(String exResult) {
// t = (TextView) rootView.findViewById(R.id.textView4);
// t.setText(exResult);
globalString = exResult;
}
Afterwards you can use it code. Please read about AsyncTask lifecycle and Android Threads.

updated Answer:
CurreencyConverter.java
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
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 info.androidhive.customlistviewvolley.R;
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

add click Listner in each item of row in Listview

i want add clickable link in android listview item, i have 5 item in each row of listview and i want only two item make clickable and open sholud in webview using putextras() intents i am using custom adapter pls any one hlep me.
suppose "link 1" is: "view Proofing"(proofinglink) (in textview) and "link 2" is : "Get More Detail"(sitelink) i want when i click link 1 then it should open in webview behind his own given url . and when i click on link 2: it should also open in webview in his own given url. using putextras() intents
here is my code.
package tipster;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import newsletter.Latest_list;
import newsletter.Webview_news;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
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;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.example.newapp.R;
public class Tipster extends Activity {
ListView lv;
ArrayList<Tipster_list>listitem;
String title;
String serviceUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tipster);
if (isNetworkAvailable()) {
// Execution here
// Toast.makeText(this, "Network is Available!",
Toast.LENGTH_LONG).show();
execute();
title="Free Tip - Betfans";
lv=(ListView) findViewById(R.id.listView_tipsterID);
listitem=new ArrayList<Tipster_list>();
}
else {
Toast.makeText(this, "Network is unavailable!",
Toast.LENGTH_LONG).show();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
private void execute() {
serviceUrl ="http://mobile.betfan.com/api/?
Action=top&type=default&key=MEu07MgiuWgXwJOo7Oe1aHL0yM8VvP";
//Toast.makeText(LatestNews.this, serviceUrl, Toast.LENGTH_LONG).show();
class LoginAsync extends AsyncTask<String, Void, String>{
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(Tipster.this, "Please
while wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
JSONObject jsonObject = new JSONObject();
String dataString = jsonObject.toString();
InputStream is = null;
List<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", dataString));
String result = null;
try{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet();
URI apiurl = new URI(serviceUrl);
httpRequest.setURI(apiurl);
HttpResponse response = httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new
InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result){
String s = result.trim();
loadingDialog.dismiss();
JSONObject respObject;
try {
respObject = new JSONObject(s);
String active = respObject.getString("status_message");
if(active.equalsIgnoreCase("success")){
JSONArray array =
respObject.getJSONArray("response");
for (int i =0; i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
String icon= jsonObject.getString("image");
String name = jsonObject.getString("name");
String total = jsonObject.getString("total");
String proofinglink =
jsonObject.getString("proofinglink");
String sitelink = jsonObject.getString("sitelink");
listitem.add(new
Tipster_list(icon,name,"+"+total,proofinglink,sitelink));
}
lv.setAdapter(new Tipster_adapter(Tipster.this,
listitem));
}else {
Toast.makeText(Tipster.this, "services received
Fail", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String getName=listitem.get(arg2).getName();
String
getproofing=listitem.get(arg2).getProofinglink();
String getsite=listitem.get(arg2).getSitelink();
Intent intent = new Intent(getApplicationContext(),
Tipster_webview.class);
intent.putExtra("gettproofing_URl",getproofing);
intent.putExtra("getsiteURL",getsite);
startActivity(intent);
}
});
}
}
LoginAsync la = new LoginAsync();
la.execute();
}
i want "proofinglink" and "sitelink" should be clickable and open in webview
here is custom adapter
public class Tipster_adapter extends BaseAdapter {
Context context;
ArrayList<Tipster_list>tipslist;
public Tipster_adapter(Context context,
ArrayList<Tipster_list> tipslist) {
super();
this.context = context;
this.tipslist = tipslist;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return tipslist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
LayoutInflater inflater=(LayoutInflater)
context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.activity_tipster_adapter
,null);
ImageView icon=
(ImageView)convertView.findViewById(R.id.icon_tipsterIconID);
TextView name=(TextView)
convertView.findViewById(R.id.txt_name_tipsterID);
TextView total=(TextView)
convertView.findViewById(R.id.txt_total_tipsterID);
TextView proofingLink=(TextView)
convertView.findViewById(R.id.txt_proofinglink_tipsterID);
TextView siteLink=(TextView)
convertView.findViewById(R.id.txt_sitelink_tipsterID);
Tipster_list services=tipslist.get(position);
Picasso.with(context).load(services.getImage()).into(icon);
Log.d("Url",services.getImage());
name.setText(services.getName());
total.setText(services.getTotal());
proofingLink.setText(services.getProofinglink());
siteLink.setText(services.getSitelink());
}
return convertView;
}
}
your code is ok you need to add a listener in your adapter for the view on which you want to fire an intent for example
inside your adapter getview method paste this code like this
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Tipster_list services=tipslist.get(position);
if(services!=null){
LayoutInflater inflater=(LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.activity_custom_adapter,null);
ImageView icon=(ImageView)convertView.findViewById(R.id.icon_tipsterIconID);
TextView name=(TextView) convertView.findViewById(R.id.txt_name_tipsterID);
TextView total=(TextView) convertView.findViewById(R.id.txt_total_tipsterID);
TextView proofingLink=(TextView) convertView.findViewById(R.id.txt_proofinglink_tipsterID);
TextView siteLink=(TextView) convertView.findViewById(R.id.txt_sitelink_tipsterID);
Picasso.with(context).load(services.getImage()).into(icon);
Log.d("Url",services.getImage());
name.setText(services.getName());
total.setText(services.getTotal());
proofingLink.setText(services.getProofinglink());
siteLink.setText(services.getSitelink());
convertView.setTag(position);
String getName=services.getName();
final String getproofing=services.getProofinglink();
final String getsite=services.getSitelink();
proofingLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, Tipster_webview.class);
intent.putExtra("gettproofing_URl",getproofing);
context.startActivity(intent);
}
});
siteLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, Tipster_webview.class);
intent.putExtra("site",getsite);
context.startActivity(intent);
}
});
}
return convertView;
}
TextView proofingLink=(TextView) convertView.findViewById(R.id.txt_proofinglink_tipsterID);
proofingLink.setOnClickListener(new OnItemClickListener() {
#Override
public void onClick(View arg0) {
String url = services.getProofinglink();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
TextView proofingLink=(TextView)
convertView.findViewById(R.id.txt_proofinglink_tipsterID);
proofingLink.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
TextView siteLink=(TextView)
convertView.findViewById(R.id.txt_sitelink_tipsterID);
siteLink.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});

Facing Error in GetJson() & OnClick() in Fragments. Plese see code help me for same

I am adding side menu screen content as a Currencyconverter. When i am clicking to calculate currency it is not getting & App is crashing. I have used yahoo API for currency converter.
Facing Error in GetJson() & onClick() in Fragments. Please see code help me for same . i am stuck why this is happening ?
In 1st image is you can see the side menu & 2nd image come after clicking currency converter (via side menu click).
Currencyconverter.java
import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
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 info.androidhive.customlistviewvolley.R;
public class CurrencyConverter extends Fragment {
public CurrencyConverter() {
}
public int to;
public int from;
public String[] val;
public String s;
public Handler handler;
/**
* Called when the activity is first created.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.currency_converter, container, false);
/* public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);*/
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) {
TextView t = (TextView) View.findViewById(R.id.textView4);
if (from == to) {
Toast.makeText(getActivity().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();
}
});
return rootView;
}
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
}
}
}
CurrencyConverter.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF"
>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#FFFFFF">
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/one"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/in"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/equal"
android:textAppearance="?android:attr/textAppearanceLarge" />
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="122dp"
android:gravity="center"
android:background="#ffffff">
<RelativeLayout
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="120dp"
android:gravity="center"
android:background="#ffffff">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/result"
android:textSize="35dp"
/>
</RelativeLayout>
</RelativeLayout>
<Button
android:id="#+id/button1"
android:layout_marginTop="10dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/calculate" />
</LinearLayout>
</ScrollView>
Error:
FATAL EXCEPTION: main Process: info.androidhive.customlistviewvolley, PID: 8469
android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
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:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at info.androidhive.customlistviewvolley.model.CurrencyConverter$1.getJson(CurrencyConverter.java:98)
at info.androidhive.customlistviewvolley.model.CurrencyConverter$1.onClick(CurrencyConverter.java:76)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
As it said "NetworkOnMainThreadException" do not hit api direclty instead use AsyncTask for it .
Just define asynctask first
class Calculate extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... args) {
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 null;
}
#Override
protected void onPostExecute(String file_url) {
t.setText(exResult);
}
And call AsyncTask there
if (from == to) {
Toast.makeText(getActivity().getApplicationContext(), "Invalid", 4000).show();
} else {
new Calculate ().excute();
}
Answer:
Updated
CurrencyConverter.java
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
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 info.androidhive.customlistviewvolley.R;
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
}
}
}

Implement a relationship between two Spinners in android

I have 2 spinners in my application. I have loaded all the items got from json response. But now I want to implement connection between these 2 Spinners. When select an item in spinner 1 then spinner 2 should load the content according to the spinner 1 selection.
This is what happens now,
Spinner 1 loads
1, 2, 3, 4
Spinner 2 loads
1.1, 1.2, 2.1, 2.2, 3.1, 4.1, 4.2
But what I want to happen is,
1st stage
Spinner 1 loads
1, 2, 3, 4
Spinner 2 loads
Nothing
2nd stage
user selecting number 1 in spinner 1 then spinner 2 should load only 1.1, 1.2.
Current Code
#Override
public void onTaskCompleted(JSONArray responseJson) {
try {
List<String> crust = new ArrayList<String>();
List<String> description = new ArrayList<String>();
List<String> extraDescription = new ArrayList<String>();
for (int i = 0; i < responseJson.length(); ++i) {
JSONObject object = responseJson.getJSONObject(i);
if ((object.getString("MainCategoryID")).equals("1")
&& (object.getString("SubCategoryID")).equals("1")) {
JSONArray subMenuArray = object
.getJSONArray("SubMenuEntity");
for (int j = 0; j < subMenuArray.length(); ++j) {
JSONObject subMenuObject = subMenuArray
.getJSONObject(j);
Log.i("Crust", subMenuObject.getString("Crust"));
crust.add(subMenuObject.getString("Crust"));
Log.i("Description",
subMenuObject.getString("Description"));
description.add(subMenuObject.getString("Description"));
}
}
crustSP = (Spinner) findViewById(R.id.sp_crust);
ArrayAdapter<String> dataAdapterCru = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, crust);
dataAdapterCru
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
crustSP.setAdapter(dataAdapterCru);
sizeSP = (Spinner) findViewById(R.id.sp_pizza_size);
ArrayAdapter<String> dataAdapterDes = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, description);
dataAdapterDes
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sizeSP.setAdapter(dataAdapterDes);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
what should I do to achieve this? Any help will be appreciated.
Latest code
ArrayAdapter<String> dataAdapterCru = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, crust);
crust = Utils.removeDuplicatesFromList(crust);
dataAdapterCru
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
crustSP.setAdapter(dataAdapterCru);
crustSP.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onNothingSelected(AdapterView<?> arg0) {
}
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
String crustSelectedItem = crustSP.getSelectedItem()
.toString();
getFilteredDescriptions(crustSelectedItem, description);
}
});
then sending selected crust value
List<String> getFilteredDescriptions(String crustSelectedItem,
List<String> description) {
List<String> resultDescription = new ArrayList<String>();
crustSelectedItem = crustSP.getSelectedItem().toString();
if (description == null || description.isEmpty())
return resultDescription;
for (int i = 0; i < description.size(); i++) {
description = Utils.removeDuplicatesFromList(description);
if (!description.get(i).contains(crustSelectedItem))
continue;
resultDescription.add(description.get(i));
}
return resultDescription;
}
Now resultDescription has selected crust, respective description values.
this is the place I'm receiving the resultDescription
sizeSP.setOnItemSelectedListener(new MyOnItemSelectedListener());
ArrayAdapter<String> dataAdapterDes = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item,
resultDescription); //resultDescription cannot be resolved to a variable
dataAdapterDes
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sizeSP.setAdapter(dataAdapterDes);
sizeSP.setAdapter(new NothingSelectedSpinnerAdapter(
dataAdapterDes,
R.layout.contact_spinner_row_nothing_selected, this));
To make the relationship between two spinners ;), follow below steps
1) Have the data in the two lists respectively for Spinner1 and Spinner2.
2) Load first list data into Spinner1.
3) Apply onItemSelectedListener listener on Spinner.
4) When user selects item your onItemSelected listener
would be called. you will get the selected position and selected item.
5) Have a method which can filter out data from list2 based on selected item you got in point 4)
6) Set list data which you got in point 4 to Spinner2.
And you have made the relationship.
Edit for point 5 I have written below method. pass selected Crust/Value in this method and this will return you Size/Description list for your Spinner2.
List<String> getFilteredDescriptions(String crust,List<String> descs){
List<String> result = new ArrayList<String>();
if(descs == null || descs.isEmpty())
return result;
for (int i = 0; i < descs.size(); i++) {
if(!descs.get(i).contains(crust)) //ignore all descriptions which doesnt have same Crust
continue;
result.add(descs.get(i)); // Change
}
return result;
}
Here is the example
I have to Spinner , one is for to select the department another one is select the executive engineer, when particular department will selected then their associated executive engineers name will be filled on second spinner.
case_list_selection.xml layout
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
android:orientation="vertical"
android:weightSum="4" >
<LinearLayout
android:id="#+id/llDept"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_margin="10dp"
android:layout_weight="1"
android:background="#fff"
android:orientation="horizontal"
android:weightSum="2" >
<TextView
android:id="#+id/tvDept"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:text="Department :"
android:textColor="#000"
android:textSize="20sp" />
<Spinner
android:id="#+id/spinnerDept"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/tvDept"
android:layout_weight="1"
android:prompt="#string/dept_prompt"
android:layout_gravity="center_vertical"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/llEE"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_below="#+id/llDept"
android:layout_margin="10dp"
android:layout_weight="1"
android:background="#fff"
android:orientation="horizontal"
android:weightSum="2" >
<TextView
android:id="#+id/tvExecutiveEngineer"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_below="#+id/tvDept"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:text="Executive Engineer :"
android:textColor="#000"
android:textSize="20sp" />
<Spinner
android:id="#+id/spinnerExecutiveEngineer"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_below="#+id/tvDept"
android:layout_toRightOf="#+id/tvExecutiveEngineer"
android:layout_weight="1"
android:prompt="#string/exec_prompt"
android:layout_gravity="center_vertical"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/llFromDate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="2"
android:layout_margin="10dp"
>
<Button
android:id="#+id/btnFromDate"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text=" From Date "
android:textColor="#000000"
android:textSize="17sp"
android:background="#drawable/bg"
android:textStyle="bold"
/>
<EditText
android:id="#+id/txtFromDate"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint=" From Date "
android:textColor="#000000"
android:textSize="17sp"
android:gravity="center"
android:enabled="false"
android:focusable="false"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/llToDate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:weightSum="2"
android:layout_margin="10dp"
>
<Button
android:id="#+id/btnToDate"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text=" To Date "
android:textColor="#000000"
android:textSize="17sp"
android:background="#drawable/bg"
android:textStyle="bold"
/>
<EditText
android:id="#+id/txtToDate"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/btnToDate"
android:layout_weight="1"
android:hint=" To Date "
android:textColor="#000000"
android:textSize="17sp"
android:gravity="center"
android:enabled="false"
android:focusable="false"
/>
</LinearLayout>
<RelativeLayout
android:id="#+id/llBtn"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_margin="10dp"
android:layout_weight="2"
android:background="#fff"
>
<Button
android:id="#+id/btnSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00728f"
android:drawableRight="#drawable/search"
android:layout_centerInParent="true"
android:padding="5dp"
android:text=" Search "
android:textColor="#FFF"
android:textSize="18sp" />
</RelativeLayout>
</LinearLayout>
CaseListSelection.java class
package com.smartcity;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.city.data.ExceutiveNamesCollection;
import com.city.webservices.Department_Webservice;
import com.city.webservices.GetExecutive_Webservices;
import com.smartcity.R;
public class CaseListSelection extends Activity{
Context context;
Spinner spinnerDept,spinnerExecutiveEngineer;
ArrayList<ExceutiveNamesCollection> listEE,listExcecutiveNames;
String executiveNames[];
ArrayAdapter<String> dataAdapter;
String selectedDept, selectedEE,selectedDeptId,selectedEEId;
Button btnSearch;
SimpleDateFormat fmtDateAndTime =new SimpleDateFormat("yyyy-MM-dd");
EditText txtFromDate,txtToDate;
Calendar myCalendar;
String fromdate,todate;
public static int posDept,posEE;
int pos;
public String TAG ="CaseListSelection";
#Override
protected void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.case_list_selection);
context=this;
spinnerDept = (Spinner) findViewById(R.id.spinnerDept);
new Department_Webservice(context,dataAdapter,spinnerDept).execute();
btnSearch = (Button) findViewById(R.id.btnSearch);
spinnerExecutiveEngineer = (Spinner) findViewById(R.id.spinnerExecutiveEngineer);
spinnerDept.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onNothingSelected(AdapterView<?> arg0) { }
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
selectedDept = spinnerDept.getSelectedItem().toString();
selectedDeptId = Department_Webservice.deptId[position];
//Toast.makeText(context, "Selected selectedDeptId : "+selectedDeptId, 2).show();
posDept = position;
new GetExecutive_Webservices(context,selectedDeptId,dataAdapter,spinnerExecutiveEngineer).execute();
}
});
spinnerExecutiveEngineer.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onNothingSelected(AdapterView<?> arg0) { }
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
selectedEE = spinnerExecutiveEngineer.getSelectedItem().toString();
selectedEEId = GetExecutive_Webservices.exceutiveIds[position];
//Toast.makeText(context, "Selected EE : "+selectedEE, 2).show();
pos = position;
posEE = position;
}
});
Log.v("selectedDeptId", "<<<<<<<<<<<"+selectedDeptId);
btnSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
fromdate = txtFromDate.getText().toString();
todate = txtToDate.getText().toString();
Log.v(TAG, "selectedDeptId="+selectedDeptId);
Log.v(TAG, "selectedEEId="+selectedEEId);
Log.v(TAG, "fromdate="+fromdate);
Log.v(TAG, "todate="+todate);
Intent i = new Intent(context, CaseList.class);
i.putExtra("DeptId", selectedDeptId);
i.putExtra("Executive_Id", selectedEEId);
i.putExtra("position", pos);
// i.putExtra("Dept", selectedDept);
// i.putExtra("EE", selectedEE);
i.putExtra("FromDate", fromdate);
i.putExtra("ToDate", todate);
startActivity(i);
}
});
myCalendar = Calendar.getInstance();
txtFromDate = (EditText) findViewById(R.id.txtFromDate);
txtToDate = (EditText)findViewById(R.id.txtToDate);
Button btnFromDate = (Button) findViewById(R.id.btnFromDate);
btnFromDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new DatePickerDialog(context, d, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
Button btnToDate = (Button) findViewById(R.id.btnToDate);
btnToDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new DatePickerDialog(context, todateListener, myCalendar
.get(Calendar.YEAR), myCalendar
.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
}catch(Exception e)
{
e.printStackTrace();
}
}
DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateFromDate();
}
};
DatePickerDialog.OnDateSetListener todateListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateToDate();
}
};
private void updateFromDate() {
txtFromDate.setText(fmtDateAndTime.format(myCalendar.getTime()));
}
private void updateToDate() {
txtToDate.setText(fmtDateAndTime.format(myCalendar.getTime()));
if (txtFromDate.getText().toString()!=null || txtToDate.getText().toString()!=null)
{
try {
fromdate = txtFromDate.getText().toString();
todate = txtToDate.getText().toString();
Date dateFrom = fmtDateAndTime.parse(fromdate);
Date dateTo = fmtDateAndTime.parse(todate);
if (dateTo.before(dateFrom))
{
Toast.makeText(context, "To Date should be greater than From date!", 2).show();
txtToDate.setText("Invalid date");
}
else
{
txtToDate.setText(fmtDateAndTime.format(myCalendar.getTime()));
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
Toast.makeText(context, "Please select the valid date!", 2).show();
}
}
}
Department_Webservice.java asynk class to fill department list
package com.city.webservices;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.city.data.DeptBean;
import com.city.data.HttpUrl;
import com.smartcity.CityApplication;
public class Department_Webservice extends AsyncTask<Void, Void, Void>
{
Context contxt;
InputStream is;
ProgressDialog pDialog;
DeptBean beanlist;
ArrayList<DeptBean>listDept;
public String TAG = "Department_Webservice";
HttpResponse response;
String str = "";
ArrayAdapter<String> dataAdapter;
public static String deptNames[],deptId[];
Spinner spinnerDept;
public Department_Webservice(Context ctx,ArrayAdapter<String> dataAdapter,Spinner spinnerDept) {
this.contxt = ctx;
this.dataAdapter = dataAdapter;
this.spinnerDept = spinnerDept;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(contxt);
pDialog.setIndeterminate(false);
pDialog.setMessage("Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try
{
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost(HttpUrl.get_department);
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
try {
if(response.toString()!=null){
JSONArray jarray = new JSONArray(str);
listDept = new ArrayList<DeptBean>();
for(int i = 0; i<jarray.length();i++)
{
JSONObject jobj = jarray.getJSONObject(i);
beanlist = new DeptBean();
beanlist.setDeptId(jobj.getString("jobid"));
beanlist.setDeptName(jobj.getString("role"));
listDept.add(beanlist);
}
Log.v(TAG, "listDept size>>>>>>>>>> " + listDept.size());
}
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
if(response.toString()!=null)
{
CityApplication.setDeptBeanlist(listDept);
deptNames = new String[listDept.size()];
deptId = new String[listDept.size()];
for (int i=0; i<listDept.size(); i++)
{
deptNames[i] = listDept.get(i).getDeptName();
deptId[i] = listDept.get(i).getDeptId();
}
dataAdapter = new ArrayAdapter<String>(contxt,
android.R.layout.simple_spinner_item, deptNames);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDept.setAdapter(dataAdapter);
}
else
{
new AlertDialog.Builder(contxt).setTitle("Message").setMessage("Server is not responding." ).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}
}
}
GetExecutive_Webservices.java asynk class to fill the associated list of executive names
package com.city.webservices;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.city.data.ExecutiveBean;
import com.city.data.HttpUrl;
public class GetExecutive_Webservices extends AsyncTask<Void, Void, Void> {
Context contxt;
InputStream is;
ProgressDialog pDialog;
String deptId;
public static ArrayList<ExecutiveBean> alist;
public String TAG = "GetExecutive_Webservices";
ArrayAdapter<String> dataAdapter;
Spinner spinnerExecutive;
public static String exceutiveNames[],exceutiveIds[];
String str = "";
HttpResponse response;
public GetExecutive_Webservices(Context ctx, String deptId,
ArrayAdapter<String> dataAdapter, Spinner spinnerExecutive) {
this.contxt = ctx;
this.deptId = deptId;
this.dataAdapter = dataAdapter;
this.spinnerExecutive = spinnerExecutive;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(contxt);
pDialog.setIndeterminate(false);
pDialog.setMessage("Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("department_id", deptId));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(HttpUrl.get_executive);
httpPost.setEntity(new UrlEncodedFormEntity(params1));
Log.v(TAG, "params1" + params1);
response = httpClient.execute(httpPost);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
Log.v(TAG, "str>>>>>>>>>>>>>>>" + str);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (response.toString() != null) {
alist = new ArrayList<ExecutiveBean>();
JSONArray jaray = new JSONArray(str);
for (int i = 0; i < jaray.length(); i++) {
JSONObject jobj = jaray.getJSONObject(i);
ExecutiveBean bean = new ExecutiveBean();
bean.setExecutiveId(jobj.getString("id"));
bean.setExecutiveName(jobj.getString("username"));
alist.add(bean);
Log.v(TAG, "Username>>>>>>>>>>" + jobj.getString("username"));
}
Log.v(TAG, "executive list size>>>>>>>>>>" + alist.size());
}
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
try {
pDialog.dismiss();
if (response.toString() != null) {
exceutiveNames = new String[alist.size()];
exceutiveIds = new String[alist.size()];
for (int i=0; i<alist.size(); i++)
{
exceutiveNames[i] = alist.get(i).getExecutiveName();
exceutiveIds[i] = alist.get(i).getExecutiveId();
}
dataAdapter = new ArrayAdapter<String>(contxt,
android.R.layout.simple_spinner_item, exceutiveNames);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerExecutive.setAdapter(dataAdapter);
} else {
new AlertDialog.Builder(contxt)
.setTitle("Message")
.setMessage("Server is not responding.")
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
}).create().show();
}
} catch (Exception e) {
Log.e("JSON Parser", "onPostExecute" + e.toString());
}
}
}
Here is HttpUrl.get_department & HttpUrl.get_executive is the url of the method of webservices
DeptBean & ExecutiveBean is the Getter Setter
Hope this post will help you

User Authentication using AsyncTask

I'm trying to create simple login form. Following URL returns "true" if the user credentials are validated and "false" otherwise. Simple string is returned.
http:/........../login.php?user=rashid&pass=rashid
The program crashes when I press login button. This is being shown on LogCat:-
FATAL EXCEPTION: main - java.lang.NullPointerException at
com.example.logintry.MainActivity$VerifyLogin.onPostExecution
Here's activit_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp"
>
<EditText
android:id="#+id/etUser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="User Name"
android:text="rashid"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Password"
android:text="rashid123"
android:inputType="textPassword" />
<Button
android:id="#+id/bLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login" />
</LinearLayout>
Here's MainActivity.java
For security reasons I've not added actual IP.
package com.example.logintry;
import java.io.IOException;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnClickListener {
private EditText etUser, etPassword;
private Button bLogin;
private String u, p;
private final String KEY_LOGIN_URL = "http://.............../login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUser = (EditText) findViewById(R.id.etUser);
etPassword = (EditText) findViewById(R.id.etPassword);
bLogin = (Button) findViewById(R.id.bLogin);
bLogin.setOnClickListener(this);
}
#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 void onClick(View v) {
// TODO Auto-generated method stub
u = etUser.getText().toString();
p = etPassword.getText().toString();
VerifyLogin runner = new VerifyLogin();
runner.execute();
}
private class VerifyLogin extends AsyncTask<URL, Void, Void> {
String msg = "";
HttpClient httpClient;
HttpGet httpGet;
HttpResponse response;
HttpEntity entity;
#Override
protected Void doInBackground(URL... urls) {
// TODO Auto-generated method stub
try {
httpClient = new DefaultHttpClient();
httpGet = new HttpGet(KEY_LOGIN_URL + "?user=" + u + "&pass=" + p);
response = httpClient.execute(httpGet);
entity = response.getEntity();
msg = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result.equals("true")) {
Toast.makeText(getApplicationContext(), "Valid password",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Invalid Password",
Toast.LENGTH_LONG).show();
}
}
}
}
result is of type Void, which is always null, so result.equals("true") will throw the NPE.
You need to change your VerifyLogin class to extends AsyncTask<URL, Void, String>, and make doInBackground return "true" or "false" as your postExecution method is expecting.

How to solve empty costume list view issue?

I have written a code to get all the videos related to a specific user in YouTube as follows:
import java.util.ArrayList;
import java.util.Collection;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.example.tstnetconnwithjson.tables.custome;
import com.example.tstnetconnwithjson.tables.videos;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
Button search; ;
TextView name ;
ListView listview ;
ArrayList<videos > videolist;
ArrayAdapter< videos > adapter ;
AlertDialog.Builder alert ;
ProgressDialog progressdialog ;
EditText name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videolist = new ArrayList<videos>();
adapter = new ArrayAdapter<videos>(this, android.R.layout.simple_list_item_1 , android.R.id.text1,videolist);
name=(EditText) findViewById(R.id.editText1);
alert = new Builder(this);
alert.setTitle("Warnning" ) ;
alert.setMessage("You want to connect to the internet ..? " );
alert.setNegativeButton("No ", null);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
String username=name.getText().toString();
new connection().execute("https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc");
}
});
progressdialog = new ProgressDialog(this);
progressdialog.setMessage("Wait Loading .... ");
progressdialog.setCancelable(false);
search = (Button) findViewById(R.id.button1);
name = (TextView) findViewById(R.id.textView1);
listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
search.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
alert.show();
}
});
}
class connection extends AsyncTask<String, Integer, String>{
#Override
protected void onPreExecute() {
progressdialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
String s = GetUrlBody(arg0[0]);
return s;
}
#Override
protected void onPostExecute(String result) {
try{
JSONObject jo =(JSONObject) new JSONTokener(result).nextValue();
JSONObject feed = jo.optJSONObject("data");
JSONArray entry = feed.optJSONArray("items");
for(int i = 0 ; i<entry.length() ; i++){
String title = entry.getJSONObject(i).getString("title");
String thumbURL = entry.getJSONObject(i).getJSONObject("thumbnail").getString("sqDefault");
Log.d("after get image", "ok")
String url;
try {
url = entry.getJSONObject(i).getJSONObject("player").getString("mobile");
} catch (JSONException ignore) {
url = entry.getJSONObject(i).getJSONObject("player").getString("default");
}
String description = entry.getJSONObject(i).getString("description");
Log.d("after get description", "ok");
videos videoobject=new videos();
videoobject.setDecscrption(description);
videoobject.setImageurl(thumbURL);
videoobject.setVediourl(url);
videoobject.setVideoname(title);
videolist.add(videoobject);
}
listview.setAdapter(new custome(MainActivity.this,videolist));
Log.d("AFTER set custome ", "before notify changes");
adapter.notifyDataSetChanged();
}catch(Exception exception) {
Log.d("exception ", "nock nock nock....");
Log.e("json ", exception.getMessage());
}
progressdialog.dismiss();
super.onPostExecute(result);
}
String GetUrlBody (String Url ){
HttpClient client = new DefaultHttpClient();
HttpGet gethttp = new HttpGet(Url);
try{
HttpResponse response = client.execute(gethttp);
if(response.getStatusLine().getStatusCode() == 200){
String save =
EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
return save;
}else {
return "Not Found";
}
}catch(Exception exception){}
return null;
}
}
}
Where the custome class is extends from base adapter in order to have list view with image view set to video image and text view set to video title.
In log cat messages the result are existed but my list view returns empty.
Can any one tell me why?
here is the code for costume list view:
public class custome extends BaseAdapter {
ArrayList<videos> data=new ArrayList<videos>();
android.content.Context context1;
android.widget.TextView name;
ImageView picture;
public custome(Context context,ArrayList<videos>arrayList) {
// TODO Auto-generated constructor stub
context=context;
arrayList=data;
}
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return data.get(arg0);
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
public View getView(int arg0, View arg1, ViewGroup arg2) {
View view=arg1;
if(view==null)
{
LayoutInflater layoutInflater=(LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=layoutInflater.inflate(R.layout.listvideo,null);
}
name=(TextView) view.findViewById(R.id.textView1);
picture=(ImageView) view.findViewById(R.id.imageView1);
videos video = data.get(arg0);
name.setText(video.getVideoname());
URL url = null;
try {
url = new URL(video.getImageurl());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
picture.setImageBitmap(bitmap);
return view;
}
}
The problem is in your assigning code of custome constructor:
Use this constructor:
public custome(Context context,ArrayList<videos> arrayList) {
context=context;
//arrayList=data;<<< WRONG
data=arrayList;//<<<<<<< Correct way of assigning
}
You are overriding your adapter here:
listview.setAdapter(new custome(MainActivity.this,videolist));
Remove this line

Categories

Resources