how to use Layout to display the result get from XML - android

I am A new guy in Android. I try to develop a list that can show the song name and author at the same line. The source data is from a online XML file
The following is the code I try to use in my program.
However, I only be able to display the author name in the list.
I would to ask how I should modify the code so that I can show the song name and author at the same line in the list?
The Format of online XML file I try to read
<recipes>
<song>
<id>1</id>
<title>Sing A Song</title>
<songs_author>ACM</songs_author>
</song>
<song>
<id>2</id>
<title>DO Re Me</title>
<songs_author>BBC/songs_author>
</song>
</recepies>
src/com.mobile/SongsActivity
package com.mobile;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class SongsActivity extends Activity implements OnItemClickListener {
protected static final int DIALOG_KEY = 0;
ListView mListView;
Button mClear;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
this.setProgressBarIndeterminateVisibility(false);
setContentView(R.layout.Songs);
mListView = (ListView) findViewById(R.id.listView1);
mListView.setTextFilterEnabled(true);
mListView.setOnItemClickListener(this);
LoadRecipesTask1 mLoadRecipesTask = new LoadRecipesTask1();
mLoadRecipesTask.execute("http://123.com/mobile/Songs_list.php");
mClear = (Button) findViewById(R.id.button3);
mClear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mListView.setAdapter(null);
}
});
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Datum datum = (Datum) mListView.getItemAtPosition(position);
Uri uri = Uri.parse("http://123.com/mobile/Songs.php?Songsid=" + datum.getId());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
this.startActivity(intent);
}
public static ArrayList<Datum> parse(String url) throws IOException, XmlPullParserException {
final ArrayList<Datum> results = new ArrayList<Datum>();
URL input = new URL(url);
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(input.openStream(), null);
int eventType = xpp.getEventType();
String currentTag = null;
Integer id = null;
String title = null;
String Songs_author = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
currentTag = xpp.getName();
} else if (eventType == XmlPullParser.TEXT) {
if ("id".equals(currentTag)) {
id = Integer.valueOf(xpp.getText());
}
if ("title".equals(currentTag)) {
title = xpp.getText();
}
if ("Songs_author".equals(currentTag)) {
Songs_author = xpp.getText();
}
} else if (eventType == XmlPullParser.END_TAG) {
if ("song".equals(xpp.getName())) {
results.add(new Datum(id, title, Songs_author));
}
}
eventType = xpp.next();
}
return results;
}
protected class LoadRecipesTask1 extends AsyncTask<String, Void, ArrayList<Datum>> {
#Override
protected void onPreExecute() {
SongsActivity.this.setProgressBarIndeterminateVisibility(true);
}
#Override
protected ArrayList<Datum> doInBackground(String... urls) {
ArrayList<Datum> datumList = new ArrayList<Datum>();
try {
datumList = parse(urls[0]);
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return datumList;
}
#Override
protected void onPostExecute(ArrayList<Datum> result) {
mListView.setAdapter(new ArrayAdapter<Datum>(SongsActivity.this, R.layout.list_item, result));
//SongsActivity.this.setProgressBarIndeterminateVisibility(false);
}
}
}
src/com.mobile/Datum
package com.mobile;
public class Datum {
int id;
String title;
String songs_author;
public Datum(int id, String title, String songs_author) {
this.id = id;
this.title = title;
this.songs_author= songs_author;
}
public String toString() {
return songs_author;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String get Songs_author() {
return Songs_author;
}
}
res/layout/songs.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button android:text="Refresh 1" android:id="#+id/button1"
android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"></Button>
<Button android:text="Clear" android:id="#+id/button3"
android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"></Button>
</LinearLayout>
<ListView android:id="#+id/listView1" android:layout_height="fill_parent"
android:layout_width="fill_parent"></ListView>
</LinearLayout>
res/layout/list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" >
</TextView>

Just make Custom List View using array adapter.
refer this example..
http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/

The web is full of tutorial and example of ListView using Custom Adapter. You will have to spend some time trying to learn them. No shortcuts. You can one of them here or you can select one of the books from Amazon.

Related

Radio button get only checked radio in android studio

I currently working with a project and stuck on the radio button which getting only the checked radio in xml, I search many case regarding with this concern and still got the same problem.
here is the activity which toasting only the checked radio in xml
package com.example.kapoyei.hatidtubiganapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.kapoyei.hatidtubiganapp.helper.Http;
import com.example.kapoyei.hatidtubiganapp.helper.Network;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
public class ClientActivity extends Activity implements View.OnClickListener {
public static String jsonObject;
SharedPreferences sharedPref;
Intent i;
Button btnLogout, btnBreakPoint;
Spinner spnStation;
ImageView btnReserve, btnStationList, btnPending, btnHistory;
TextView txtSelectDate;
EditText no_container;
RadioGroup radioGroup;
RadioButton radioButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnReserve = (ImageView) findViewById(R.id.btnReserve);
btnStationList = (ImageView) findViewById(R.id.btnStation);
btnPending = (ImageView) findViewById(R.id.btnPending);
btnHistory = (ImageView) findViewById(R.id.btnHistory);
btnPending.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
i = new Intent(ClientActivity.this, PendingClientOrderActivity.class);
startActivity(i);
}
});
btnStationList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
i = new Intent(ClientActivity.this, StationList.class);
startActivity(i);
}
});
btnReserve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(ClientActivity.this);
LayoutInflater inflater = getLayoutInflater();
view = inflater.inflate(R.layout.layout_dialog_reserve, null);
spnStation = (Spinner) view.findViewById(R.id.spnStation);
txtSelectDate = (TextView) view.findViewById(R.id.txtDate);
no_container = (EditText) view.findViewById(R.id.etContainer);
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
btnBreakPoint = (Button) view.findViewById(R.id.btnBreakPoint);
final Calendar c = Calendar.getInstance();
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
String dateFormat = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.US);
txtSelectDate.setText(sdf.format(c.getTime()));
}
};
txtSelectDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new DatePickerDialog(ClientActivity.this,
date,
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH)).show();
}
});
btnBreakPoint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(no_container.getText().toString().isEmpty() || txtSelectDate.getText().toString().equalsIgnoreCase("-- CLICK TO DATE DELIVER --")) {
Toast.makeText(getApplicationContext(), "All fields require", Toast.LENGTH_SHORT).show();
} else {
/*Bundle bundle = new Bundle();
bundle.putString("station", spnStation.getSelectedItem().toString());
bundle.putString("date", txtSelectDate.getText().toString());
bundle.putString("no_container", no_container.getText().toString());
bundle.putString("type", Integer.toString(radioGroup.getCheckedRadioButtonId()));
i = new Intent(ClientActivity.this, CheckOut.class);
i.putExtras(bundle);
startActivity(i);*/
String typeOrder = radioButton.getText().toString();
Toast.makeText(getApplicationContext(), typeOrder, Toast.LENGTH_LONG).show();
}
}
});
Network network = new Network(getApplicationContext());
if(network.isNetwork()) {
new ClientActivity.GetStationList().execute();
} else {
Toast.makeText(getApplicationContext(), "Coud not get stations", Toast.LENGTH_SHORT).show();
}
builder.setView(view);
builder.setCancelable(true);
AlertDialog dialog = builder.create();
dialog.show();
}
});
btnHistory.setOnClickListener(this);
btnLogout.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.btnLogout) {
finish();
sharedPref = getSharedPreferences("ht", MODE_PRIVATE);
SharedPreferences.Editor modify = sharedPref.edit();
modify.putBoolean("login", false);
modify.putString("id", "");
modify.putString("auth", "");
modify.apply();
i = new Intent(ClientActivity.this, LoginActivity.class);
startActivity(i);
}
if(view.getId() == R.id.btnHistory) {
i = new Intent(ClientActivity.this, HistoryActivity.class);
startActivity(i);
}
}
public class GetStationList extends AsyncTask<Void, Void, String> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ClientActivity.this);
pd.setMessage("Getting station ...");
pd.setCancelable(false);
pd.show();
}
#Override
protected void onPostExecute(String result) {
pd.cancel();
json(result);
}
#Override
protected String doInBackground(Void... voids) {
String data = "";
jsonObject = "";
try {
String link = (String) Http.url + "?type=getstationlist";
URL getURL = new URL(link);
HttpURLConnection httpURLConnection = (HttpURLConnection) getURL.openConnection();
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
InputStream is = (InputStream) httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while((data = reader.readLine()) != null) {
jsonObject += data;
}
Log.i("", jsonObject);
return jsonObject;
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
public void json(String json) {
List<String> collectionName = new ArrayList<>();
if(json != null) {
try {
JSONObject jobj = new JSONObject(json);
JSONArray jarray = jobj.getJSONArray("stationlist");
String name = "";
String id = "";
for(int i = 0; i < jarray.length(); i++) {
JSONObject obj = jarray.getJSONObject(i);
name = obj.getString("name");
collectionName.add(name);
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(getBaseContext(), android.R.layout.simple_list_item_1, collectionName);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnStation.setAdapter(adapter);
} catch(Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Connection problem", Toast.LENGTH_SHORT).show();
}
}
}
}
and here is the xml where located the layout of my radio
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Station"
android:layout_margin="10dp"
android:textSize="20sp"/>
<Spinner
android:id="#+id/spnStation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Date"
android:layout_margin="10dp"
android:textSize="20sp"/>
<TextView
android:id="#+id/txtDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="-- CLICK TO DATE DELIVER --"
android:textSize="15sp"
android:layout_margin="10dp"
android:layout_gravity="center"
android:textAlignment="center"/>
<EditText
android:id="#+id/etContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="No. Of Containers"
android:layout_margin="10dp"/>
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:id="#+id/Gallon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Gallon"
android:checked="true"/>
<RadioButton
android:id="#+id/Litre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Litre" />
</RadioGroup>
<Button
android:id="#+id/btnBreakPoint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_margin="10dp"
android:text="Proceed to Check Out" />
</LinearLayout>
</RelativeLayout>
You can apply the below codes:
int radioid = radioButtonGroup.getCheckedRadioButtonId();
View radio_button= radioButtonGroup.findViewById(radioButtonID);
int index = radioButtonGroup.indexOfChild(radioButton);
If the RadioGroup contains other Views (like a TextView) then the indexOfChild() method will return wrong index.
To get selected RadioButton Text on RadioGroup follow the below code:
RadioButton radio = (RadioButton) radioButtonGroup.getChildAt(index);
String text = radio.getText().toString();
Why this is happened? Because before you click Break Point button, you change the radio button id but not bind it to your variable, your variable still storing the old value. You need to add this code
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
above
String typeOrder = radioButton.getText().toString();
so it will shown
btnBreakPoint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
...
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
String typeOrder = radioButton.getText().toString();
...
}
or you can move the scope of radioGroup assignment to onCreate scope

OnClick() is not working for currency converter.

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
}
}
}

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
}
}
}

