Null Pointer Exception - trying to Retrieve Data from PHPMYADMIN server - android

I am writing an App in which i am trying to fetch previous Order Details from Server PHPMYADMIN, and want to show these order details in ListView, but whenever i run my app getting NullPointerException, please check my code and tell me what i am missing and where i am doing mistake..
Log says:
05-22 12:33:35.652: E/AndroidRuntime(786): Caused by: java.lang.NullPointerException
05-22 12:33:35.652: E/AndroidRuntime(786): at OrdersActivity.showInfo(OrdersActivity.java:121)
05-22 12:33:35.652: E/AndroidRuntime(786): at OrdersActivity.onCreate(OrdersActivity.java:75)
05-22 12:33:35.652: E/AndroidRuntime(786): at android.app.Activity.performCreate(Activity.java:5104)
05-22 12:33:35.652: E/AndroidRuntime(786): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
05-22 12:33:35.652: E/AndroidRuntime(786): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
05-22 12:33:35.652: E/AndroidRuntime(786): ... 11 more
Error Line Number 75 is : showinfo();
Error Line Number 121 is : if(!strMemberID.equals(""))
OrdersActivity.java:
public class OrdersActivity extends Activity {
TextView total, items ;
String strMemberID,resultServer,MemberID;
ListView list;
OrdersAdapter adapter;
ArrayList<HashMap<String, String>> itemsList;
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_orders);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
showInfo();
itemsList = new ArrayList<HashMap<String, String>>();
list = (ListView) findViewById(R.id.listView1);
adapter = new OrdersAdapter(this, itemsList);
list.setAdapter(adapter);
if (isNetworkAvailable()) {
new MyAsyncTask().execute();
} else {
AlertDialog alertDialog = new AlertDialog.Builder(OrdersActivity.this).create();
alertDialog.setMessage("The Internet connection appears to be offline.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
public void showInfo()
{
total = (TextView)findViewById(R.id.txtTotalAmount);
items = (TextView)findViewById(R.id.txtItemDetails);
String url = "http://172.16.0.4/res/order_fetch.php";
Intent intent= getIntent();
MemberID = intent.getStringExtra("MemberID");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("sMemberID", MemberID));
resultServer = getHttpPost(url,params);
String strTotal = "";
String strItems = "";
JSONObject c;
try {
c = new JSONObject(resultServer);
strTotal = c.getString("TotalAmount");
strItems = c.getString("ItemDetails");
if(!strMemberID.equals(""))
{
total.setText(strTotal);
items.setText(strItems);
}
else
{
total.setText("-");
items.setText("-");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getHttpPost(String url,List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
private boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
return (info != null);
}
class MyAsyncTask extends
AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
private ProgressDialog progressDialog = new ProgressDialog(
OrdersActivity.this);
#Override
protected void onPreExecute() {
progressDialog.setMessage("Loading, Please wait.....");
progressDialog.show();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
list = (ListView) findViewById(R.id.listView1);
adapter = new OrdersAdapter(OrdersActivity.this, itemsList);
list.setAdapter(adapter);
this.progressDialog.dismiss();
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
}
}
OrdersAdapter.java:
public class OrdersAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
String strName,strMemberID ;
public OrdersAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.listrow_orders, null);
TextView title = (TextView)vi.findViewById(R.id.txtTotalAmount);
TextView description = (TextView)vi.findViewById(R.id.txtItemDetails);
HashMap<String, String> item = new HashMap<String, String>();
item = data.get(position);
title.setText(item.get(strName));
description.setText(strMemberID);
return vi;
}
}

Declare your strMemberID as String strMemberID = "";
NullPointorException will be solved... :)

The default initialization for the String type, when it is declared in the Class scope, is null. That's mean that you can not use before intialize it. You can change the if this way:
if(strMemberID != null && !strMemberID.equals("")) {
}

Related

ANDROID - How to use custom adapter to add jsonObject from API webservices?

