Reputation: 31
I want to retrieve my all data from database but there is a compilation error and I am new with android. This is my class in which I want to get all users from table and show there name in listview. If there is no name in then username will be the name. Error that I am getting is Frame not available.
package com.gmakerorganisation.glocator.Fragments;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.android.volley.RequestQueue;
import com.gmakerorganisation.glocator.Config;
import com.gmakerorganisation.glocator.GetAllUsers;
import com.gmakerorganisation.glocator.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class Sendrequest extends Fragment {
private RequestQueue requestQueue;
ArrayList<HashMap<String, String>> UserList;
private static final String TAG_ID = "id";
private static final String TAG_USERNAME = "username";
private static final String TAG_NAME = "name";
private static final String TAG_PHONE = "phone";
private static final String TAG_PROFILE = "profile";
ListView listView;
public Sendrequest() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v=inflater.inflate(R.layout.fragment_sendrequest, container, false);
listView=(ListView)v.findViewById(R.id.list);
new GetStudents().execute();
return v;
}
private class GetStudents extends AsyncTask<Void, Void, Void> {
// Hashmap for ListView
ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
GetAllUsers webreq = new GetAllUsers();
// Making a request to url and getting response
String jsonStr = webreq.makeWebServiceCall(Config.USERS_URL, GetAllUsers.GET);
Log.d("Response: ", "> " + jsonStr);
UserList = ParseJSON(jsonStr);
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
/**
* Updating parsed JSON data into ListView
li * */
ListAdapter adapter = new SimpleAdapter(
getActivity().getApplicationContext(), UserList,
R.layout.list_item, new String[]{TAG_NAME, TAG_PHONE}, new int[]{R.id.name,
R.id.mobile});
listView.setAdapter(adapter);
}
}
private ArrayList<HashMap<String, String>> ParseJSON(String json) {
if (json != null) {
try {
// Hashmap for ListView
ArrayList<HashMap<String, String>> studentList = new ArrayList<HashMap<String, String>>();
JSONObject jsonObj = new JSONObject(json);
// Getting JSON Array node
JSONArray userrs = jsonObj.getJSONArray(null);
// looping through All Students
for (int i = 0; i < userrs.length(); i++) {
JSONObject c = userrs.getJSONObject(i);
String id = c.getString(TAG_ID);
String username = c.getString(TAG_USERNAME);
String name = c.getString(TAG_NAME);
String phone = c.getString(TAG_PHONE);
String profile = c.getString(TAG_PROFILE);
// tmp hashmap for single student
HashMap<String, String> user = new HashMap<String, String>();
// adding each child node to HashMap key => value
user.put(TAG_ID, id);
user.put(TAG_USERNAME, username);
user.put(TAG_NAME, name);
user.put(TAG_PHONE, phone);
user.put(TAG_PROFILE, profile);
// adding student to students list
studentList.add(user);
}
return studentList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
return null;
}
}
}
GetAllUser class
package com.gmakerorganisation.glocator;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by user on 14-07-2016.
*/
public class GetAllUsers {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
//Constructor with no parameter
public GetAllUsers() {
}
/**
* Making web service call
*
* @url - url to make request
* @requestmethod - http request method
*/
public String makeWebServiceCall(String url, int requestmethod) {
return this.makeWebServiceCall(url, requestmethod, null);
}
/**
* Making service call
*
* @url - url to make request
* @requestmethod - http request method
* @params - http request params
*/
public String makeWebServiceCall(String urladdress, int requestmethod,
HashMap<String, String> params) {
URL url;
String response = "";
try {
url = new URL(urladdress);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setDoInput(true);
conn.setDoOutput(true);
if (requestmethod == POST) {
conn.setRequestMethod("POST");
} else if (requestmethod == GET) {
conn.setRequestMethod("GET");
}
if (params != null) {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
writer.write(result.toString());
writer.flush();
writer.close();
os.close();
}
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
My php source code is
<?php
//If a post request is detected
if($_SERVER['REQUEST_METHOD']=='POST'){
//Importing the dbConnect script
require_once('conn.php');
$users = array();
$sql = "SELECT id , username, name, phone, profile FROM glocator";
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result)>0) {
while ($row =mysqli_fetch_array($result)) {
$users['id'] = $row['id'];
$users['username'] = $row['username'];
$users['name'] = $row['name'];
$users['phone'] = $row['phone'];
$users['profile'] = $row['profile'];
echo json_encode($users);
}
}
//Closing the database
mysqli_close($con);
}
?>
And I am using postman so when I send post request it gives this data
{"id":"1","username":"gmaker","name":"SHUBHAM SHARMA","phone":"9711979977","profile":"http:\/\/glocator.esy.es\/profilepicture\/1."}{"id":"4","username":"somnath","name":"","phone":"9582223881","profile":""}{"id":"7","username":"shitij","name":"","phone":"9650154839","profile":""}
Upvotes: 0
Views: 90
Reputation: 617
your Json file does not contain any array.Then you could not use it to retrieve data by creating object of jsonarray..so try this code and remove for loop.
JSONObject jsonObj = new JSONObject(json);
// looping through All Students
JSONObject c = JSONObject.getJSONObject(jsonobj);
String id = c.getString(TAG_ID);
String username = c.getString(TAG_USERNAME);
String name = c.getString(TAG_NAME);
String phone = c.getString(TAG_PHONE);
String profile = c.getString(TAG_PROFILE);
Upvotes: 0
Reputation: 51
You json have some errors, copy your JSON and verify here.
Its must looks like:
[
{
"id":"1",
"username":"gmaker",
"name":"SHUBHAM SHARMA",
"phone":"9711979977",
"profile":"http:\/\/glocator.esy.es\/profilepicture\/1."
},
{
"id":"4",
"username":"somnath",
"name":"",
"phone":"9582223881",
"profile":""
},
{
"id":"7",
"username":"shitij",
"name":"",
"phone":"9650154839",
"profile":""
}
]
Now you can follow some following tutorials.
Android json parsing using okhttp example with new material design library
Upvotes: 2