I want to display a list of member from a JSON file. Member information like Name, Location, Contact number, image etc. All information is showing fine but Member Image is not showing. Here is given the necessary file and coding for your checking.
JSON file
{"names":[
{
"serialno":"1. ",
"memberimage":"#drawable/tojib",
"membername":"শেখ তজিবুল ইসলাম",
"farmacyname":"Farmacy1",
"mobileno":"01942717067",
"address":"Digholia, Lohagara, Narial"
},
{
"serialno":"2. ",
"memberimage":"#drawable/tojib",
"membername":"শেখ তজিবুল ইসলাম",
"farmacyname":"Farmacy2",
"mobileno":"01823987654",
"address":"Kumri, Lohagara, Narial"
},
{
"serialno":"3. ",
"memberimage":"#drawable/tojib",
"membername":"শেখ তজিবুল ইসলাম",
"farmacyname":"Farmacy3",
"mobileno":"01782345678",
"address":"Baira, Lohagara, Narial"
},
{
"serialno":"4. ",
"memberimage":"#drawable/tojib",
"membername":"শেখ তজিবুল ইসলাম",
"farmacyname":"Farmacy4",
"mobileno":"01943876543",
"address":"Lutia, Lohagara, Narial"
}
]
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolBarId);
setSupportActionBar(toolbar);
listview=findViewById(R.id.listViewId);
try {
JSONObject jsonObject=new JSONObject(loadJsonFile());
JSONArray jsonArray=jsonObject.getJSONArray("names");
HashMap<String,String> listItem;
ArrayList<HashMap<String,String>> listItems=new ArrayList<>();
for(int i=0; i<jsonArray.length();i++)
{
JSONObject obj=jsonArray.getJSONObject(i);
String serialno=obj.getString("serialno");
String memberimage=obj.getString("memberimage");
String farmacyname=obj.getString("farmacyname");
String membername=obj.getString("membername");
String mobileno=obj.getString("mobileno");
String address=obj.getString("address");
listItem=new HashMap<>();
listItem.put("serialno",serialno);
listItem.put("memberimage",memberimage);
listItem.put("farmacyname",farmacyname);
listItem.put("membername",membername);
listItem.put("mobileno",mobileno);
listItem.put("address",address);
listItems.add(listItem);
}
ListAdapter adapter=new SimpleAdapter(this,listItems,R.layout.main_list_item_layout,
new String[]{"serialno","memberimage","membername","farmacyname","mobileno","address"},
new int[]{R.id.serialTextViewId,R.id.imageViewId,R.id.nameTextViewId,
R.id.shopNameTextViewId,R.id.mobileNoTextViewId,R.id.addressTextViewId});
listview.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String loadJsonFile() throws IOException {
String json=null;
InputStream inputStream=this.getAssets().open("member.json");
int size=inputStream.available();
byte[] byteArray=new byte[size];
inputStream.read(byteArray);
inputStream.close();
json=new String(byteArray, "UTF-8");
return json;
}
}
Problem: The image is not showing in list. Other information is showing good but Image is blank. Can anyone please help me if I do mistake anywhere.
When adding the image to the list you want to add the drawble id and not the drawable string i.e "#drawable/tojib" like below:
String memberImageDrawable = obj.getString("memberimage");
memberImageDrawable = memberImageDrawable.substring(memberImageDrawable.indexOf("/")); //extract the String after #drawable/
String memberimage = Integer.toString(getApplicationContext().getResources().getIdentifier(memberImageDrawable, "drawable", getApplicationContext().getPackageName()));
Related
I have an app that is supposed to read a json file and inset its contents into a list view, I know this question was asked tons of times here but I can't understand why it's not working. I managed to narrow my problem to 1 line so far, JSONObject object = new JSONObject(readJSON());. This is all of my code:
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<Post> arrayList;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.lvPosts);
arrayList = new ArrayList<>();
try {
JSONObject object = new JSONObject(readJSON());
JSONArray array = object.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String productName = jsonObject.getString("productName");
String locationName = jsonObject.getString("locationName");
String price = jsonObject.getString("price");
String date = jsonObject.getString("date");
String description = jsonObject.getString("description");
String comment = jsonObject.getString("comment");
Log.i(TAG, price);
Post post = new Post();
post.setItemName(productName);
post.setLocationName(locationName);
post.setPrice(price);
post.setDate(date);
post.setDescription(description);
post.setExistingComment(comment);
arrayList.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
}
PostAdapter adapter = new PostAdapter(this, arrayList);
listView.setAdapter(adapter);
}
public String readJSON() {
String json = null;
try {
// Opening data.json file
InputStream inputStream = getAssets().open("MOCK_DATA.json");
int size = inputStream.available();
byte[] buffer = new byte[size];
// read values in the byte array
inputStream.read(buffer);
inputStream.close();
// convert byte to string
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return null;
}
return json;
}
}
My problem is that once I run the app my listView will remain empty and wont be populated with data.
if you are using java version >jdk1.7 then I would recommend you use Files class from "java.nio.file" package . you can easily read JSON file in a single line code.
public String readJSON() {
String jsontext="";
try{
jsontext= new String(Files.readAllBytes(Paths.get("<file path>"),StandardCharset.UTF_8);
}
catch(Exception ex){
ex.printStackTrace();
}
return jsontext;
}
after that you can use JSONObject to parse string like below:---
JSONObject object = new JSONObject(readJSON());
I am trying to get data from a JSON file that was written in a PHP file which was stored in my online hosting server(00webhost.com). When I run my program it says unknown host. However, the address will give JSON formatted file.
I have all the permissions along with the internet permission in my AndroidManifest.xml file.
Activity Class :
public class Recmain extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
TextView uid;
TextView name1;
TextView email1;
Button Btngetdata;
//URL to get JSON Array
private static String url = "http://tongue-tied-
papers.000webhostapp.com/data_fetch.php";
//JSON Node Names
private static final String TAG_USER = "user";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
JSONArray user = null;
private List<movie> movieList = new ArrayList<>();
private RecyclerView recyclerView;
private moviesadapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rmain);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent=getIntent();
String m=intent.getStringExtra("data");
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new moviesadapter(movieList);
RecyclerView.LayoutManager mLayoutManager = new
LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
prepareMovieData();
}
private void prepareMovieData(){
movie movie = new movie("Mad Max: Fury Road", "Action & Adventure",
"2015");
movieList.add(movie);
mAdapter.notifyDataSetChanged();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(recmain.this,url,Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
JSONParser sh = new JSONParser();
// Making a request to url and getting response
String url = "https://tongue-tied-
papers.000webhostapp.com/data_fetch.php";
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("id");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
Toast.makeText(getApplicationContext(), id ,
Toast.LENGTH_LONG).show();
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat
for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
}
Adapter class:
public class JSONParser {
private static final String TAG = JSONParser.class.getSimpleName();
public JSONParser() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection)
url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new
InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
It says, unknown host.
Looks like the URL is not formatted correctly. I think there is a space between the two parts of the URL.
private static String url = "http://tongue-tied-papers.000webhostapp.com/data_fetch.php"
Please try with the URL above without any space between the tied- and papers. You have two separate URL declaration, one at the beginning of the class and the other is in the doInBackground method. Please try changing both.
I am New to the android studio and want to something more. Actually, I am trying to pass the string that I got from the spinner in onCreateMethod and pass to the onPostExecute function. I will be grateful for the help. Bellow is my code.
I tried making a global variable called First and store the string from spinner and pass it on the onPostExecute function.
public class Convert extends AppCompatActivity implements LocationListener
{
Spinner dropdown;
Button btn;
String text;
String first;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_convert);
dropdown = (Spinner) findViewById(R.id.spinner1);
btn = (Button)findViewById(R.id.btn);
String[] items = new String[]{"United States,USD", "Nepal,NPR", "Bangladesh,BDT","Brazil,BRL"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
dropdown.setAdapter(adapter);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text = dropdown.getSelectedItem().toString();
first = text.substring(text.length()-3);
Log.i("her", first);
}
});
new DownloadTask().execute("http://openexchangerates.org/api/latest.json?
app_id=XXXXXXXXXX");
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection httpURLConnection = null;
try {
url = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char counter = (char) data;
result += counter;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try{
JSONObject jsonObject = new JSONObject(result);
JSONObject curr = jsonObject.getJSONObject("rates");
String npr = curr.getString(first);
Log.i("money", npr );
} catch (JSONException e) {
e.printStackTrace();
}
}
}
What I want is to pass the string first on the onPostExecute function.
When you will call your DownloadTask, asyncTask fires with method execute, just pass param though him. Example:
How to pass url
new DownloadTask().execute("url for download");
How to receive url
protected String doInBackground(String... urls) {
String url = urls[0]; // url for download
}
Also you could send and array of params. Also be careful with AsyncTask, do not pass your context/view variable, it could arise memory leaks, read docs.
I am currently making an app where the user can access study material from a list view of different subjects.
In my database table where the subject names are fetched from also has a column which has a file path to a folder on my online server. Each subject has an individual folder on the server.
How would I go about adding to my code so that when a user clicks on a subject on the list, the content of their specific folder displays on a new activity?
here is my code at the moment of a simple list view:
public class FindMaterialActivity extends Activity {
private ListView list;
private ArrayList<String> subjects;
private JSONArray result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_material2);
list = (ListView) findViewById(R.id.list);
subjects = new ArrayList<String>();
getData();
}
private void getData() {
//Creating a string request
StringRequest stringRequest = new StringRequest(SubConfig.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(SubConfig.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getSubjects(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getSubjects(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
subjects.add(json.getString(SubConfig.TAG_SUBJECTS));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
list.setAdapter(new ArrayAdapter<String>(FindMaterialActivity.this, android.R.layout.simple_list_item_1, subjects));
}
}
and subject config.java
public class SubConfig {
//JSON URL
public static final String DATA_URL = "http://opuna.co.uk/subject_api/FetchSub.php";
//Tags used in the JSON String
public static final String TAG_SUBJECTS = "Subject_Name";
public static final String TAG_SUB_ID = "Sub_id";
//JSON array name
public static final String JSON_ARRAY = "result";
}
Store the meta about the sub folders in your database as you did for subjects and get the meta using JSON in your app as you got for subjects and show them in a custom layout made of your own.
I'm trying to load JSON from a URL in an Android app (the URL only links to JSON data, there is nothing else).
For now I'm only trying to load the content of the URL into a String.
The problem I have is that I need to handle the Exceptions, but I'm not too familiar with that.
Here is the relevant part of my 'Functions' class:
static public String loadURL(String inputURL) throws Exception {
String fullString = "";
URL url = new URL(inputURL);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
fullString += line;
}
reader.close();
return fullString;
}
This is what I'm currently using (in a different class) for testing purposes:
Toast.makeText(Setup.this, Functions.loadURL("http://www.exampleJSON.com"), Toast.LENGTH_LONG).show();
I'm planning on using the output to extract JSON data for if-statements, saving in sharedPreferences and displaying.
EDIT
Here what I'm using to call the method:
public class Setup extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup);
final SharedPreferences preferences = this.getPreferences(Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
final Spinner spinner = (Spinner) findViewById(R.id.spinner);
final EditText editText = (EditText) findViewById(R.id.editText);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.setup_region_spinner, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
//BUTTON PRESS
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putString("Server", String.valueOf(spinner.getSelectedItem()));
if (String.valueOf(spinner.getSelectedItem()).equals("EUW")) {
}
else if (String.valueOf(spinner.getSelectedItem()).equals("NA")) {
try {
Toast.makeText(Setup.this, Functions.loadURL("https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/" +
editText.getText().toString().replaceAll("\\s", "") +
"?api_key=cbc50791-3c4d-45e6-b0c1-8aa204ced475"), Toast.LENGTH_LONG).show();
}catch(Exception e){
e.printStackTrace();
}
}
//ERROR
else {
Toast.makeText(Setup.this, "Server selection error", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
The try-block was just added after reading through the answers. Another one was added in my loadURL method. It seems to work for now.
I'm now getting errors because I was trying to run this on the main thread. I'll have to read more about that.
Put your code inside try block and catch the exception:
try {
String fullString = "";
URL url = new URL(inputURL);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
fullString += line;
}
reader.close();
return fullString;
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
First, go through the basic JSON format. There are basically two things to look at :
JSONObject
JSONArray
Once you are comfortable with these two, try parsing the response using :
try{
JSONObject jsonObject = new JSONObject(<your_response_string_here>);
//Your parsing logic here
}catch(JSONException ex){
ex.printStackTrace();
}
Lets say your json was :
{
"some_status": 200,
"my_data": {
"param1": "value1",
"param2": "value2"
},
"my_array": ["arrayvalue1", "arrayvalue2"]
}
Your code should look somehting like this:
try{
JSONObject jsonObject = new JSONObject(<your_response_string_here>);
//Your parsing logic here
int status = jsonObject.optString("some_status");
JSONObject my_data = jsonObject.optJSONObject("my_data");
//Here parse your "my_data" object to get "param1" and "param2"
JSONArray my_array = jsonObject.optJSONArray("my_array");
//Here parse your "my_array" array to get "arrayvalue1" and "arrayvalue2"
}catch(JSONException ex){
ex.printStackTrace();
}
Please go through Android DOCS: http://developer.android.com/reference/org/json/JSONObject.html
And some examples like : http://www.tutorialspoint.com/android/android_json_parser.htm
I hope this helps.