populating listview through a fragment - android

I have a class extending listFragment. I have written code for fetching json response in a method which is called in oncreate of the class. For fetching json in background I have created new inner class which extends asyncTask. I can get the jsonarrays and strings in the json response in the logcat. But when I try to save them in a string array and pass them my custom baseadapter, I get a nullpointer exception.
public class OnlineInfo extends ListFragment {
public static String result;
public String[] Technologies1;
public String[] TechnologyDescription1;
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
downloadjsonresponse();
}
public class Download extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
StringBuilder stringbuilder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet url = new HttpGet(params[0]);
try
{
Log.d("in background", "in background");
HttpResponse response = client.execute(url);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line ;
while((line = reader.readLine()) != null)
{
stringbuilder.append(line);
}
}
catch(ClientProtocolException e)
{
Log.d("error in clientprotocol", "error");
e.printStackTrace();
}
catch(IOException e)
{
Log.d("error in IO", "error");
e.printStackTrace();
}
return stringbuilder.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
OnlineInfo.result = result;
try {
JSONObject jsonobject = new JSONObject(result);
JSONArray raja = jsonobject.getJSONArray("Technologies");
//String raja = jsonobject.getJSONArray("Technologies").getJSONObject(0).getString("desc");
//Log.d("desc:", raja);
for(int i=0; i<raja.length();i++)
{
Technologies1[i] = raja.getJSONObject(i).getString("name");
TechnologyDescription1[i] = raja.getJSONObject(i).getString("desc");
Log.d("technology :", raja.getJSONObject(i).getString("name"));
Log.d("technologydescription :", raja.getJSONObject(i).getString("desc"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("desc:", "error");
}
getListView().setAdapter(new AdapterForOnlineInfo(getActivity(), OnlineInfo.this.Technologies1, OnlineInfo.this.TechnologyDescription1));
}
}
public void downloadjsonresponse()
{
Download jsonresponse = new Download();
jsonresponse.execute("http://www.avantajsoftwares.com/result.json");
}
}
I could get the results in logcat whenever I comment these two lines in for-loop:
Technologies1[i] = raja.getJSONObject(i).getString("name");
TechnologyDescription1[i] = raja.getJSONObject(i).getString("desc");
Don't know what's going wrong. Please somebody provide me some insight....:-(

I think you need to allocate space in your string arrays to hold the new strings.
Just before your for loop, try putting something like this:
Technologies1 = new String[raja.length()];
TechnologyDescription1 = new String[raja.length()];

Related

LIstView Filter From Json Returns First Item Only Everytime

I tried to get help on this post without any luck, I played around with code but still no luck. My list for example is as follows: Blue, Red, Purple from Json remote server.
When I type B.. it returns Blue. OK
When I type X.. it returns no results because no color matched "X". OK
When I type R.. (or RE.. or RED) it returns Blue instead of returning Red.
Conclusion - The code always returns the first item on the list when filtered.
My code:
JSON:
private class JsonReadTask extends AsyncTask<String, Void, String> {
//Pending 01
private ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPreExecute() {
this.dialog.setMessage("Loading Rooms, Please Wait");
this.dialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getActivity(),"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
//Pending 02
if (dialog.isShowing()) {
dialog.dismiss();
}
adapter.notifyDataSetChanged();
try{
ListDrwaer(); //has ConnectionException (when it cannot reach server)
}catch (Exception e){
Toast.makeText(getActivity(), "Please check your connection..", Toast.LENGTH_LONG).show();
}
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { "http://www.website.com/file.php?psortby="+sortby});
}
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("room_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String request_title = jsonChildNode.optString("Title");
String request_members = jsonChildNode.optString("Members");
request_title_replaced = request_title.replace("room_", "");
arrRequest_Title.add(request_title_replaced);
arrRequest_Members.add(request_members);
}
} catch (JSONException e) {
System.out.println("Json Error Rooms" +e.toString());
//Toast.makeText(getApplicationContext(), "No Rooms To Load", Toast.LENGTH_SHORT).show();
}
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
Adapter:
class RoomsAdapter extends ArrayAdapter<String>
{
#Override
public void clear() {
super.clear();
arrRequest_Title.clear();
arrRequest_Members.clear();
}
Context context;
List<String> Request_Title;
List<String> Request_Members;
RoomsAdapter(Context c, List<String> Request_Title, List<String> Request_Members)
{
super(c, R.layout.activity_rooms_single, R.id.textTitle, Request_Title);
this.context=c;
this.Request_Title=Request_Title;
this.Request_Members=Request_Members;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row=convertView;
if(row==null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.activity_rooms_single, parent, false);
}
TextView txtTitle = (TextView) row.findViewById(R.id.textTitle);
TextView txtMembers = (TextView) row.findViewById(R.id.textMembers);
txtTitle.setText(Request_Title.get(position));
txtMembers.setText(Request_Members.get(position));
return row;
}
}
Fragment Class:
public class Fragment_01_Rooms extends Fragment

Android currency converter application

