This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Hi I am learning Android App Development. For this, I wanted to make myself a simple wallpaper app. Hence, I wrote something roughly which is presented here. I want to get wallpaper urls from json. Unfortunately, I am unable to get data from my server. java.lang.NullPointerException: Attempt to read from null array
How do I get the data correctly from the jsonParse asynctask?
I am stuck on this the whole day. What could have gone wrong here?
Here is my code:
myjson.json:
{
"walls":[
{"ourUrl":"http://www.hdbloggers.net/wp-content/uploads/2016/01/Wallpapers-for-Android.jpg"},
{"ourUrl":"http://androidwallpape.rs/content/02-wallpapers/131-night-sky/wallpaper-2707591.jpg"},
{"ourUrl":"http://androidwallpape.rs/content/02-wallpapers/155-starrynight/starry-night-sky-star-galaxy-space-dark-9-wallpaper.jpg"}
]
}
MainActivity.java:
package regalstreak.me.wallpapers;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
public class MainActivity extends Activity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
RecyclerView.Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new RecyclerAdapter(this);
recyclerView.setAdapter(adapter);
}
}
RecyclerAdapter.java:
package regalstreak.me.wallpapers;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
// This is a recycleradapter which will set the correct images to the correct position in the recyclerview.
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private Context myCtx1;
String[] arr;
String[] arrurl;
String jsonURL = "http://dev.regalstreak.me/myjson.json";
public RecyclerAdapter(Context ctx) {
this.myCtx1 = ctx;
}
public ImageView Image;
private String[] mText = {
"Text 1",
"Text 2",
"Text 3"
};
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView Text;
public ViewHolder(View itemView) {
super(itemView);
Image = (ImageView) itemView.findViewById(R.id.image_view);
Text = (TextView) itemView.findViewById(R.id.text_view);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.wallpapers_list, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
viewHolder.Text.setText(mText[i]);
new jsonParse().execute();
new DownloadImageTask(Image).execute(arrurl[i]);
}
#Override
public int getItemCount() {
return mText.length;
}
class jsonParse extends AsyncTask<String, Void, String[]> {
protected String[] doInBackground(String[] urls) {
String myText = null;
String url = urls[0];
String ourUrl;
try {
InputStream in = new java.net.URL(jsonURL).openStream();
myText = IOUtils.toString(in, "utf-8");
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Parse the json
List<String> allUrls = new ArrayList<String>();
JSONObject jsonObjectRoot = new JSONObject(myText);
JSONArray jsonArray = jsonObjectRoot.getJSONArray("walls");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
ourUrl = jsonObject.getString("ourUrl");
allUrls.add(ourUrl);
}
arr = allUrls.toArray(new String[allUrls.size()]);
} catch (JSONException e) {
e.printStackTrace();
}
return arr;
}
protected void onPostExecute(String[] result){
arrurl = result;
}
}
}
DownloadImageTask.java:
package regalstreak.me.wallpapers;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
import java.io.InputStream;
// Here, we will download the wallpapers obtained from jsonData with an asynctask.
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap>{
ImageView bmImage;
public DownloadImageTask(ImageView bmImage){
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
in.close();
} catch (Exception e) {
Log.e("Error getting images.", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result){
bmImage.setImageBitmap(result);
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="regalstreak.me.wallpapers.MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycler_view" />
</RelativeLayout>
wallpaper_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relative"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="5dp">
<ImageView
android:id="#+id/image_view"
android:layout_width="match_parent"
android:layout_height="150dp" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/image_view"
android:alpha="0.6"
android:background="#color/colorDivider"
android:padding="9dp">
<TextView
android:id="#+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:textColor="#color/colorPrimaryText" />
</RelativeLayout>
</RelativeLayout>
I have used HttpURLConnection class here for quick response and features like cache. The data received from the URL is being added to an input stream which we then convert to a String builder to get a string object which we can further use with the JSON classes.
PS - Add the AsyncTask code to your MainActivity itself, don't make a separate java file for this.
Tip - Always verify the json using this tool - jsonlint.com
MainActivity
/*
your code
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
new MyAsyncTask().execute("");
}
class MyAsyncTask extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(StartScreen.this);
InputStream inputStream = null;
String result = "";
ArrayList<String> list;
protected void onPreExecute() {
progressDialog.setTitle("Downloading JSON Data");
progressDialog.show();
// above code makes a dialog with a progress bar
}
#Override
protected Void doInBackground(String... params) {
ArrayList<String> param = new ArrayList<String>();
URL url, url2;
try{
url = new URL("http://dev.regalstreak.me/myjson.json");
// link to your json file
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setUseCaches(false);
inputStream = new BufferedInputStream(urlConnection.getInputStream());
}catch (MalformedURLException malle){
Log.e("Mal", ""+malle);
malle.printStackTrace();
}catch (IOException ioe){
Log.e("IO", ""+ioe);
ioe.printStackTrace();
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding", "Error converting result " + e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
//parse JSON data
try {
JSONObject jobj = new JSONObject(result);
//Taking a JSON Array from the JSONObject created above
String url = jobj.getString("ourUrl");
// We are adding this string to the ArrayList
list.add(url);
progressDialog.dismiss();
Context con = ListLoader.this.getApplication();
adapter = new RecyclerAdapter(list,con);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
}
}
/*
your code
*/
Now to display the images more effectively in the list, use the repo Universal image loader. It has a lot of features. You can get it here - https://github.com/nostra13/Android-Universal-Image-Loader
And then add this kind of code to display the images. Put it inside the onBindViewHolder
Adapter
#Override
public void onBindViewHolder(DataHolder holder, int position) {
ImageLoaderConfiguration config;
config = new ImageLoaderConfiguration.Builder(mContext).build();
ImageLoader.getInstance().init(config);
imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_error_black_48dp) // displays this image not found
.showImageOnFail(R.drawable.ic_error_black_48dp) // Displays this on failure
.showImageOnLoading(R.drawable.white) // Displays while loading
.cacheInMemory(false)
.cacheOnDisk(true)
.build();
imageLoader.displayImage(list.get(position), holder.imageView, options);
// We are feeding the urls here.
}
Related
I intended to fetch data from ConnectionClass in background and then populate it into recyclerView.
Now, I have successfully fetched the data from url in json format, but my app is crashing when I am trying to display data using recyclerView.
Adapter Class for recyclerview
package com.example.mainapp;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import Model.PersonDetails;
public class PersonDetailsAdapter extends RecyclerView.Adapter<PersonDetailsAdapter.ViewHolder> {
private List<PersonDetails> personDetails;
PersonDetailsAdapter(List<PersonDetails>details)
{
personDetails = details;
}
#NonNull
#Override
public PersonDetailsAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Log.d("create view " , personDetails.toString());
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context) ;
View personView = inflater.inflate(R.layout.person_details_view , parent , true) ;
ViewHolder view = new ViewHolder(personView) ;
return view;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
PersonDetails details = personDetails.get(position);
holder.nameTextView.setText(details.getName());
holder.aliasTextView.setText(details.getAlias());
}
#Override
public int getItemCount() {
return personDetails.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView nameTextView;
public TextView aliasTextView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
nameTextView = (TextView) itemView.findViewById(R.id.nameHolder);
aliasTextView = (TextView) itemView.findViewById(R.id.aliasHolder);
}
}
}
MainActivity.java
package com.example.mainapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.example.mainapp.Utility.ConnectionClass;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.net.MalformedURLException;
import java.util.List;
import Model.PersonDetails;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button getButton = findViewById(R.id.get);
Button postButton = findViewById(R.id.post);
Context context = this.getBaseContext();
getButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConnectionClass conn = null;
try {
conn = new ConnectionClass("URL", context);
conn.execute();
} catch (MalformedURLException e) {
System.out.println("connection not set ");
e.printStackTrace();
}
}
});
postButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postRequest();
}
}
);
}
public void updateView( List<PersonDetails> personDetails ) {
Log.d("1" , "******************************************called fro");
RecyclerView rView = (RecyclerView)findViewById(R.id.recyclerViewPerson);
Log.d("2" , "******************************************iosdjdsa");
PersonDetailsAdapter adapter = new PersonDetailsAdapter(personDetails);
rView.setLayoutManager(new GridLayoutManager(this, 5));
rView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
private void postRequest() {
}
}
ConnectionClass.java
package com.example.mainapp.Utility;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.example.mainapp.MainActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import Model.PersonDetails;
public class ConnectionClass extends AsyncTask<Void, Void, Void> {
private URL url ;
private HttpURLConnection conn;
private String response ;
private Context context ;
public ConnectionClass() {
super();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Log.d("onPost", "*****************************************postexe");
Toast.makeText(context, "Records fetched",Toast.LENGTH_SHORT);
List<PersonDetails> details = new ArrayList<>();
try {
JSONArray arr = new JSONArray(response);
for( int i = 0; i < arr.length() ; ++i )
{
JSONObject jObject = arr.getJSONObject(i);
PersonDetails record = new PersonDetails(jObject.getString("name"),jObject.getString("alias") );
details.add(record);
}
} catch (JSONException e) {
Log.d("t","json exception");
e.printStackTrace();
}
Log.d( "detalis", "**************************************"+details.toString());
MainActivity activity = new MainActivity();
activity.updateView(details);
}
public ConnectionClass(String url, Context context) throws MalformedURLException {
this.url = new URL (url);
conn = null ;
this.context = context;
}
// public void sendRequest(){
// try {
// System.out.println("\n\n***************************************hello**********************\n\n");
// conn = (HttpURLConnection) url.openConnection();
// conn.setDoOutput(false);
// conn.setDoInput(true);
// conn.setUseCaches(false);
// conn.setRequestMethod("GET");
// conn.setRequestProperty("Content-Type", "application/json");
// conn.connect();
// // handle the response
// System.out.println("\n\n***************************************here**********************\n\n");
//
// int status = conn.getResponseCode();
// System.out.println(status);
//
// if (status != 200)
// throw new IOException("Request not completed");
// else
// {
// BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// String inputLine ;
// StringBuilder builder = new StringBuilder() ;
// while((inputLine = in.readLine()) != null )
// builder.append(inputLine);
// in.close();
// response = builder.toString();
// }
//
// }
// catch (IOException e) {
// e.printStackTrace();
// }
// finally{
// if( conn != null )
// conn.disconnect();
// }
// }
public void setUrl(String url) throws MalformedURLException {
this.url = new URL(url);
}
public String getResponse() {
return response;
}
#Override
protected Void doInBackground(Void... voids) {
try {
conn = (HttpURLConnection) url.openConnection();
Log.d("conn", "***************************************************************************connectioon set " ) ;
} catch (IOException e) {
e.printStackTrace();
}
try {
conn.setRequestMethod("GET");
} catch (ProtocolException e) {
e.printStackTrace();
}
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setDoOutput(true);
try {
conn.connect();
Log.d("conn " , "**********************************************************************connected ");
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
try{
br =new BufferedReader(new InputStreamReader(url.openStream()));
char[] buffer = new char[1024];
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
Log.d("sb" , String.valueOf(sb));
}
catch (IOException e)
{
e.printStackTrace();
}
finally{
Log.d("finally ", "*****************************************************************************************finally");
response = sb.toString();
System.out.println("JSON: " + response);
conn.disconnect();
}
return null ;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentTop="true"
android:layout_marginTop="-3dp">
<TextView
android:id="#+id/nameText"
android:layout_width="141dp"
android:layout_height="45dp"/>
<TextView
android:id="#+id/aliasText"
android:layout_width="141dp"
android:layout_height="45dp"
android:layout_marginLeft="119dp"
android:layout_toRightOf="#+id/nameText" />
<Button
android:id="#+id/post"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentBottom="true"
android:layout_marginLeft="-11dp"
android:layout_marginBottom="2dp"
android:text="POST" />
<Button
android:id="#+id/get"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginRight="1dp"
android:layout_marginBottom="3dp"
android:text="GET" />
</RelativeLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewPerson"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#972A2A" />
</RelativeLayout>
xml for RecyclerView content
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="50dp"
android:padding="10dp">
<TextView
android:id="#+id/nameHolder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="TextView" />
<TextView
android:id="#+id/aliasHolder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="TextView" />
</LinearLayout>
Application is crashing when control reaches updateView()?
Add your AsyncTask code at the bottom of your MainActivity and then update the recyclerview like this:
updateView(details);
Let me clarify #sdex answer:
When you create an instance of Activity - in your case MainActivity - it doesn't have a view, it is not visible to the user and it's not added to the Activity stack. You could say - this activity is "Dead"
In order to display the result to your currently running MainActivity, so it's displayed to the user, you need to pass the instance of it to the ConnectionClass class. For example - pass it to the constructor of the ConnectionClass.
By the way - please consider moving away from AsyncTask, it's been deprecated and could be a reason for the Context leaks, meaning - you'll have massive objects, that are no more visible to the user are retaining in the memory.
In order to avoid leaking the Activity reference, please store it as the "WeakReference"
MainActivity activity = new MainActivity();
activity.updateView(details);
You can't instantiate activity like this; if you want to call a method in the activity within the AsynkTask class ConnectionClass; you can pass a listener to it and implement this listener in the activity, and then invoke the callback of that listener when you want to call some functionality in the activity.
interface ConnectionClassListener {
void onPostExecuteFinished(List<PersonDetails> personDetails);
}
Pass the class to the AsyncTask constructor
public class ConnectionClass extends AsyncTask<Void, Void, Void> {
ConnectionClassListener mConnectionClassListener;
public ConnectionClass(String url, Context context, ConnectionClassListener listener) throws MalformedURLException {
this.url = new URL (url);
conn = null ;
this.context = context;
mConnectionClassListener = listener;
}
Implement the listener by the activity
public class MainActivity extends AppCompatActivity implements ConnectionClassListener {
#Override
void onPostExecuteFinished(List<PersonDetails> personDetails) {
// Do here what you want when the ConnectionClass calls `onPostExecuteFinished()`
updateView(personDetails);
}
}
add this when creating the AsynkTask class
conn = new ConnectionClass("URL", context, this);
And finally call onPostExecuteFinished() in your ConnectionClass
public class ConnectionClass extends AsyncTask<Void, Void, Void> {
// ...
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// ...
mConnectionClassListener.onPostExecuteFinished(details);
MainActivity activity = new MainActivity();
You cannot just create the instance using the constructor. You should pass a reference of MainActivity to make it work. You need just to change a few lines of the code:
In ConnectionClass replace field private Context context; by private MainActivity activity; and change the constructor accordingly:
public ConnectionClass(String url, MainActivity activity) throws MalformedURLException {
this.url = new URL (url);
conn = null ;
this.activity = activity;
}
After that, you will be able to call activity.updateView(details);.
And don't forget to remove MainActivity activity = new MainActivity();
Further reading:
Proper use of AsyncTask
AsyncTask deprecation and alternatives
I'm making a simple program where I can get a content from JSON in this url
https://www.haliminfo.com/feeds/posts/summary/?max-results=10&start-index=1&alt=json
and make it a list Using RecyclerView on Android.
I have made several necessary components such as Model, Adapter, Post Row Item and HttpHandler
when I try RecyclerView with a method like this it works.
private void addData () {
postsArrayList = new ArrayList <> ();
postsArrayList.add (new Posts ("TITLE", "SUMMARY"));
}
but when I apply the method below nothing appears in the activity
private class getContent extends AsyncTask <Void, Void, Void> {
# Override
protected Void doInBackground (Void ... voids) {
HttpHandler sh = new HttpHandler ();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall (URL_FIX);
if (jsonStr! = null) {
try {
JSONObject jsonObj = new JSONObject (jsonStr);
JSONObject feed = jsonObj.getJSONObject ("feed");
JSONArray entry = feed.getJSONArray ("entry");
Posts postsModel = new Posts ();
for (int i = 0; i <entry.length (); i ++) {
postsModel.setTitle (entry.getJSONObject (i) .getJSONObject ("title"). getString ("$ t"));
postsModel.setSummary (entry.getJSONObject (i) .getJSONObject ("summary"). getString ("$ t"));
postsArrayList.add (postsModel);
}
} catch (final JSONException e) {
Log.e ("RESPONSE", "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 ("RESPONSE", "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;
}
}
this is a full file of some important files in my project
MainActivity.java
package com.badjing.bloggercoba.activities;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.badjing.bloggercoba.R;
import com.badjing.bloggercoba.adapter.PostRecyclerViewAdapter;
import com.badjing.bloggercoba.config.Config;
import com.badjing.bloggercoba.handler.HttpHandler;
import com.badjing.bloggercoba.model.Posts;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private PostRecyclerViewAdapter postAdapter;
private ArrayList<Posts> postsArrayList;
private ProgressDialog pDialog;
private Config config = new Config();
String URL_FIX = Config.BLOG_URL + Config.BLOG_URL_MAX_RESULT + Config.MAX_RESULT + config.BLOG_URL_START_INDEX + config.START_INDEX + config.BLOG_URL_ALT_TYPE;;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
postsArrayList = new ArrayList<>();
new getContent().execute();
recyclerView = (RecyclerView) findViewById(R.id.post_recycle_view);
postAdapter = new PostRecyclerViewAdapter(postsArrayList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(postAdapter);
}
// private void addData() {
//
// postsArrayList = new ArrayList<>();
// postsArrayList.add(new Posts("JUDUL", "SUMMARY"));
//
// }
private class getContent extends AsyncTask<Void, Void, Void> {
// #Override
// protected void onPreExecute() {
// super.onPreExecute();
// // Showing progress dialog
// pDialog = new ProgressDialog(MainActivity.this);
// pDialog.setMessage("Please wait...");
// pDialog.setCancelable(false);
// pDialog.show();
// }
#Override
protected Void doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(URL_FIX);
if (jsonStr != null) {
try{
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject feed = jsonObj.getJSONObject("feed");
JSONArray entry = feed.getJSONArray("entry");
Posts postsModel = new Posts();
for (int i = 0; i < entry.length(); i++) {
postsModel.setTitle(entry.getJSONObject(i).getJSONObject("title").getString("$t"));
postsModel.setSummary(entry.getJSONObject(i).getJSONObject("summary").getString("$t"));
postsArrayList.add(postsModel);
}
} catch (final JSONException e) {
Log.e("RESPONSE", "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("RESPONSE", "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;
}
}
private void urlBuilder() {
URL_FIX = Config.BLOG_URL + Config.BLOG_URL_MAX_RESULT + 10 + config.BLOG_URL_START_INDEX + 1 + config.BLOG_URL_ALT_TYPE;
}
}
Post.java (post model)
package com.badjing.bloggercoba.model;
public class Posts {
String title;
String summary;
public Posts() {
}
public Posts(String title, String summary) {
this.title = title;
this.summary = summary;
}
public String getTitle() {
return title;
}
public String getSummary() {
return summary;
}
public void setTitle(String title) {
this.title = title;
}
public void setSummary(String summary) {
this.summary = summary;
}
}
PostRecyclerViewAdapter.java
package com.badjing.bloggercoba.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.badjing.bloggercoba.R;
import com.badjing.bloggercoba.model.Posts;
import java.util.ArrayList;
public class PostRecyclerViewAdapter extends RecyclerView.Adapter<PostRecyclerViewAdapter.MyViewHolder> {
private ArrayList<Posts> postsList;
public PostRecyclerViewAdapter(ArrayList<Posts> postsArrayList) {
this.postsList = postsArrayList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.post_row_item, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.blog_post_title.setText(postsList.get(position).getTitle());
holder.blog_post_sumary.setText(postsList.get(position).getSummary());
}
#Override
public int getItemCount() {
return (postsList!= null) ? postsList.size() : 0;
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView blog_post_title, blog_post_sumary, blog_post_author;
ImageView img_thumbnail;
public MyViewHolder(View itemView) {
super(itemView);
blog_post_title = itemView.findViewById(R.id.blog_post_title);
blog_post_sumary = itemView.findViewById(R.id.blog_post_sumary);
// blog_post_author = itemView.findViewById(R.id.blog_post_author);
// img_thumbnail = itemView.findViewById(R.id.post_thumbnail);
}
}
}
post_row_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_marginTop="5dp"
android:padding="8dp"
android:background="#fff">
<ImageView
android:id="#+id/post_thumbnail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/loading_shape"></ImageView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="230dp"
android:orientation="vertical"
android:layout_margin="8dp" >
<TextView
android:id="#+id/blog_post_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="blog post title"
android:textSize="20dp"
android:textStyle="bold"/>
<TextView
android:id="#+id/blog_post_sumary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="blog post summary"/>
<TextView
android:id="#+id/blog_post_author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="~ author"/>
</LinearLayout>
</LinearLayout>
thank you for your attention and help.
RecyclerView is updated after the search and mCallback returns null but before search works correctly.
AdapterHistorico.java
package com.beliasdev.cadjobel.adapter;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.beliasdev.cadjobel.R;
import com.beliasdev.cadjobel.utility.DrawableHelper;
import com.bumptech.glide.Glide;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
public class AdapterHistorico extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Spinner spinner1;
private String dateold;
private String datenew;
private String compareValue;
private String concluido;
private String em_andamento;
private String cancelado;
private String concluido1;
private String em_andamento1;
private String cancelado1;
private String status;
private Context context;
private LayoutInflater inflater;
private IProcessFilter mCallback;
private ArrayList<DataHistorico> data;
//List<DataHistorico> data= Collections.emptyList();
DataHistorico current;
int currentPos=0;
public AdapterHistorico(Context context, ArrayList<DataHistorico> data, IProcessFilter callback){
this.context=context;
inflater= LayoutInflater.from(context);
this.data=data;
mCallback = callback;
}
public interface IProcessFilter {
void onProcessFilter(DataHistorico produtos);
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.container_historico, parent,false);
MyHolder holder=new MyHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final DataHistorico pedidos = data.get(position);
values from list
MyHolder myHolder= (MyHolder) holder;
final DataHistorico current = data.get(position);
dateold = current.pData;
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yyyy 'ás' HH:mm:ss");
datenew = df2.format(format.parse(dateold));
} catch (ParseException e) {
e.printStackTrace();
}
myHolder.txtPedidoNumero.setText("N° " + current.pNumero);
myHolder.txtPedidoCliente.setText(current.pCliente);
myHolder.txtPedidoData.setText(datenew);
myHolder.txtPedidoTotal.setText("R$ " + current.pTotal);
myHolder.edtPedido.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCallback.onProcessFilter(pedidos); //NullPointerException here
}
});
// load image into imageview using glide
concluido = "concluido";
cancelado = "cancelado";
em_andamento= "em_andamento";
status = current.pStatus;
if (status.equals(concluido)) {
Glide.with(context).load(R.drawable.ic_pedido_concluido).into(myHolder.imgPedidoStatus);
} else if (status.equals(cancelado)) {
Glide.with(context).load(R.drawable.ic_pedido_cancelado).into(myHolder.imgPedidoStatus);
}else if (status.equals(em_andamento)) {
Glide.with(context).load(R.drawable.ic_pedido_em_andamento).into(myHolder.imgPedidoStatus);
}
}
// return total item from List
#Override
public int getItemCount() {
return data.size();
}
class MyHolder extends RecyclerView.ViewHolder{
TextView txtPedidoNumero;
TextView txtPedidoCliente;
ImageView imgPedidoStatus;
TextView txtPedidoData;
TextView txtPedidoTotal;
ImageView edtPedido;
// create constructor to get widget reference
public MyHolder(View itemView) {
super(itemView);
txtPedidoNumero= (TextView) itemView.findViewById(R.id.txtPedidoNumero);
txtPedidoCliente= (TextView) itemView.findViewById(R.id.txtPedidoCliente);
imgPedidoStatus= (ImageView) itemView.findViewById(R.id.imgPedidoStatus);
txtPedidoData = (TextView) itemView.findViewById(R.id.txtPedidoData);
txtPedidoTotal = (TextView) itemView.findViewById(R.id.txtPedidoTotal);
edtPedido = (ImageView) itemView.findViewById(R.id.edtPedido);
}
}
}
FragmentoHistorico.java
public class FragmentoHistorico extends Fragment implements AdapterHistorico.IProcessFilter {
[...]
public void onProcessFilter(DataHistorico pedidos) {
EditarPedidoDialog(pedidos);
}
private void EditarPedidoDialog(final DataHistorico pedidos){
LayoutInflater inflater = LayoutInflater.from(getActivity());
final View subView = inflater.inflate(R.layout.layout_edt_pedido, null);
[...]
private class ProcurarPedido extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(getActivity());
HttpURLConnection conn;
URL url = null;
private String searchQuery;
private View rootView;
public ProcurarPedido(String searchQuery, View rootView){
this.searchQuery=searchQuery;
this.rootView=rootView;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tAguarde...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL(ADMIN_PANEL_URL + "public/procurar-pedido-app.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput to true as we send and recieve data
conn.setDoInput(true);
conn.setDoOutput(true);
// add parameter to our above url
Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("Erro na conexão!");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
Log.v("result", result);
pdLoading.dismiss();
ArrayList<DataHistorico> data=new ArrayList<>();
if(result.equals("no rows")) {
mRVHistoricoInfo = (RecyclerView)rootView.findViewById(R.id.ListaHistoricoInfo);
mAdapter = new AdapterHistorico(getActivity(), data, null);
mRVHistoricoInfo.setAdapter(mAdapter);
mRVHistoricoInfo.setLayoutManager(new LinearLayoutManager(getActivity()));
data.clear();
Toast.makeText(getActivity(), "Não foram encontrados pedidos pelo nome do cliente informado.", Toast.LENGTH_LONG).show();
}else{
try {
data.clear();
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataHistorico historicoData = new DataHistorico();
historicoData.pNumero= json_data.getString("nid");
historicoData.pStatus= json_data.getString("pedido_status");
historicoData.pCliente= json_data.getString("pedido_cliente");
historicoData.pEndereco= json_data.getString("pedido_endereco");
historicoData.pData= json_data.getString("pedido_data");
historicoData.pTotal= json_data.getString("pedido_total");
data.add(historicoData);
}
mRVHistoricoInfo = (RecyclerView)rootView.findViewById(R.id.ListaHistoricoInfo);
mAdapter = new AdapterHistorico(getActivity(), data, null);
mRVHistoricoInfo.setAdapter(mAdapter);
mRVHistoricoInfo.setLayoutManager(new LinearLayoutManager(getActivity()));
} catch (JSONException e) {
// You to understand what actually error is and handle it appropriately
Toast.makeText(getActivity(),"Não foi possível contatar o servidor.", Toast.LENGTH_LONG).show();
}
}
}
}
[...]
This is the error:
java.lang.NullPointerException: Attempt to invoke interface method
'void
com.beliasdev.cadjobel.adapter.AdapterHistorico$IProcessFilter.onProcessFilter(com.beliasdev.cadjobel.adapter.DataHistorico)'
on a null object reference
You are sending null instead of listener as a parameter:
So change
mAdapter = new AdapterHistorico(getActivity(), data, null);
To
mAdapter = new AdapterHistorico(getActivity(), data, this);
I am using this code to download images from my server, but for some reason I cannot display them. I show you the code that I use.
Main activity
MainActivity.java
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private String imagesJSON;
private static final String JSON_ARRAY ="result";
private static final String IMAGE_URL = "url";
private JSONArray arrayImages= null;
private int TRACK = 0;
private static final String IMAGES_URL = "http://imzzycool.biz.ht/PhotoUpload/getAllImages.php";
private Button buttonFetchImages;
private Button buttonMoveNext;
private Button buttonMovePrevious;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
buttonFetchImages = (Button) findViewById(R.id.buttonFetchImages);
buttonMoveNext = (Button) findViewById(R.id.buttonNext);
buttonMovePrevious = (Button) findViewById(R.id.buttonPrev);
buttonFetchImages.setOnClickListener(this);
buttonMoveNext.setOnClickListener(this);
buttonMovePrevious.setOnClickListener(this);
}
private void extractJSON(){
try {
JSONObject jsonObject = new JSONObject(imagesJSON);
arrayImages = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showImage(){
try {
JSONObject jsonObject = arrayImages.getJSONObject(TRACK);
getImage(jsonObject.getString(IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext() {
if (TRACK < arrayImages.length()) {
TRACK++;
showImage();
}
}
private void movePrevious() {
if (TRACK > 0) {
TRACK--;
showImage();
}
}
private void getAllImages() {
class GetAllImages extends AsyncTask<String,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Fetching Data...","Please Wait...",true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
imagesJSON = s;
extractJSON();
showImage();
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
}
GetAllImages gai = new GetAllImages();
gai.execute(IMAGES_URL);
}
private void getImage(String urlToImage){
class GetImage extends AsyncTask<String,Void,Bitmap>{
ProgressDialog loading;
#Override
protected Bitmap doInBackground(String... params) {
URL url = null;
Bitmap image = null;
String urlToImage = params[0];
try {
url = new URL(urlToImage);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Downloading Image...","Please wait...",true,true);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
loading.dismiss();
imageView.setImageBitmap(bitmap);
}
}
GetImage gi = new GetImage();
gi.execute(urlToImage);
}
#Override
public void onClick(View v) {
if(v == buttonFetchImages) {
getAllImages();
}
if(v == buttonMoveNext){
moveNext();
}
if(v== buttonMovePrevious){
movePrevious();
}
}
}
Proper xml file used
activity_main.xml
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Fetch Images"
android:id="#+id/buttonFetchImages" />
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="#+id/imageView"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Previous"
android:layout_weight="1"
android:id="#+id/buttonPrev" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Next"
android:layout_weight="1"
android:id="#+id/buttonNext" />
</LinearLayout>
And the server code(PHP)
getimage.php
<?php
require_once ('dbConnect.php');
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$id = $_GET['id'];
$sql = "SELECT * FROM photos WHERE id = '$id'";
$r = mysqli_query($con,$sql);
$result = mysqli_fetch_array($r);
header('content-type: image/jpeg');
echo base64_decode($result['image']);
mysqli_close($con);
} else {
echo "Error";
}
And for get all the images
getAllImages.php
require_once('dbConnect.php');
$sql = "SELECT id FROM photos";
$res = mysqli_query($con, $sql);
$result = array();
$url = "http://imzzycool.biz.ht/PhotoUpload/getImage.php?id=";
while ($row = mysqli_fetch_array($res)) {
array_push($result, array('url' => $url . $row['id']));
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
It just replaces image get downloaded but image is not visible
I am trying to populate some items from PHP to Android using ListView
public class ChooseCategory extends ListActivity {
private ListView lv;
ArrayAdapter<FoodStores> arrayAdapter;
private static final String TAG = MainActivity.class.getSimpleName();
private ArrayList<FoodStores> storefoodList;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private String URL_STORES = "http://www.123.com/get_stores.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
//lv = (ListView) findViewById(R.id.list_item);
lv = (ListView)findViewById(android.R.id.list);
storefoodList = new ArrayList<FoodStores>();
new GetFoodStores().execute();
arrayAdapter = new ArrayAdapter<FoodStores> (this,R.layout.restaurant_list,storefoodList );
private class GetFoodStores extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandlerFood jsonParserFood = new ServiceHandlerFood();
String json = jsonParserFood.makeServiceCall(URL_STORES, ServiceHandlerFood.GET);
Log.e("Response: ", " > " + json);
if(json != null){
try{
JSONObject jsonObj = new JSONObject(json);
if(jsonObj != null){
JSONArray storeListFood = jsonObj.getJSONArray("storelistfood");
for(int i = 0; i < storeListFood.length(); i++){
JSONObject storeFoodObj = (JSONObject) storeListFood.get(i);
FoodStores foodStores = new FoodStores(storeFoodObj.getInt("id"),storeFoodObj.getString("STORENAME"));
storefoodList.add(foodStores);
}
}
}catch(JSONException e){
e.printStackTrace();
}
}else{
Log.e("JSON Data", "No data received from server");
}
return null;
}
#Override
protected void onPostExecute(Void result){
super.onPostExecute(result);
lv.setAdapter(arrayAdapter);
}
}
}
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"
tools:context="{relativePackage}.${activityClass}" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
restaurant_list.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<ImageView
android:id="#+id/icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:src="#drawable/nasilemak2" />
<TextView
android:id="#+id/Itemname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:paddingTop="5dp"/>
</LinearLayout>
The error that I got is that it only shows blank screen and it crashed after a minute. I would like to populate the ListView using ArrayList from PHP.
You didn't provide all classes so some classes are provided by me.
Here you are:
ChooseCategory.java:
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ChooseCategory extends ListActivity {
private ListView lv;
ArrayAdapter<FoodStores> arrayAdapter;
private static final String TAG = "XXX";
private ArrayList<FoodStores> storefoodList;
// JSON parser class
// JSONParser jsonParser = new JSONParser();
// ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private String URL_STORES = "http://echo.jsontest.com/id/1/STORENAME/Perogi";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(android.R.id.list);
storefoodList = new ArrayList<FoodStores>();
new GetFoodStores().execute();
arrayAdapter = new ArrayAdapter<FoodStores>(this,
R.layout.restaurant_list, R.id.Itemname, storefoodList);
lv.setAdapter(arrayAdapter);
}
private class GetFoodStores extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandlerFood jsonParserFood = new ServiceHandlerFood();
String json = jsonParserFood.makeServiceCall(URL_STORES,
"TEST");
//ServiceHandlerFood.GET);
Log.e("Response: ", " > " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray storeListFood = jsonObj
.getJSONArray("storelistfood");
for (int i = 0; i < storeListFood.length(); i++) {
JSONObject storeFoodObj = (JSONObject) storeListFood
.get(i);
FoodStores foodStores = new FoodStores(
storeFoodObj.getInt("id"),
storeFoodObj.getString("STORENAME"));
storefoodList.add(foodStores);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "No data received from server");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
lv.setAdapter(arrayAdapter);
}
}
}
Foodstores.java:
public class FoodStores {
int id;
String name;
public FoodStores(int id, String string) {
this.id=id;
name=string;
}
#Override
public String toString(){
return name;
}
}
ServiceHandlerFood.java:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
public class ServiceHandlerFood {
public static final String GET = "GET";
public String makeServiceCall(String uRL_STORES, String get2) {
if ("TEST".equals(get2))
return "{'storelistfood':[{'id':1, 'STORENAME':'Arbys'},{'id':2, 'STORENAME':'Perogi'},{'id':3, 'STORENAME':'McDonalds'}]}";
DefaultHttpClient httpclient = new DefaultHttpClient(
new BasicHttpParams());
HttpPost httppost = new HttpPost(uRL_STORES);
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (Exception squish) {
}
}
return result;
}
}
The rest of files was untouched.
Move this line in onPost method:
arrayAdapter = new ArrayAdapter<FoodStores> `(this,R.layout.restaurant_list,storefoodList );`
Like this
#Override
protected void onPostExecute(Void result){
super.onPostExecute(result);
arrayAdapter = new ArrayAdapter<FoodStores> (this,R.layout.restaurant_list,storefoodList );
lv.setAdapter(arrayAdapter);
}
Edit :
And change "this" to getApplicationContext() like this
arrayAdapter = new ArrayAdapter<FoodStores> (getApplicationContext(),R.layout.restaurant_list,storefoodList );
Edit 1:
Replace the following to
lv = (ListView)findViewById(android.R.id.list);
this
lv = (ListView)findViewById(R.id.list);
The main problem with your code is, the default implementation of the ArrayAdapter needs a TextView in which it will display its list items as strings. If not provided, it will throw exception like
06-22 21:22:42.535: E/AndroidRuntime(6531): FATAL EXCEPTION: main
06-22 21:22:42.535: E/AndroidRuntime(6531):
java.lang.IllegalStateException: ArrayAdapter requires the resource ID
to be a TextView 06-22 21:22:42.535: E/AndroidRuntime(6531): at
android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:386)
06-22 21:22:42.535: E/AndroidRuntime(6531): at
android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
The simplest solution will be to just replace
arrayAdapter = new ArrayAdapter<FoodStores> (this,R.layout.restaurant_list,storefoodList );
with
arrayAdapter = new ArrayAdapter<FoodStores> (this,R.layout.restaurant_list,R.id.Itemname,storefoodList);
Please note the additional parameter R.id.Itemname which is the TextView in your layout that the ArrayAdapter needs to display the content.
Please also remember to override the toString() method in your FoodStores to return some logical string like the name if not done already (as suggested by #Alex above).
Hope this helps.
I`m not sure about it, but this line is not good,because:
storefoodList = new ArrayList<FoodStores>();
new GetFoodStores().execute();
arrayAdapter = new ArrayAdapter<FoodStores> (this,R.layout.restaurant_list,storefoodList );
You give an empty arrayList to the adapter, because AsyncTaks is still loading the content. So in this case, the adapter cache an empty list, and its going to provide to the listview when you call the lw.setAdapter(adapter) at onPostExecute.
If you wouldnt like to change the architecture of your app then,You should call notifydatasetchanged() after you set the adapter in onPostExecute.
OR you can initialize the adapter with the updated list, onPostExecute, and set it to the ListView.
I see 3 problems here
you need to create a custom adapter that extends from
ArrayAdapter
you cannot use ArrayAdapter directly [enter link description here][1] [1]:
http://developer.android.com/reference/android/widget/ArrayAdapter.html
either need to create the array adapter in onPostExecute or you
need to tell your adapter that arraylist haschanged
if your
activity extends listactivity then as you did listview's id in xml
should be #android:id/list but then ListView lv = getListView() or
your activity just extends Activity and listview's id is in xml
should be #+id/list then ListView lv =
(ListView)findViewById(R.id.list)
try to implement image with Picasso and do more one thing that please do have any other web service so please check this web service in this code so it will clear that the code will working correctly or not. After that that will be more easily for you. do let me know if any.