The method initLoader(int, Bundle, LoaderManager.LoaderCallbacks<D>) keeps giving me not applicable error

I'm stuck in my code where I'm using drawer layout and on the fragment layout I want to display list of persons after getting it from database. In the fragment class when I query using cursor adapter and set it to list adapter the error says:
The method initLoader(int, Bundle, LoaderManager.LoaderCallbacks) in the type LoaderManager is not applicable for the arguments (int, null, MainFragment).
Where I'm going wrong, please help. If u need more info please ask. Below is my fragment class and its corresponding layout code. Thanks in advance.
Fragment Class:
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.bnkinfotech.corporatedirectory.Directory.Mobile;
import com.bnkinfotech.corporatedirectory.Directory.Telephone;
import android.app.ListFragment;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
//import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.support.v4.content.CursorLoader;
import android.support.v4.widget.CursorAdapter;
public class MainFragment extends ListFragment implements LoaderCallbacks<Cursor> {
String loginPref;
String email;
String updatedDate;
String onlineemail = null;
SharedPreferences prefAccount;
protected Cursor cursor;
protected ListAdapter adapter;
protected SQLiteDatabase db;
public static String ArgAccountNumber = "account_list_number";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
prefAccount = getActivity().getSharedPreferences("CoDiAccount", Context.MODE_PRIVATE);
onlineemail = prefAccount.getString("email", "-1").toLowerCase();
String directoryname = "CoDiApp" + onlineemail;
SharedPreferences prefs = getActivity().getSharedPreferences(directoryname, Context.MODE_PRIVATE);
loginPref = prefs.getString("login", "-1");
email = prefs.getString("email", "-1").toLowerCase();
updatedDate = prefs.getString("lastupdateddate", "-1");
View rootView = inflater.inflate(R.layout.main_fragment, container, false);
return rootView;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
}
#Override
public void onStart() {
super.onStart();
if (loginPref == "1")
{
showContacts();
}
else if (loginPref == "0")
{
//Validate account
Intent verifyAccount = new Intent(getActivity(), VerifyAccountActivity.class);
getActivity().startActivity(verifyAccount);
}
else
{
//Email Login
Intent checkEmail = new Intent(getActivity(), CheckEmailActivity.class);
getActivity().startActivity(checkEmail);
}
}
public int showContacts() {
SharedPreferences prefAccount = getActivity().getSharedPreferences("CoDiAccount", Context.MODE_PRIVATE);
String onlineemail = prefAccount.getString("email", "-1").toLowerCase(Locale.ENGLISH);
String directoryname = "CoDiApp" + onlineemail;
SharedPreferences prefs = getActivity().getSharedPreferences(directoryname, Context.MODE_PRIVATE);
String loadxml = prefs.getString("loadxml", "-1");
String groupBy = prefs.getString("groupby", "0");
if (loadxml == "-1")
{
LoadXMLFile();
Editor prefEditor = prefs.edit();
prefEditor.putString("loadxml", "1");
String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
prefEditor.putString("lastupdateddate", timeStamp.toString());
prefEditor.commit();
}
String[] uiBindFrom = { SQLiteDB.FIRST_NAME, SQLiteDB.LAST_NAME };
int[] uiBindTo = { R.id.firstName, R.id.lastName };
getLoaderManager().initLoader(0, null, this);
adapter = new SimpleCursorAdapter(
getActivity().getApplicationContext(), R.layout.main_fragment,
null, uiBindFrom, uiBindTo,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setListAdapter(adapter);
return 1;
}
public void LoadXMLFile() {
String response = "";
RequestManager rm = new RequestManager();
String x = "";
ArrayList<Mobile> arrMob;
ArrayList<Telephone> arrTel;
try
{
if(isValidEmail(email))
{
String url = String.format("GetDirectory/{0}", email);
response = rm.GetResponse(url);
try {
// Create your Json Array
JSONArray lList=new JSONArray(response);
// Iterate the json array to get each Json object
for (int i = 0; i < lList.length(); i++) {
JSONObject lObject=lList.getJSONObject(i);
String fName=lObject.getString("FirstName");
String lName=lObject.getString("LastName");
String gName=lObject.getString("GroupName");
JSONArray jsonArr= lObject.getJSONArray("MobileNumbers");
Mobile[] mNumbers=new Mobile[jsonArr.length()];
arrMob = new ArrayList<Mobile>();
for(int j=0;j<jsonArr.length();j++)
{
mNumbers[j]= (Mobile) jsonArr.get(j);
arrMob.add(mNumbers[j]);
}
JSONArray jsonArrTel= lObject.getJSONArray("TelephoneNumbers");
Telephone [] tNumbers=new Telephone[jsonArrTel.length()];
arrTel = new ArrayList<Telephone>();
for(int k=0;k<jsonArrTel.length();k++)
{
tNumbers[k]=(Telephone) jsonArrTel.get(k);
arrTel.add(tNumbers[k]);
}
String hAddress=lObject.getString("HomeAddress");
String oAddress=lObject.getString("OfficeAddress");
//Code to Insert in Sqlite database .....
Directory dir = new Directory();
dir.setFirstName(fName);
dir.setLastName(lName);
dir.setGroupName(gName);
dir.setMobiles(arrMob);
dir.setTelephones(arrTel);
dir.setHomeAddress(hAddress);
dir.setOfficeAddress(oAddress);
DatabaseHandler dbHandler = new DatabaseHandler(getActivity().getApplicationContext());
SQLiteDatabase sqliteDatabase = dbHandler.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHandler.ID, dir.getId());
contentValues.put(DatabaseHandler.FIRST_NAME, dir.getFirstName());
contentValues.put(DatabaseHandler.LAST_NAME, dir.getLastName());
contentValues.put(DatabaseHandler.GROUP_NAME, dir.getGroupName());
contentValues.put(DatabaseHandler.MOBILES, dir.getMobiles().toString());
contentValues.put(DatabaseHandler.TELEPHONES, dir.getTelephones().toString());
contentValues.put(DatabaseHandler.HOME_ADDRESS, dir.getHomeAddress());
contentValues.put(DatabaseHandler.OFFICE_ADDRESS, dir.getOfficeAddress());
sqliteDatabase.insert(DatabaseHandler.TABLE_NAME_MEMBER, null, contentValues);
sqliteDatabase.close();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else
{
String msg = "Sorry, invalid email";
Toast.makeText(getActivity().getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
}
catch (Exception ex)
{
response = ex.getMessage().toString();
}
}
public final static boolean isValidEmail(CharSequence email) {
if (email == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
String[] projection = { SQLiteDB.ID, SQLiteDB.FIRST_NAME, SQLiteDB.LAST_NAME };
CursorLoader cursorLoader = new CursorLoader(getActivity(),
DatabaseAccessUtility.CONTENT_URI, projection, null, null, null);
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
((SimpleCursorAdapter) adapter).swapCursor(arg1);
}
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
((SimpleCursorAdapter) adapter).swapCursor(null);
}
}
MainFragment Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minWidth="25dp"
android:minHeight="25dp"
android:id="#+id/FlyOutContent">
<LinearLayout
android:id="#+id/linlaHeaderProgress"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone">
<ProgressBar
android:id="#+id/pbHeaderProgress"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<RelativeLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="8dp" >
<TextView
android:id="#+id/firstName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="First" />
<TextView
android:id="#+id/lastName"
android:layout_marginLeft="6dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/firstName"
android:text="Last" />
</RelativeLayout>
<LinearLayout
android:orientation="vertical"
android:minWidth="25dp"
android:minHeight="25dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#android:id/empty">
<TextView
android:text="#string/NoFavoritesText"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:id="#+id/textView1"
android:gravity="center"
android:layout_marginLeft="12dip"
android:layout_marginRight="12dip"
android:textColor="#ff5a5a5a"
android:layout_marginTop="80dip" />
</LinearLayout>
</LinearLayout>
Since you are using the support library, use instead:
getActivity().getSupportLoaderManager().initLoader(0, null, this);

Simple xml SAX parser error while retrieve from HTTP

Actually i try to do parse simple XML containing some details using SAX parser and display the result in Spinner. But i con't identify the what is the problem in my problem i mean may be it will be syntax error or my program was not correct. can anyone help me to fix this issues.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="178dp" />
<Button
android:id="#+id/button1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/spinner1"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/spinner1"
android:layout_marginTop="17dp"
android:text="Parse XML using SAX" />
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/title"
style="#style/spinner" />
styles.xml
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="AppTheme" parent="#android:style/android:Theme" />
<style name="spinner">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">fill_parent</item>
<item name="android:textColor">#0000CD</item>
<item name="android:text">15dp</item>
<item name="android:typeface">monospace</item>
<item name="android:maxHeight">35dp</item>
<item name="android:paddingTop">5dp</item>
<item name="android:paddingBottom">8dp</item>
</style>
</resources>
Mainactivity.class
public abstract class MainActivity extends Activity implements OnClickListener,OnItemSelectedListener {
Button button;
Spinner spinner;
List<Item> item = null;
static final String URL = "http://www.androidituts.com/source/tutorials.xml";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById();
button.setOnClickListener(this);
}
private void findViewById() {
// TODO Auto-generated method stub
button = (Button) findViewById(R.id.button1);
spinner = (Spinner) findViewById(R.id.spinner1);
}
public void onClick(View v) {
item = SAXXMLParser.parse(URL);
ArrayAdapter<Item> adapter = new ArrayAdapter<Item>(this,
R.layout.list_item, item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
Item item = (Item) parent.getItemAtPosition(pos);
Toast.makeText(parent.getContext(), item.getDetails(),
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
Item.java
public class Item {
private String name;
private int id;
private String category;
private String published;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setcategory(String category) {
this.category = category;
}
public String getcategory() {
return category;
}
public void setpublished(String published) {
this.published = published;
}
public String getpublished() {
return published;
}
public String getDetails() {
// TODO Auto-generated method stub
String result = id + ": " + name + "\n" + category + "-" + published;
return result;
}
}
SAXXMLParser.java
public class SAXXMLParser {
public static List<Item> parse(String URL) {
List<Item> menu=null;
try {
// create a XMLReader from SAXParser
XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser()
.getXMLReader();
// create a SAXXMLHandler
SAXXMLHandler saxHandler = new SAXXMLHandler();
// store handler in XMLReader
xmlReader.setContentHandler(saxHandler);
// the process starts
xmlReader.parse(URL);
// get the `Employee list`
menu = saxHandler.getmenu();
} catch (Exception ex) {
Log.d("XML", "SAXXMLParser: parse() failed");
}
// return Employee list
return menu;
}
}
SAXXMLHandler.java
public class SAXXMLHandler extends DefaultHandler {
private List<Item> menu;
private String tempVal;
private Item tempEmp;
public SAXXMLHandler() {
menu = new ArrayList<Item>();
}
public List<Item> getmenu() {
return menu;
}
// Event Handlers
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// reset
tempVal = "";
if (qName.equalsIgnoreCase("item")) {
// create a new instance of employee
tempEmp = new Item();
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("item")) {
// add it to the list
menu.add(tempEmp);
} else if (qName.equalsIgnoreCase("id")) {
tempEmp.setId(Integer.parseInt(tempVal));
} else if (qName.equalsIgnoreCase("name")) {
tempEmp.setName(tempVal);
} else if (qName.equalsIgnoreCase("category")) {
tempEmp.setcategory(tempVal);
} else if (qName.equalsIgnoreCase("published")) {
tempEmp.setpublished(tempVal);
}
}
}
Android manifesto.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.xmlspinner"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.xmlspinner.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
logcat detail
http://i.stack.imgur.com/BpNKV.jpg
I have done changes in codes try below codes...
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class XMLParsingDOMExample extends Activity implements AdapterView.OnItemSelectedListener {
ArrayList<String> title;
Button button;
Spinner spinner;
ArrayAdapter<String> from_adapter;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
title = new ArrayList<String>();
button = (Button) findViewById(R.id.button1);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setOnItemSelectedListener(this);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
parse();
from_adapter=new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_spinner_item, title);
from_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(from_adapter);
}
});
}
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
Toast.makeText(parent.getContext(), ""+spinner.getSelectedItem().toString().trim(),
Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
protected void parse() {
// TODO Auto-generated method stub
try {
URL url = new URL(
"http://www.androidituts.com/source/tutorials.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("id");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
NodeList websiteList = fstElmnt.getElementsByTagName("name");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
NodeList websiteList1 = fstElmnt.getElementsByTagName("category");
Element websiteElement1 = (Element) websiteList1.item(0);
websiteList1 = websiteElement1.getChildNodes();
NodeList websiteList2 = fstElmnt.getElementsByTagName("published");
Element websiteElement2 = (Element) websiteList2.item(0);
websiteList2 = websiteElement2.getChildNodes();
title.add(((Node) nameList.item(0)).getNodeValue()+":"+((Node) websiteList.item(0)).getNodeValue() +"\n"+((Node) websiteList1.item(0)).getNodeValue()+"-"+((Node) websiteList2.item(0)).getNodeValue());
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
}
Now you can get all the details in that spinner...
You can't Performing Network Operations ON GUI thread so you have to create a thread to fitch and parse data from URL.
public void onClick(View v) {
new Thread(new Runnable() {
#Override
public void run() {
item = SAXXMLParser.parse(URL);
spinhandler.sendEmptyMessage(0);
}
}).start();
}
Create Handler
private Handler spinhandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if(msg.what == 0) {
ArrayAdapter<Item> adapter = new ArrayAdapter<Item>(MainActivity.this, R.layout.list_item, item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(MainActivity.this);
}
}
};
When try to put data in Item Object the Item object equal null so you have to intialize the object before start access it
if (qName.equalsIgnoreCase("id")) {
tempEmp = new Item();
tempEmp.setId(Integer.parseInt(tempVal));
}

Categories

Resources