is there a way to use custom adapter with jsonArray obtained from a specific link?
I getting error when I run my app with my code, what should i do??
I've tried to find a way how to do, but the examples given too scrimpy, that's why I need help here,
I've tried this code to do :
Pertanyaan.java
public class Pertanyaan {
private float ratingStar;
private String ask;
Pertanyaan(int ratingStar, String ask) {
this.ratingStar = ratingStar;
this.ask = ask;
}
float getRatingStar() {
return 0;
}
void setRatingStar(float ratingStar) {
this.ratingStar = ratingStar;
}
public String getAsk() {
return ask;
}
public void setAsk(String ask) {
this.ask = ask;
}
}
PertanyaanAdapter.java
class PertanyaanAdapter extends ArrayAdapter<Pertanyaan> {
private AppCompatActivity activity;
private List<Pertanyaan> movieList;
PertanyaanAdapter(AppCompatActivity context, int resource, List<Pertanyaan> objects) {
super(context, resource, objects);
this.activity = context;
this.movieList = objects;
}
#Override
public Pertanyaan getItem(int position) {
return movieList.get(position);
}
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_listview, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
//holder.ratingBar.getTag(position);
}
holder.ratingBar.setOnRatingBarChangeListener(onRatingChangedListener(position));
holder.ratingBar.setTag(position);
holder.ratingBar.setRating(getItem(position).getRatingStar());
holder.movieName.setText(getItem(position).getAsk());
return convertView;
}
private RatingBar.OnRatingBarChangeListener onRatingChangedListener(final int position) {
return new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
Pertanyaan item = getItem(position);
assert item != null;
item.setRatingStar(v);
Log.i("Adapter", "star: " + v);
}
};
}
private static class ViewHolder {
private RatingBar ratingBar;
private TextView movieName;
ViewHolder(View view) {
ratingBar = (RatingBar) view.findViewById(R.id.rate_img);
movieName = (TextView) view.findViewById(R.id.text);
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<Pertanyaan> listPertanyaan;
ArrayAdapter<Pertanyaan> adapter2;
ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.list_view);
getpertanyaan get= new getpertanyaan();
get.execute();
adapter2 = new PertanyaanAdapter(this, R.layout.item_listview, listPertanyaan);
listView.setOnItemClickListener(onItemClickListener());
}
private AdapterView.OnItemClickListener onItemClickListener() {
}
private class getpertanyaan extends AsyncTask<Void, Void, Integer> {
ArrayList<Pertanyaan> list;
protected void onPreExecute() {
pDialog=new ProgressDialog(MainActivity.this);
pDialog.setTitle("Nama Dosen");
pDialog.setMessage("Menampilkan nama dosen... Mohon tunggu...!");
pDialog.setCancelable(false);
pDialog.show();
super.onPreExecute();
list = new ArrayList<>();
}
#Override
protected Integer doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://flix.16mb.com/send_data.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
//convert response to string
try {
BufferedReader reader = null;
if (is != null) {
reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
}
String line;
if (reader != null) {
while ((line = reader.readLine()) != null) {
result += line;
}
}
if (is != null) {
is.close();
}
//result=sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
list.add(new Pertanyaan(0,jsonObject.getString("ask")));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Integer result) {
if (pDialog.isShowing())
pDialog.dismiss();
listPertanyaan.addAll(list);
adapter2.notifyDataSetChanged();
}
}
EDIT :
Error from logcat :
FATAL EXCEPTION: main
Process: flix.yudi.pertanyaan3, PID: 23836
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.addAll(java.util.Collection)' on a null object reference
at flix.yudi.pertanyaan3.MainActivity$getpertanyaan.onPostExecute(MainActivity.java:156)
at flix.yudi.pertanyaan3.MainActivity$getpertanyaan.onPostExecute(MainActivity.java:92)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
Your problem is that your ArrayList is not initialized. It crashs at this point:
protected void onPostExecute(Integer result) {
if (pDialog.isShowing())
pDialog.dismiss();
listPertanyaan.addAll(list); // CRASH!
adapter2.notifyDataSetChanged();
}
To explain more, like we discussed in the comments, what you have done is to creating a new ArrayList in your asyncTask:
private class getpertanyaan extends AsyncTask<Void, Void, Integer> {
ArrayList<Pertanyaan> list; //NEW ARRAYLIST
protected void onPreExecute() {
pDialog=new ProgressDialog(MainActivity.this);
pDialog.setTitle("Nama Dosen");
pDialog.setMessage("Menampilkan nama dosen... Mohon tunggu...!");
pDialog.setCancelable(false);
pDialog.show();
super.onPreExecute();
list = new ArrayList<>();//NEW ARRAYLIST INITIALIZING
}
but still not have initialized listPertanyaan . Wether you have to use the new created arrayList like:
list.addAll(list);
in your onPostExecute(), or you have to initialize the listPertanyaan before like
listPertanyaan = new ArrayList<Pertanyaan>();
EDIT
For your second question, you should initialize your adapter and set it to listView in onPostExecute() after you get filled the arrayList. It should look like:
protected void onPostExecute(Integer result) {
if (pDialog.isShowing())
pDialog.dismiss();
listPertanyaan.addAll(list);
adapter2 = new PertanyaanAdapter(this, R.layout.item_listview, listPertanyaan);
listView.setAdapter(adapter2);
}

Android: JSON parse: null object reference when attempting to parse JSON into a ListView

This app is supposed to parse some JSON data (hard coded for now) from the Google Books API, and pass an ArrayList of Books to the adapter that will display it on a ListView. The problem I have is that the JSON parse is returning null instead of the parsed data.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ProgressBar pBar;
List<MyTask> tasks;
ArrayList<Book> bookList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pBar = (ProgressBar) findViewById(R.id.progressBar);
pBar.setVisibility(View.INVISIBLE);
Button sButton = (Button) findViewById(R.id.s_button);
sButton.setOnClickListener(this);
tasks = new ArrayList<>();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.s_button: {
if (isOnline()) {
new MyTask().execute("https://www.googleapis.com/books/v1/volumes?q=millionare"); //https://www.googleapis.com/books/v1/volumes?q=soft+skills
} else {
Toast.makeText(this, "Connection failed", Toast.LENGTH_LONG).show();
}
break;
}
}
}
protected boolean isOnline() {
ConnectivityManager connectManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connectManager.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return HttpManager.getData(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
#Override
protected void onPostExecute(String result) {
bookList = BookJSONParser.parseFeed(result);
updateDisplay();
}
}
protected void updateDisplay() {
BookAdapter adapter = new BookAdapter(this, bookList);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
}
public class BookJSONParser {
public static ArrayList<Book> parseFeed(String content) {
try {
JSONArray jsonArray = new JSONArray(content);
ArrayList<Book> bookList = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String name = object.getString("title").toString();
Book book = new Book(name);
bookList.add(book);
}
return bookList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}
public class BookAdapter extends ArrayAdapter<Book> {
public BookAdapter(Context context, ArrayList<Book> bookList) {
super(context, 0, bookList);
}
#Override
public View getView(int position, View convertedView, ViewGroup parent) {
View listItemView = convertedView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Book currentBook = getItem(position);
TextView locationName = (TextView) listItemView.findViewById(R.id.book_title);
locationName.setText(currentBook.getTittle());
TextView locationAddress = (TextView) listItemView.findViewById(R.id.book_author);
locationAddress.setText(currentBook.getAuthor());
return listItemView;
}
}
public class HttpManager {
public static String getData(String myUrl) throws IOException {
// BufferedReader reader = null;
InputStream inputStream = null;
int len = 10000;
try {
URL url = new URL(myUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(10000 /* milliseconds */);
connection.setConnectTimeout(15000 /* milliseconds */);
connection.setRequestMethod("GET");
connection.setDoInput(true);
// Starts the query
connection.connect();
int response = connection.getResponseCode();
inputStream = connection.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(inputStream, len);
return contentAsString;
// Makes sure that the InputStream inputStream closed after the app inputStream
// finished using it.
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
// Reads an InputStream and converts it to a String.
public static String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}
public class Book {
private String mTittle;
/**
* This is the constructor.
* #param title is the book title being passed in.
*/
public Book(String title) {
mTittle = title;
}
public String getTittle() {
return mTittle;
}
public void setTittle(String tittle) {
mTittle = tittle;
}
}
FATAL EXCEPTION: main
Process: com.narvin.android.booklisting, PID: 3278
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
at android.widget.ListView.setAdapter(ListView.java:502)
at com.narvin.android.booklisting.MainActivity.updateDisplay(MainActivity.java:113)
at com.narvin.android.booklisting.MainActivity$MyTask.onPostExecute(MainActivity.java:100)
at com.narvin.android.booklisting.MainActivity$MyTask.onPostExecute(MainActivity.java:79)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
The issue is that one of the arguments in BookAdapter adapter = new BookAdapter(this, bookList); is null for some reason. Try passing bookList as an argument to updateDisplay and checking whether it's not null.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ProgressBar pBar;
List<MyTask> tasks;
ArrayList<Book> bookList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pBar = (ProgressBar) findViewById(R.id.progressBar);
pBar.setVisibility(View.INVISIBLE);
Button sButton = (Button) findViewById(R.id.s_button);
sButton.setOnClickListener(this);
tasks = new ArrayList<>();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.s_button: {
if (isOnline()) {
new MyTask().execute("https://www.googleapis.com/books/v1/volumes?q=millionare"); //https://www.googleapis.com/books/v1/volumes?q=soft+skills
} else {
Toast.makeText(this, "Connection failed", Toast.LENGTH_LONG).show();
}
break;
}
}
}
protected boolean isOnline() {
ConnectivityManager connectManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = connectManager.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return HttpManager.getData(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
#Override
protected void onPostExecute(String result) {
ArrayList<Book> bookList = BookJSONParser.parseFeed(result);
updateDisplay(bookList);
}
}
protected void updateDisplay(ArrayList<Book> bookList) {
if (bookList != null){
BookAdapter adapter = new BookAdapter(this, bookList);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
}
}
It would appear you are getting a JSONParseException... therefore causing a NullPointerExpcetion for the List into the Adapter
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
That is your error, here is how you get it
public static ArrayList<Book> parseFeed(String content) {
try {
JSONArray jsonArray = new JSONArray(content); // <-- Throws an error
ArrayList<Book> bookList = new ArrayList<>();
// Stuff...
return bookList;
} catch (JSONException e) {
e.printStackTrace();
return null; // <----- Null is returned
}
And you use that null value here
#Override
protected void onPostExecute(String result) {
bookList = BookJSONParser.parseFeed(result);
updateDisplay();
}
Followed by
protected void updateDisplay() {
BookAdapter adapter = new BookAdapter(this, bookList); // <-- Null here
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
So, the way to fix that NullPointerExpception is to always return an ArrayList
ArrayList<Book> bookList = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(content);
// Stuff...
} catch (JSONException e) {
e.printStackTrace();
}
return bookList;
to get json string from url you should do it like that
String content = new MyTask()
.execute("https://www.googleapis.com/books/v1/volumes?q=millionare")
.get();
//pass the content to BookJSONParser class
booklist = new BookJSONParser().parseFeed(content);
updateDisplay();
what you get from the url you provided is NOT jsonArray it's a jsonobject
so I think this code will work "assuming that you did everything else correctly"
JSONObject o = new JSONObject(content);
JSONArray jsonArray = o.getJSONArray("items");
the you can do the for loop

onResume Does Not Update ListView With New Data

I am trying to update a ListView on previous fragment after back button press. The onResume is called (verified with Toast) and the webservice runs (listView is displayed after it is cleared). The problem is that the ListView is still showing old values and not new value after accessWebService_getUsername is called. I verify the values from MySQL and even though the DB is updated, the ListView only returns old values.
#Override
public void onResume() {
Toast.makeText(getActivity(), "onResume", Toast.LENGTH_SHORT).show();
super.onResume();
adapter.clear();
getIMEI();
accessWebService_getUsername();
adapter.notifyDataSetChanged();
}
Update:
//ListView
ListView lv =(ListView)view.findViewById(R.id.listView);
adapter = new ContactsAdapter(getActivity(), arrRequest_Contact, arrRequest_NameSurname, arrRequest_MessageCount, arrRequest_Time, arrRequest_Image);
lv.setAdapter(adapter);
// Json
private class JsonGetUsername extends AsyncTask<String, Void, String> {
//Pending 01
private ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPreExecute() {
this.dialog.setMessage("Loading Contacts, Please Wait");
this.dialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getActivity(),"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
//Pending 02
if (dialog.isShowing()) {
dialog.dismiss();
}
adapter.notifyDataSetChanged();
try{
ListDrawer_getUsername(); //has ConnectionException (when it cannot reach server)
}catch (Exception e){
Toast.makeText(getActivity(), "Please check your connection..", Toast.LENGTH_LONG).show();
}
}
}// end async task
public void accessWebService_getUsername() {
JsonGetUsername task = new JsonGetUsername();
// passes values for the urls string array
task.execute(new String[] { "http://mywebsite/php/get_username.php?pIMEI="+IMEI});
}
// build hash set for list view
public void ListDrawer_getUsername() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("username_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
request_username = jsonChildNode.optString("Username");
}
accessWebService_getContacts();
} catch (JSONException e) {
System.out.println("Json Error Rooms" +e.toString());
//Toast.makeText(getApplicationContext(), "No Rooms To Load", Toast.LENGTH_SHORT).show();
}
}
UPDATE 2:
//ContactsAdpater
class ContactsAdapter extends ArrayAdapter<String>
{
Context context;
List<String> Request_Contact;
List<String> Request_NameSurname;
List<String> Request_MessageCount;
List<String> Request_Time;
List<String> Request_Image;
ContactsAdapter(Context c, List<String> Request_Contact, List<String> Request_NameSurname, List<String> Request_MessageCount, List<String> Request_Time, List<String> Request_Image)
{
super(c, R.layout.activity_contacts_single, R.id.textContact, Request_Contact);
this.context=c;
this.Request_Contact=Request_Contact;
this.Request_NameSurname=Request_NameSurname;
this.Request_MessageCount=Request_MessageCount;
this.Request_Time=Request_Time;
this.Request_Image=Request_Image;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row=convertView;
if(row==null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.activity_contacts_single, parent, false);
}
TextView txtContact = (TextView) row.findViewById(R.id.textContact);
TextView txtNameSurname = (TextView) row.findViewById(R.id.textNameSurname);
TextView txtMessageCount = (TextView) row.findViewById(R.id.textMessageCount);
TextView txtTime = (TextView) row.findViewById(R.id.textTime);
ImageView imageView = (ImageView) row.findViewById(R.id.imageView);
txtContact.setText(Request_Contact.get(position));
txtNameSurname.setText(Request_NameSurname.get(position));
txtMessageCount.setText(Request_MessageCount.get(position));
txtTime.setText(Request_Time.get(position));
Picasso.with(context).load(arrRequest_Image.get(position)).transform(new CircleTransform()).placeholder(R.drawable.ic_launcher).into(imageView);
return row;
}
}
You'll need to override the clear method in your ContactsAdapter to actually clear the lists you are storing your data in.
It looks like you'll need to clear all your lists, so if you add this to ContactsAdapter, your code should work as expected:
#Override
public void clear() {
super.clear();
Request_Contact.clear();
Request_NameSurname.clear();
Request_MessageCount.clear();
Request_Time.clear();
Request_Image.clear();
}

My app crashes after I use doInBackground(Object... arg0)

Everything was fine until I used doInBackground(Object... arg0) inorder to show ProgressDialog until it is loaded then dismisses it on onPostExecute(Object result) method. No error message in a LogCat, just crashes. Please help?
Vacancy.java
package com.apps.vacancy;
//all the necessary imports are imported
public class Vacancy extends Activity {
public static String urlPageNumHolder;
public ProgressDialog dialog;
ListView lisView1;
EditText inputText;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vacancy);
lisView1 = (ListView) findViewById(R.id.listView1);
inputText = (EditText) findViewById(R.id.editText1);
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final Button btn1 = (Button) findViewById(R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
searchJob();
}
});
}
public void searchJob() {
new LoadContentFromServer().execute();
dialog = ProgressDialog.show(this, "Vacancy", "Loading...", true, false);
}
public String getJSONUrl(String url, List<NameValuePair> params) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Download OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download file..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
class LoadContentFromServer extends AsyncTask<Object, Integer, Object> {
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Object... arg0) {
String url = "http://10.0.2.2/android/smartaddis/mobile/vacancy/getVacancy.php";
// Paste Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("txtKeyword", inputText.getText().toString()));
try {
JSONArray data = new JSONArray(getJSONUrl(url, params));
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("id", c.getString("id"));
map.put("title_en", c.getString("title_en"));
map.put("description_en", c.getString("description_en"));
map.put("posteddate", c.getString("posteddate"));
map.put("expiredate", c.getString("expiredate"));
MyArrList.add(map);
}
lisView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView,
int position, long mylng) {
urlPageNumHolder = MyArrList.get(position).get("id").toString();
Intent subActivity = new Intent(Vacancy.this,
VacancyWebber.class);
Bundle translateBundle = ActivityOptions
.makeCustomAnimation(Vacancy.this,
R.anim.slide_in_left, R.anim.slide_out_left).toBundle();
startActivity(subActivity, translateBundle);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
return MyArrList;
}
#Override
protected void onPostExecute (ArrayList<HashMap<String, String>> result) {
if (dialog != null)
dialog.dismiss();
SimpleAdapter sAdap = new SimpleAdapter(Vacancy.this, result,
R.layout.vacancy_column, new String[] { "title_en",
"description_en", "posteddate", "expiredate" }, new int[] { R.id.jobtitle,
R.id.jobdescription, R.id.jobdateTime, R.id.jobexpiredate });
lisView1.setAdapter(sAdap);
}
}
#Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);
}
}
You are updating ui from doInbackground which you should not do. Return the result in doInbackground and update ui in onPostExecute.
In doInbackground return MyArrList. The result of background computation is a passed to onPostExecute.
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Object... params) {
// TODO Auto-generated method stub
ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
... // rest of the code
return MyArrList;
}
In onPostExecute initialize adapter and set the adapter to listview.
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// dimiss dialog
SimpleAdapter sAdap = new SimpleAdapter(Vacancy.this, result,
R.layout.vacancy_column, new String[] { "title_en",
"description_en", "posteddate", "expiredate" }, new int[] { R.id.jobtitle,
R.id.jobdescription, R.id.jobdateTime, R.id.jobexpiredate });
lisView1.setAdapter(sAdap);
... // rest of the code
}
For more info
http://developer.android.com/reference/android/os/AsyncTask.html
You also need to move the below inside onCreate after setContentView coz findViewById looks for a view in the current inflated layout.
ListView lisView1;
EditText inputText;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vacancy);
lisView1 = (ListView) findViewById(R.id.listView1);
inputText = (EditText) findViewById(R.id.editText1);