I'm working on a big program for Android and I'm trying to get the currency converter part of the program to work. For full disclosure: I found it from http://firstamong.com/building-android-currency-converter/, and it's a tutorial on how to build a real-time currency converter. I'll post the code in question followed by the logcat. The error that occurs is when I try to convert from one currency to another, the application says it was forced to stop. However, the "Invalid" portion works (the case where both currency fields are the same.) Any help would truly be appreciated:
Code:
public class currency_converter extends Activity {
public int to;
public int from;
public String [] val;
public String s;
public Handler handler;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_currency_converter);
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
Spinner s2 = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.name, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
val = getResources().getStringArray(R.array.value);
s1.setAdapter(adapter);
s2.setAdapter(adapter);
s1.setOnItemSelectedListener(new spinOne(1));
s2.setOnItemSelectedListener(new spinOne(2));
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
TextView t = (TextView) findViewById(R.id.textView4);
if(from == to)
{
Toast.makeText(getApplicationContext(), "Invalid", 4000).show();
}
else
{
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
t.setText(exResult);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
public String getJson(String url)throws ClientProtocolException, IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
private class spinOne implements OnItemSelectedListener
{
int ide;
spinOne(int i)
{
ide =i;
}
public void onItemSelected(AdapterView<?> parent, View view,
int index, long id) {
if(ide == 1)
from = index;
else if(ide == 2)
to = index;
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
class GetResponseData extends AsyncTask<String, String, String> {
private ProgressDialog dialog;
private ArrayList<String> titleList;
private TextView textView;
public GetResponseData(TextView textView) {
this.textView = textView;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(currency_converter.this, "", "Loading",
false);
}
#Override
protected String doInBackground(String... params) {
try {
String s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22" + val[from] + val[to] + "%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
return exResult;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog != null)
dialog.dismiss();
if (result != null) {
textView.setText(result);
}
}
}
}
}
Logcat:
10-30 00:59:48.164 20591-20591/com.example.travelapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:365)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:587)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:511)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:489)
at com.example.travelapplication.currency_converter.getJson(currency_converter.java:93)
at com.example.travelapplication.currency_converter$1.onClick(currency_converter.java:68)
at android.view.View.performClick(View.java:4222)
at android.view.View$PerformClick.run(View.java:17620)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5391)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Try this,,
Your performing a networking operation on its main thread. That why your getting NetworkOnMainThreadException
b.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
TextView t = (TextView) findViewById(R.id.textView4);
if(from == to)
{
Toast.makeText(getApplicationContext(), "Invalid", 4000).show();
}
else
{
GetResponseData abcd = GetResponseData(t);
abcd.execute();
}
}
});
You are getting:
NetworkOnMainThreadException
Issue is that you are calling your function getJson() in your Activity.
Use AsyncTask:
public class ProcessTask extends AsyncTask<Void, Integer, String>{
public ProcessTask() {
// TODO Auto-generated constructor stub
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
//your code of parsing
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url); //your yahooapi url goes here
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
It looks like you have strict mode on in your android manifest. Strict mode will complain when you are doing network calls on you main thread. You can just disable strict mode or a better approach is to put your network call into an async task. The network call in question is
HttpResponse response = client.execute(httpGet);
inside public String getJson(String url)
The async task you need is already there you just need to use it
Change this else statement
else
{
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
t.setText(exResult);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
To this
else {
new GetResponseData().execute("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
}
It will help use this :
public class CurrencyConverter extends Fragment {
public CurrencyConverter() {
}
TextView t;
public int to;
public int from;
public String[] val;
public String s;
String exResult;
public Handler handler;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.currency_converter, container, false);
t= (TextView) rootView.findViewById(R.id.textView4);
Spinner s1 = (Spinner) rootView.findViewById(R.id.spinner1);
Spinner s2 = (Spinner) rootView.findViewById(R.id.spinner2);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this.getActivity(), R.array.name, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);
val = getResources().getStringArray(R.array.value);
s1.setAdapter(adapter);
s2.setAdapter(adapter);
s1.setOnItemSelectedListener(new spinOne(1));
s2.setOnItemSelectedListener(new spinOne(2));
Button b = (Button) rootView.findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View View) {
if (from == to) {
Toast.makeText(getActivity().getApplicationContext(), "Invalid", 4000).show();
} else {
new calculate().execute();
}
}
});
return rootView;
}
public class calculate extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... args) {
try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
exResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return exResult;
}
#Override
protected void onPostExecute(String exResult) {
t.setText(exResult);
}
}
public String getJson(String url)throws IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
public class spinOne implements AdapterView.OnItemSelectedListener
{
int ide;
spinOne(int i)
{
ide =i;
}
public void onItemSelected(AdapterView<?> parent, View view,
int index, long id) {
if(ide == 1)
from = index;
else if(ide == 2)
to = index;
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
}

error type mismatch asynctask in android

I'm trying to retrieve data from mysql using asynctask. But I got this
" Type mismatch: cannot convert from AsyncTask
to String"
Though the return from the asynctask process is already string
Here's my codes
public void tampilkanPenyakit() {
try {
String nama = URLEncoder.encode(username, "utf-8");
urltampil += "?" + "&nama=" + nama;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
xResult = getRequestTampil(urltampil);
try {
parse();
} catch (Exception e) {
e.printStackTrace();
}
}
class ProsesTampil extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
String sret = "";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(params[0]);
try{
HttpResponse response = client.execute(request);
sret = EditPenyakit.request(response);
}catch(Exception ex){
}
return sret;
// TODO Auto-generated method stub
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
public String getRequestTampil(String UrlTampil){
String sret="";
sret= new ProsesTampil().execute(UrlTampil);
return sret;
}
private void parse() throws Exception {
//jObject = new JSONObject(xResult);
jObject = new JSONObject(xResult);
String sret = "";
JSONArray menuitemArray = jObject.getJSONArray("food");
cb_menu1 = (CheckBox) findViewById(R.id.cb_menu1);
cb_menu2 = (CheckBox) findViewById(R.id.cb_menu2);
cb_menu3 = (CheckBox) findViewById(R.id.cb_menu3);
for (int i = 0; i < menuitemArray.length(); i++) {
sret =menuitemArray.getJSONObject(i).getString(
"penyakit").toString();
System.out.println(sret);
if (sret.equals("1")){
cb_menu1.setChecked(true);
}
else if (sret.equals("2")){
cb_menu2.setChecked(true);
}
}
}
Any help would be appreciated. thanks
The AsyncTask execute() method return the Asyntask itself, you cannot convert it to String.
You need to handle the result in the onPostExecute() method.
Other option could be use the AsynTask get method :
sret= new ProsesTampil().execute(UrlTampil).get();
Take in account the doc:
Waits if necessary for the computation to complete, and then retrieves its result.

Android Load JSON and Passing Data to View

Guys
I Am Trying Getting JSONData to ListView
it's Works fine,, but the problem is i Want pass the json data for each row to next view
Here's, My JSON Class
public class GetJSON extends AsyncTask<String, Void, ArrayList<JSONFields>> {
#Override
protected ArrayList<JSONFields> doInBackground(String... params) {
// TODO Auto-generated method stub
try {
String url = params[0];
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response;
response = client.execute(get);
InputStream content = response.getEntity().getContent();
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(content));
String line;
String json = "";
while ((line = reader.readLine()) != null) {
json += line;
}
JSONArray array = new JSONArray(json);
ArrayList<JSONFields> alData = new ArrayList<JSONFields>();
for (int i = 0; i < array.length(); i++) {
obj = array.getJSONObject(i);
data = new JSONFields();
data.setID(obj.getString("id"));
data.setTitle(obj.getString("title"));
data.setImage(obj.getString("image"));
data.setYoutube(obj.getString("youtube"));
data.setLength(obj.getString("length"));
alData.add(data);
}
System.out.println("Data returned sucessfully");
return alData;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<JSONFields> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
CustomAdapter adapter = new CustomAdapter(MainApp.this, result);
listview.setAdapter(adapter);
}
}
and I have Create Class for Holding JSON Data Fields
here it is
public class JSONFields {
private String id;
private String title;
public String getID() {
return id;
}
public void setID(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
but when I pass with this code
String thetitle = data.getTitle();
Intent showView = new Intent(MainApp.this, Show.class);
showView.putExtra("title", thetitle);
startActivity(showView);
I get only the last row info..
that's my problem
I want if I clicked the row 5 see the attr of row 5 in show View
I am new to Java and android
and I think I should add the position to getTitle(position)
when getting< because in iOS dev, I pass the data of array objectAtIndex:int to NSDic
that's all
but here< I don't know
Thanks in advance
You can use onItemClickListener to get the position of clicked view,
And than you can get the same object from the list or from array which you have set to adapter.

Parsing multiple JSON strings

I would like to thank all the users in this community for helping me get as far as I am in my project today.
I now need your help once again. So far, I am able to establish a connection in my project from this JSON link (REMOVED FOR PRIVACY CONCERNS)
The problem is I am only able to parse one string, (firstName)
Here is my code:
public class JSONActivity extends Activity {
static TextView http;
HttpClient client;
JSONObject json;
final static String URL = "REMOVED FOR PRIVACY CONCERNS
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
http = (TextView) findViewById(R.id.http);
client = new DefaultHttpClient();
new Read().execute("firstName");
}
public JSONObject getpw(String password) throws ClientProtocolException,
IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
url.append(password);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONObject getname = new JSONObject(data);
return getname;
} else {
Toast.makeText(JSONActivity.this, "error", Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
json = getpw("trustme");
return json.getString("firstName");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
http.setText(result);
}
}
}
My question is, how can I parse multiple strings rather than just "firstName"?
You can get it all by doing the following:
String firstname = json.getString("firstName");
String lastname = json.getString("lastName");
int checkedIn = json.getInt("checkedIn");
int updated = json.getInt("checkedindatetime");
JSONObject address = json.getJSONObject("address");
String streetaddress = address.getString("streetAddress");
String city = address.getString("city");
etc...
JSONArray phoneNumbers = json.getJSONArray("phoneNumber");
String type = phoneNumbers.getJSONObject(0).getString("type");
etc...
Hope this helps.
A good resource for looking at json, is this validator.

Categories

Resources