how to connect app using json - android

I am trying to connect my app using json but when I run my app it gets crashed. I think the problem is in the following code:
protected void onPostExecute(ArrayList result)
{
if (result == null)
{
Toast.makeText(MainActivity.this, "Failed to download Movies", Toast.LENGTH_LONG).show();
return;
}
JSONObject jsono = null;
// gridView gv = (GridView)findViewById(R.id.main_gridview);
ArrayList<Movie> l = new ArrayList<>();
try
{
jsono = new JSONObject((java.util.Map) result);
JSONArray jarray = jsono.getJSONArray("result");
for (int i = 0; i < jarray.length(); i++)
{
JSONObject object = jarray.getJSONObject(i);
String posterPath = object.getString("poster_path");
String title = object.getString("original_title");
String id = object.getString("id");
Movie m = new Movie(id, title, posterPath);
l.add(m);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
MainAdapter adapter = new MainAdapter(MainActivity.this, result);
}
Someone kindly help me.

jsono = new JSONObject((java.util.Map) result);
Cast ArrayList to Map?
I think that you should read more basic knowledge about casting types in java, Maps, ArrayList and JSON.

Related

How to parse a JSONArray and assign it to different TextViews?

I have a JSONArray and when I try to parse it, an NPE shows and the logcat shows W/System.err: org.json.JSONException: Value at 0 is null. Please help. I have provided my codes below.
JSON Array
[
{
"student_number":"201411870",
"full_name":"Miranda , Andrew Matthew Matera",
"year":"4",
"course":"BSIT"
}
]
Code Snippet
ArrayList<User> userArrayList = new JsonConverter<User>().toArrayList(response, User.class);
JSONArray jsonArray = new JSONArray(userArrayList);
try {
int regStudentNumber = jsonArray.getJSONObject(0).getInt("student_number");
String regFullName = jsonArray.getJSONObject(1).getString("full_name");
int regYear = jsonArray.getJSONObject(2).getInt("year");
String regCourse = jsonArray.getJSONObject(3).getString("course");
tvStudentNumber.setText(String.valueOf(regStudentNumber));
tvFullName.setText(regFullName);
tvYear.setText(String.valueOf(regYear));
tvCourse.setText(regCourse);
} catch (JSONException e) {
e.printStackTrace();
}
Solved it on my own. Sorry for the unclear question.
try {
JSONArray jsonArray = new JSONArray(response);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int regStudentNumber = jsonObject.getInt("student_number");
String regFullName = jsonObject.getString("full_name");
int regYear = jsonObject.getInt("year");
String regCourse = jsonObject.getString("course");
tvStudentNumber.setText(String.valueOf(regStudentNumber));
tvFullName.setText(regFullName);
tvYear.setText(String.valueOf(regYear));
tvCourse.setText(regCourse);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
First of all parse JSON array to object to make clear it is for a particular value then fetch things from it based on need.
To parse json array to object use code
try {
JSONArray jsonArray = new JSONArray(response);
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
}
}
} catch (JSONException e) {
e.printStackTrace();
}

how to parse json object and json array in listview android

I am beginner to android app. I am facing trouble how to parse json object and json array to listview in android. Here is my json output
UPDATED WITH JSON CORRECTION
{status: "ok", listUsers: [{"id":2,"username":"myusername","name":"myname","email":"myemail","password":"mypassword","groupid":1,"type":"mytype"},{"id":3,"username":"myusername","name":"myname","email":"myemail2","password":"mypassword2","groupid":1,"type":"mytype"},{"id":4,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":5,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":6,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":7,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":8,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":9,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":10,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":11,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"1"},{"id":12,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":13,"username":"yuwah","name":"yu","email":"mail#gmail.com","password":"pass1","groupid":1,"type":"type1"},{"id":14,"username":"myusername","name":"myname","email":"myemail2","password":"mypassword2","groupid":1,"type":"mytype"}] }
Can anyone explain me how to do it. I am searching all over the topics but I still can't get it. Thanks.
Here is my code block
public class MainActivity extends ListActivity {
String url = "http://staging.workberryplus.com/mobile/listUsers/1";
ProgressDialog PD;
ArrayList<String> listUsers;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listUsers = new ArrayList<String>();
PD = new ProgressDialog(this);
PD.setMessage("Loading.....");
PD.setCancelable(false);
adapter = new ArrayAdapter(this, R.layout.items, R.id.tv, listUsers);
setListAdapter(adapter);
MakeJsonArrayReq();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
}
private void MakeJsonArrayReq() {
PD.show();
//JsonArrayRequest jr=new JsonArrayRequest(url, listener, errorListener)
final StringRequest jreq = new StringRequest(url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
for (int i = 0; i < response.length(); i++) {
try {
Log.d("Response","->"+response);
JSONObject jo = new JSONObject(response);
JSONArray jarray = jo.getJSONArray("listUsers");
JSONObject jo2 = jarray.getJSONObject(i);
String name = jo2.getString("name");
listUsers.add(name);
} catch (JSONException e) {
e.printStackTrace();
}
}
PD.dismiss();
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
MyApplication.getInstance().addToReqQueue(jreq, "jreq");
}
}
try {
JSONObject jo = new JSONObject(response);
JSONArray jarray =jo.getJSONArray("listUsers");
for (int i = 0; i < jarray.length(); i++){
JSONObject jo2 = jarray.getJSONObject(i);
String name = jo2.getString("name");
listUsers.add(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
Convert your String which is response to Json Object
JSONObject jsonObj = new JSONObject(response);
Then do the following
try {
if (jsonObj != null) {
if (jsonObj.optString("status").equals("ok")) {
JSONArray jsonArray = jsonObj.optJSONArray("listUsers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
if (jsonObject != null) {
//Do work here
}
}
}
}
}catch (Exception e1) {
e1.printStackTrace();
}
try this and make changes accordingly and let me know if it work for you or not
JSONObject jo2 = jarray.getJSONObject(i);
You are iterating over the length of the response (a string). You should iterate over the length of jarray

Get value from db and show it in list view and set click listener on it

I am new to android development and i am doing my Final year project. In my project i want to perform search action . search from database and show it in list view so multiple results could be there . so i want to set click listener on it.but every thing is working but when i tried to click on list view results. Its no working .. please give me some suggestions or any guideline. I have already searched all the posts here related to my problem but its not solved . please
here is my java code and in method SeeProfile OnClick event is set
public class DisplaySearchResults extends ActionBarActivity {
String json_string, json_string2;
JSONObject jsonObject, JsonObject2;
JSONArray jsonArray, jsonArray2;
AdapterSearchElements adapterSearchElements;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_search_results);
listView = (ListView) findViewById(R.id.listviewsearch);
listView.setAdapter(adapterSearchElements);
adapterSearchElements = new AdapterSearchElements(this, R.layout.searchresultcutomrow);
listView.setAdapter(adapterSearchElements);
json_string = getIntent().getExtras().getString("json_data");
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String name, Gender, address;
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
name = JO.getString("name");
Gender = JO.getString("Gender");
address = JO.getString("address");
SearchResultsElements searchResultsElements = new SearchResultsElements(name, Gender, address);
adapterSearchElements.add(searchResultsElements);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void SeeProfile(View view){
json_string2 = getIntent().getExtras().getString("json_data");
Intent i = new Intent(DisplaySearchResults.this, FriendsProfile.class);
i.putExtra("json_data", json_string2);
startActivity(i);
}
}
You can set listview OnItemClickListener. Examples are below:
http://www.vogella.com/tutorials/AndroidListView/article.html
http://www.mkyong.com/android/android-listview-example/
i think you are wrong way to fill up listview.and do googling how to bind adapter.
follow on this way ..
json_string = getIntent().getExtras().getString("json_data");
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String name, Gender, address;
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
name = JO.getString("name");
Gender = JO.getString("Gender");
address = JO.getString("address");
SearchResultsElements searchResultsElements = new SearchResultsElements(name, Gender, address);
adapterSearchElements.add(searchResultsElements);
count++;
}
adapterSearchElements = new AdapterSearchElements(this, R.layout.searchresultcutomrow);
listView.setAdapter(adapterSearchElements);
} catch (JSONException e) {
e.printStackTrace();
}
first add array value in Arraylist then after bind adapter.

How to fetch JSONArray values

In my program, I am able to fetch all my text. But In my JSOn in a JSON Array there is another JSONArray which have image url. I am getting all my URL in JSON Array when I am using
JSONArray attachments = post.getJSONArray("itemimage");
but when loop is finished, I am getting nothing in my response. How can I replace my ImageView with URLs which is store in attatchment. My Code is here
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("items");
GridItem item;
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String title = post.optString("itemname");
item = new GridItem();
item.setTitle(title);
JSONArray attachments = post.getJSONArray("itemimage");
if (null != attachments && attachments.length() > 0) {
JSONObject attachment = attachments.getJSONObject(0);
if (attachment != null)
item.setImage(attachment.getString(""));
}
mGridData.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Um,i am 2 mins late post it out...cuz writing the demo for u.
The parse method you need is below,and you can use framework like Universal Image Loader to load the url to your imageView.
private String parseaaa(String jsonString) {
String imgUrl = "";
try {
JSONObject mJsonObject = new JSONObject(jsonString);
JSONArray mArray = mJsonObject.getJSONArray("items");
for (int i = 0; i < mArray.length(); i++) {
JSONObject object=mArray.getJSONObject(i);
imgUrl+=object.getString("itemimage")+"\n";
Log.i(TAG, imgUrl);
}
} catch (Exception e) {
// TODO: handle exception
}
return imgUrl;
}
BTW,just use JSONArray to load things between [] and JSONObject to load the obj... It's easy to do.
As I can see your JSON you should get JSONException at
JSONObject attachment = attachments.getJSONObject(0);
because your are creating object which is not present there, So I would suggest to simply extract String from your JSONArray and do your setImage stuff..
if (null != attachments && attachments.length() > 0) {
String image= (String) attachments.get(0);
//--- set your image here--//
}

How do I pull the string array from this json object?

I am trying to get a list of available numbers from the following json object, using the class from org.json
{
"response":true,
"state":1,
"data":
{
"CALLERID":"81101099",
"numbers":
[
"21344111","21772917",
"28511113","29274472",
"29843999","29845591",
"30870001","30870089",
"30870090","30870091"
]
}
}
My first steps were, after receiving the json object from the web service:
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
Now, how do I save the string array of numbers?
use:
jsonObj = new JSONObject(response);
jsonData = jsonObj.optJSONObject("data");
JSONArray arrJson = jsonData.getJSONArray("numbers");
String[] arr = new String[arrJson.length()];
for(int i = 0; i < arrJson.length(); i++)
arr[i] = arrJson.getString(i);
you need to use JSONArray to pull data in an array
JSONObject jObj= new JSONObject(your_json_response);
JSONArray array = jObj.getJSONArray("data");
Assuming that you are trying to get it in a javascript block, Try something like this
var arrNumber = jsonData.numbers;
My code is for getting "data":
public void jsonParserArray(String json) {
String [] resultsNumbers = new String[100];
try {
JSONObject jsonObjectGetData = new JSONObject(json);
JSONObject jsonObjectGetNumbers = jsonObjectGetData.optJSONObject("results");
JSONArray jsonArray = jsonObjectGetNumbers.getJSONArray("numbers");
for (int i = 0; i < jsonArray.length(); i++) {
resultsNumbers[i] = jsonArray.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(LOG_TAG, e.toString());
}
}

Categories

Resources