Load Images from url in Android

I am trying to load images from url and set in to gridview, when i scroll my screen images changes. I am a beginner in android. I don't know what is the problem in my code.
Here is my code..
public class Photos extends Activity {
public static final String TAG_IMAGE_NAME = "image_name";
public static final String TAG_IMAGE_THUMB_NAME = "image_thumb_name";
public static String URL = "http://...../..../..../mainAPI.php";
ArrayList<HashMap<String, String>> photoList;
String responseData = null;
static GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photos);
gridView = (GridView)findViewById(R.id.gridView);
photoList = new ArrayList<HashMap<String,String>>();
new AsyncData().execute();
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Sending image id to FullScreenActivity
Intent i = new Intent(getApplicationContext(), FullImage.class);
// passing array index
i.putExtra("ImageName", TAG_IMAGE_NAME);
startActivity(i);
}
});
}
class AsyncData extends AsyncTask<String, Void, Void> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(Photos.this);
pDialog.setTitle("Loading....");
pDialog.setMessage("Please wait...");
pDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... args) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("rquest","{\"method\":\"photogallery\",\"body\":[{}]}"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
responseData = EntityUtils.toString(resEntity);
try {
JSONArray data = new JSONArray(responseData);
for (int i = 0; i < data.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = data.getJSONObject(i);
String photoName = c.getString(TAG_IMAGE_NAME);
String imageThumbName = c.getString(TAG_IMAGE_THUMB_NAME);
map.put(TAG_IMAGE_NAME, photoName);
map.put(TAG_IMAGE_THUMB_NAME, imageThumbName);
photoList.add(map);
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
gridView.setAdapter(new PhotosAdapter(Photos.this, R.layout.photo_row, photoList));
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
{
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
PhgotosAdapter Class
public class PhotosAdapter extends ArrayAdapter<HashMap<String, String>>{
Context context;
String uri;
Bitmap bitmap;
ArrayList<HashMap<String, String>> myList;
HashMap<String, String> myData;
int layout;
public PhotosAdapter(Context context, int textViewResourceId, List<HashMap<String, String>> objects) {
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
this.context = context;
this.myList = (ArrayList<HashMap<String, String>>) objects;
this.layout = textViewResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = null;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layout, parent, false);
myData = myList.get(position);
ImageView image = (ImageView)row.findViewById(R.id.imagePhoto);
try{
ImageDownloadTask task = new ImageDownloadTask(image);
task.execute();
uri = "" + myData.get(Photos.TAG_IMAGE_THUMB_NAME).replace(" ", "%20");
image.setImageBitmap(bitmap);
image.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return row;
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
class ImageDownloadTask extends AsyncTask<Void, Integer, Bitmap> {
private ImageView mView;
ProgressDialog pDialog;
ImageDownloadTask(ImageView view){
mView = view;
}
#Override
protected Bitmap doInBackground(Void... params) {
try {
bitmap = getBitmapFromURL(uri);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
mView.setImageBitmap(result);
}
}
}
I don't know what is the problem in it, Please Help me and give some solution.
ImageLoader imageLoader;
imageLoader=new ImageLoader(context.getApplicationContext());
imageLoader.DisplayImage(urlname, imageViewname);
try it

Categories

Resources