I have a viewPager to appear 3 fragments, the first is a ListFragment, this is the code:
MainActivity's code:
package info.androidhive.tabsswipe;
import info.androidhive.tabsswipe.adapter.TabsPagerAdapter;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "My interventions", "MAP", "My report" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
FragmentList's code:
package info.androidhive.tabsswipe;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
public class TopRatedFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.fragment_top_rated,
container, false);
return myFragmentView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
ArrayList<HashMap<String, String>> interventionsList;
// Progress Dialog
private ProgressDialog pDialog;
// url to get all interventions list
private static String url_all_interventions = "http://10.0.2.2/Scripts/liste_interventions.php";
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
// interventions JSONArray
JSONArray interventions = null;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.getListView().setTextFilterEnabled(true);
// Hashmap for ListView
interventionsList = new ArrayList<HashMap<String, String>>();
// Loading interventions in Background Thread
new LoadAllInterventions().execute();
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllInterventions extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading interventions. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONArray json = jParser.makeHttpRequest(url_all_interventions, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Interventions: ", json.toString());
try {
// Getting Array of interventions
JSONArray interventions = json;
// looping through All interventions
for (int i = 0; i < interventions.length(); i++) {
JSONObject c = interventions.getJSONObject(i);
// Storing each json item in variable
String id = c.getString("id");
String name = c.getString("name");
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("Int_id", id);
map.put("Int_name", name);
// adding HashList to ArrayList
interventionsList.add(map);
}
} catch (JSONException e) {e.printStackTrace();}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), interventionsList,
R.layout.list_item, new String[] { "Int_id",
"Int_name"},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
Log.e("LIST", "setListAdapter is done");
}
});
}
}
public void runOnUiThread(Runnable runnable) {
// TODO Auto-generated method stub
}
}
this is the JSONParser class's code:
package info.androidhive.tabsswipe;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONArray jArr = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONArray makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON array
try {
jArr = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jArr;
}
}
this is the class TabsPagerAdapter's code:
package info.androidhive.tabsswipe.adapter;
import info.androidhive.tabsswipe.GamesFragment;
import info.androidhive.tabsswipe.MoviesFragment;
import info.androidhive.tabsswipe.TopRatedFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new TopRatedFragment();
case 1:
// Games fragment activity
return new GamesFragment();
case 2:
// Movies fragment activity
return new MoviesFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
and this is MoviesFragment's code: "Edited"
package info.androidhive.tabsswipe;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class MoviesFragment extends Fragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button ajout=(Button)getActivity().findViewById(R.id.button1);
ajout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText code=(EditText)getActivity().findViewById(R.id.editText1);
EditText lib=(EditText)getActivity().findViewById(R.id.editText2);
EditText desc=(EditText)getActivity().findViewById(R.id.editText3);
EditText st=(EditText)getActivity().findViewById(R.id.editText4);
EditText act=(EditText)getActivity().findViewById(R.id.editText5);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
StringBuffer adresse= new StringBuffer("http://10.0.2.2:8080/Scripts/Create_Rapport.php?");
adresse.append("code="+code.getText().toString());
adresse.append("&lib="+lib.getText().toString());
adresse.append("&desc="+desc.getText().toString());
adresse.append("&state="+st.getText().toString());
adresse.append("&action="+act.getText().toString());
getPage(adresse.toString());
}});
}
public void getPage(String adresse) {
new Requete().execute(adresse);
}
private class Requete extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
}
catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
}
}
When i run the application, first the first fragment which containt the list populated from the database appear and no data in the fragment, when i swipe from this fragment to an other fragment, the application close and this error appear on the LogCat:
D/All Interventions:(1066): [{"id":"2","name":"request 2"},{"id":"1","name":"request 1"}]
10-26 16:53:54.677:
I/Choreographer(1066): Skipped 122 frames! The application may be doing too much work on its main thread.
10-26 16:54:13.732:
D/AndroidRuntime(1066): Shutting down VM
10-26 16:54:13.737:
W/dalvikvm(1066): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
10-26 16:54:13.887:
E/AndroidRuntime(1066): FATAL EXCEPTION: main
10-26 16:54:13.887:
E/AndroidRuntime(1066): java.lang.NullPointerException
10-26 16:54:13.887:
E/AndroidRuntime(1066): at info.androidhive.tabsswipe.MoviesFragment.onActivityCreated(MoviesFragment.java:26)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1486)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:550)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:509)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:490)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at info.androidhive.tabsswipe.MainActivity.onTabSelected(MainActivity.java:70)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at com.android.internal.app.ActionBarImpl.selectTab(ActionBarImpl.java:579)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at com.android.internal.app.ActionBarImpl$TabImpl.select(ActionBarImpl.java:1081)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at com.android.internal.widget.ScrollingTabContainerView$TabClickListener.onClick(ScrollingTabContainerView.java:519)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.view.View.performClick(View.java:4204)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.view.View$PerformClick.run(View.java:17355)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.os.Handler.handleCallback(Handler.java:725)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.os.Handler.dispatchMessage(Handler.java:92)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.os.Looper.loop(Looper.java:137)
10-26 16:54:13.887:
E/AndroidRuntime(1066): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-26 16:54:13.887
This is MovieFragment's code, please what is the error's cause ??
package info.androidhive.tabsswipe;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class MoviesFragment extends Fragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button ajout=(Button)getActivity().findViewById(R.id.button1);
ajout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EditText code=(EditText)getActivity().findViewById(R.id.editText1);
EditText lib=(EditText)getActivity().findViewById(R.id.editText2);
EditText desc=(EditText)getActivity().findViewById(R.id.editText3);
EditText st=(EditText)getActivity().findViewById(R.id.editText4);
EditText act=(EditText)getActivity().findViewById(R.id.editText5);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());
StringBuffer adresse= new StringBuffer("http://10.0.2.2:8080/Scripts/Create_Rapport.php?");
adresse.append("code="+code.getText().toString());
adresse.append("&lib="+lib.getText().toString());
adresse.append("&desc="+desc.getText().toString());
adresse.append("&state="+st.getText().toString());
adresse.append("&action="+act.getText().toString());
getPage(adresse.toString());
}});
}
public void getPage(String adresse) {
new Requete().execute(adresse);
}
private class Requete extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
}
catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
}
}
Related
i have a list in my PostgreSql Data Base that i want it to appear in 1 of my 3 viewPager Fragment,
this is the mainActivity code of my application:
package info.androidhive.tabsswipe;
import info.androidhive.tabsswipe.adapter.TabsPagerAdapter;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Top Rated", "Games", "Movies" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
This is the ListFragment code:
package info.androidhive.tabsswipe;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.support.v4.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
public class TopRatedFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.fragment_top_rated,
container, false);
return myFragmentView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
ArrayList<HashMap<String, String>> interventionsList;
// Progress Dialog
private ProgressDialog pDialog;
// url to get all interventions list
private static String url_all_interventions = "http://10.0.2.2/Scripts/liste_interventions.php";
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
// interventions JSONArray
JSONArray interventions = null;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.getListView().setTextFilterEnabled(true);
// Hashmap for ListView
interventionsList = new ArrayList<HashMap<String, String>>();
// Loading interventions in Background Thread
new LoadAllInterventions().execute();
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllInterventions extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading interventions. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All interventions from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_interventions, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Interventions: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt("success");
Log.d("success" , json.toString());
if (success == 1) {
// interventions found
// Getting Array of interventions
interventions = json.getJSONArray("interventions");
// looping through All interventions
for (int i = 0; i < interventions.length(); i++) {
JSONObject c = interventions.getJSONObject(i);
// Storing each json item in variable
String id = c.getString("id");
String name = c.getString("name");
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("Int_id", id);
map.put("Int_name", name);
// adding HashList to ArrayList
interventionsList.add(map);
}
}
} catch (JSONException e) {e.printStackTrace();}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), interventionsList,
R.layout.list_item, new String[] { "Int_id",
"Int_name"},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
Log.e("LIST", "setListAdapter is done");
}
});
}
}
public void runOnUiThread(Runnable runnable) {
// TODO Auto-generated method stub
}
}
This is tha TabsPagerAdapter class's code:
package info.androidhive.tabsswipe.adapter;
import info.androidhive.tabsswipe.GamesFragment;
import info.androidhive.tabsswipe.MoviesFragment;
import info.androidhive.tabsswipe.TopRatedFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new TopRatedFragment();
case 1:
// Games fragment activity
return new GamesFragment();
case 2:
// Movies fragment activity
return new MoviesFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
This is JSONParser class's code:
package info.androidhive.tabsswipe;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
This is ListFragment Layout's code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#99E7E5" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
and this is the php file that communicate with the postgresql data base:
<?php
$hostname_localhost ='localhost';
$port_localhost =5432;
$database_localhost ='techmobi';
$username_localhost ='openpg';
$password_localhost ='openpgpwd';
$localhost = "host='$hostname_localhost' port='$port_localhost' dbname='$database_localhost' user='$username_localhost' password='$password_localhost'";
$connexion =pg_connect($localhost) or die ("Erreur de connexion ".pg_last_error());
$query_search = "select id,name from crm_helpdesk";
$query_exec = pg_query($query_search) or die(pg_error());
$output = array();
while($rows=pg_fetch_assoc($query_exec))
{
$output[]=$rows;
}
echo json_encode($output);
?>
The the application close after running and that what appears in the logCat:
JSONParser error
Please any helps !!!
The error at the top of the log files is telling you exactly the problem:
Your JSON string is a JSON Array of two JSON objects. But you are trying to parse it as a JSON Object.
Change this line:
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
To be this:
// try parse the string to a JSON array
try {
jArr = new JSONArray(json);
Where jArr is declared to be of type JSONArray.
please help me with this problem..
i change my previous question to this..
i cant post new question because im in danger of being blocked..
heres my problem..
im trying to get data from database but i got this error when i run the app..
09-29 13:41:07.032 26507-26507/? E/Error﹕ No value for result
09-29 13:41:07.032 26507-26507/? W/System.err﹕ org.json.JSONException: No value for result
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at org.json.JSONObject.get(JSONObject.java:354)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at org.json.JSONObject.getJSONArray(JSONObject.java:548)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at com.example.administrator.mosbeau.CategoryFragment.prepareListData(CategoryFragment.java:249)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:233)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:180)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.os.AsyncTask.finish(AsyncTask.java:631)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.os.AsyncTask.access$600(AsyncTask.java:177)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:99)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5494)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:525)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
09-29 13:41:07.042 26507-26507/? I/MemoryCache﹕ MemoryCache will use up to 24.0MB
09-29 13:41:07.042 26507-26507/? D/AndroidRuntime﹕ Shutting down VM
09-29 13:41:07.042 26507-26507/? W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x418e38e0)
09-29 13:41:07.042 26507-26507/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.administrator.mosbeau.ListViewAdapter.getCount(ListViewAdapter.java:38)
at android.widget.ListView.setAdapter(ListView.java:463)
at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:236)
at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:180)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5494)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691)
at dalvik.system.NativeStart.main(Native Method)
09-29 13:41:07.052 941-7799/? I/ActivityManager﹕ Notify an ApplicationCrash
here is the code..
CategoryFragment.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ListView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by Administrator on 9/18/2015.
*/
public class CategoryFragment extends Fragment {
public static CategoryFragment newInstance(String id,String name) {
CategoryFragment fragment = new CategoryFragment();
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("name", name);
fragment.setArguments(bundle);
return fragment;
}
public CategoryFragment () {
}
EditText tpid, tpname;
String cid;
String cname;
String myJSON;
JSONObject jsonobject;
JSONArray jsonarray;
ListView productlistview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static final String result="result";
static String products_id = "products_id";
static String products_name = "products_name";
static String products_price = "products_price";
static String products_image = "products_image";
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.categorylayout, container, false);
getActivity().invalidateOptionsMenu();
tpid = (EditText) rootView.findViewById(R.id.tpid);
tpname = (EditText) rootView.findViewById(R.id.tpname);
if(getArguments() != null) {
String catid = getArguments().getString("id");
String catname = getArguments().getString("name");
tpid.setText(catid);
tpname.setText(catname);
cid = catid;
cname = catname;
}
productlistview = (ListView) rootView.findViewById(R.id.productlistview);
//new DownloadJSON().execute();
detectconnection = new Seocnd(getActivity());
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
getProduct();
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
return rootView;
}
public void getProduct(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle(cname);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");
// Depends on your web service
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;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
prepareListData();
adapter = new ListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
productlistview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void prepareListData(){
try {
// Locate the array name in JSON
JSONObject jsonObj = new JSONObject(myJSON);
jsonarray = jsonObj.getJSONArray(result);
HashMap<String, String> map = new HashMap<String, String>();
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject p = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("products_id", p.getString("products_id"));
map.put("products_name", p.getString("products_name"));
map.put("products_price", p.getString("products_price"));
map.put("products_image", p.getString("products_image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
}
ListViewAdapter.java
package com.example.administrator.mosbeau;
/**
* Created by Administrator on 9/28/2015.
*/
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView products_id;
TextView products_name;
TextView products_price;
ImageView products_image;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.product_listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in product_listview_item.xml
products_id = (TextView) itemView.findViewById(R.id.products_id);
products_name = (TextView) itemView.findViewById(R.id.products_name);
products_price = (TextView) itemView.findViewById(R.id.products_price);
// Locate the ImageView in product_listview_item.xml
products_image = (ImageView) itemView.findViewById(R.id.products_image);
// Capture position and set results to the TextViews
products_id.setText(resultp.get(CategoryFragment.products_id));
products_name.setText(resultp.get(CategoryFragment.products_name));
products_price.setText(resultp.get(CategoryFragment.products_price));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(CategoryFragment.products_image), products_image);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("products_id", resultp.get(CategoryFragment.products_id));
// Pass all data country
intent.putExtra("products_name", resultp.get(CategoryFragment.products_name));
// Pass all data population
intent.putExtra("products_price",resultp.get(CategoryFragment.products_price));
// Pass all data flag
intent.putExtra("products_image", resultp.get(CategoryFragment.products_image));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
NEW ERROR
09-29 14:12:26.981 593-593/? W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x409bf1f8)
09-29 14:12:26.992 593-593/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.administrator.mosbeau.CategoryFragment.prepareListData(CategoryFragment.java:259)
at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:232)
at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:179)
at android.os.AsyncTask.finish(AsyncTask.java:602)
at android.os.AsyncTask.access$600(AsyncTask.java:156)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
this is line 259
arraylist.add(map);
line 232
prepareListData();
UPDATED CODE
CategoryFragment.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ListView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by Administrator on 9/18/2015.
*/
public class CategoryFragment extends Fragment {
public static CategoryFragment newInstance(String id,String name) {
CategoryFragment fragment = new CategoryFragment();
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("name", name);
fragment.setArguments(bundle);
return fragment;
}
public CategoryFragment () {
}
EditText tpid, tpname;
String cid;
String cname;
String myJSON;
JSONObject jsonobject;
JSONArray jsonarray;
ListView productlistview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
public static String products_id = "products_id";
public static String products_name = "products_name";
public static String products_price = "products_price";
public static String products_image = "products_image";
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.categorylayout, container, false);
getActivity().invalidateOptionsMenu();
tpid = (EditText) rootView.findViewById(R.id.tpid);
tpname = (EditText) rootView.findViewById(R.id.tpname);
if(getArguments() != null) {
String catid = getArguments().getString("id");
String catname = getArguments().getString("name");
tpid.setText(catid);
tpname.setText(catname);
cid = catid;
cname = catname;
}
productlistview = (ListView) rootView.findViewById(R.id.productlistview);
//new DownloadJSON().execute();
detectconnection = new Seocnd(getActivity());
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
getProduct();
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
return rootView;
}
public void getProduct(){
class DownloadJSON extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle(cname);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");
// Depends on your web service
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;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
try {
// Locate the array name in JSON
JSONObject jsonObj = new JSONObject(myJSON);
jsonarray = jsonObj.getJSONArray("products");
arraylist = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject p = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("products_id", p.getString("products_id"));
map.put("products_name", p.getString("products_name"));
map.put("products_price", p.getString("products_price"));
map.put("products_image", p.getString("products_image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
adapter = new ListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
productlistview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
DownloadJSON g = new DownloadJSON();
g.execute();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
}
the image is not displaying when i use the .php file in this code..
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");
but when i use the .txt file it works..
i tried to copy the data of products.php and save it as .txt then when i change the link to this http://joehamirbalabadan.com/android/android/products.txt..
it works.. but i want to use the .php file because i use this to get the data from database..
products.php result
products.txt result
please help me..
Try to initialize arraylist first and also create HashMap item new instance inside for loop like :
protected void prepareListData(){
try {
arraylist = new ArrayList<HashMap<String, String>>();
// Locate the array name in JSON
JSONObject jsonObj = new JSONObject(myJSON);
jsonarray = jsonObj.getJSONArray(result);
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject p = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("products_id", p.getString("products_id"));
map.put("products_name", p.getString("products_name"));
map.put("products_price", p.getString("products_price"));
map.put("products_image", p.getString("products_image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
Initialize your result string with products like this one:
static final String result="products";
It will work
I think you need to decalre below variables
static final String result="result";
static String products_id = "products_id";
static String products_name = "products_name";
static String products_price = "products_price";
static String products_image = "products_image";
which you have to change like this
public static final String result="result";
public static String products_id = "products_id";
public static String products_name = "products_name";
public static String products_price = "products_price";
public static String products_image = "products_image";
I hope it work.
what i am trying to do is to first insert some values in the database(see insertvalues function) and then retrieving all the data from database into the spinner(see getvalues function).i successfully retrieve data from database which i checked through the textboxes.but when i set this data to my spinner adapter and run the app,i get an empty spinner.i understand that i should first write the line
My_spinner=(spinner)findViewbyid(--) and then call the getvalues function,but when i try to move this line(My_spinner=(spinner)findViewbyid(--) somewhere else,my app does not work anymore and says unfortunately the app was closed.i took quite alot of time to figure out the problem but i could not,please help.
package com.example.gcmclientapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class GcmServer extends Activity {
void showToast(CharSequence msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
// declarations for creating the database
SQLiteDatabase mydb;
String name_from_spinner; // this will be used to filter the database for the required registrationID
private static String DBNAME = "new1.db"; // this is our database..change it when you use
private static String TABLE = "MY_TABLE";
//end of dec
EditText et;
String regId,userName;
Button b;
TextView tv,tv2;
String temp="";
String[] arr;
Spinner My_spinner;
InputStream is=null;
ArrayList<String> my_array1 = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gcmserver);
b= (Button)findViewById(R.id.button1);
et=(EditText)findViewById(R.id.editText1);
tv=(TextView)findViewById(R.id.textView1);
tv2=(TextView)findViewById(R.id.textView2);
regId = getIntent().getStringExtra("REGID");
userName = getIntent().getStringExtra("USER");
insertvalues();
getTableValues();
My_spinner = (Spinner) findViewById(R.id.spinner1);
//setting on click listeners for the items of the spinner
My_spinner.setOnItemSelectedListener(
new OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
name_from_spinner=my_array1.get(position);
showToast(name_from_spinner);// get the name that has been clicked in the spinner
}
public void onNothingSelected(AdapterView<?> parent) {
showToast("Please enter contact");
}
});
// when the send button is clicked,we will extract the message from editText,regID and send to sendtoserver
// send button
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String ID = null;
String REGID=null;
String NAME=null;
String message =et.getText().toString(); //extract message from edit text
// extract registration number
try {
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
Cursor allrows = mydb.rawQuery("SELECT * FROM " + TABLE, null);
if (allrows.moveToFirst()) {
do {
ID = allrows.getString(0);
REGID = allrows.getString(1);
NAME = allrows.getString(2);
if(NAME.equals(name_from_spinner)) // string comparison
{
break;
}
} while (allrows.moveToNext());
showToast("left loop");
}
allrows.close();
mydb.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error encountered.",
Toast.LENGTH_LONG);
}
//tv.setText(REGID);
System.out.print(REGID);
sendToServer(message,REGID);
}
});
}
//#########################################INSERT############################################################
public void insertvalues()
{
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("regid", regId));
nameValuePairs.add(new BasicNameValuePair("name", userName));
try {
//tv2.setText(regId);
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost("http://192.168.1.3/new.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpClient.execute(httpPost);
HttpEntity entity=response.getEntity();
is=entity.getContent();
showToast("data inserted successfully");
}
catch(ClientProtocolException e)
{
Log.e("clientProtocol","Log_tag");
e.printStackTrace();
}catch(IOException e)
{
Log.e("log_tag","ioexception");
e.printStackTrace();
}
}
public void sendToServer(final String message,final String ID){
//tv2.setText(ID);
new AsyncTask<String, Void, String>(){
// changes are needed here
#Override
protected String doInBackground(String... params) {
try {
HttpResponse response = null;
HttpParams httpParameters = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(httpParameters);
String url="http://192.168.1.3/GCM/gcm.php?" + "®ID="+ ID + "&message="+ message; // changes needed here
Log.i("Send URL:", url);
HttpGet request = new HttpGet(url);
response = client.execute(request);
Log.i("responce URL:"," ");
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String webServiceInfo = "";
while ((webServiceInfo = rd.readLine()) != null) {
Log.d("****Status Log***", "Webservice: " + webServiceInfo);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute(null,null,null);
}
// ################################THIS FUNCTION SHOWS DATA FROM THE DATABASE#####################################
public void getTableValues() {
InputStream iss=null;
String line=null;
String result=null;
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost("http://192.168.1.3/retrieve.php");
HttpResponse response=httpClient.execute(httpPost);
HttpEntity entity=response.getEntity();
iss=entity.getContent();
}
catch(ClientProtocolException e)
{
System.out.println("exception 1 caught");
}
catch(IOException e)
{
Log.e("log_tag","ioexception");
e.printStackTrace();
}
try{
BufferedReader reader=new BufferedReader(new InputStreamReader(iss,"iso-8859-1"),8);
StringBuilder sb=new StringBuilder();
while((line=reader.readLine())!=null)
sb.append(line+"\n");
result=sb.toString();
//result now contains the data in the form of json
iss.close();
System.out.println("here is my data");
System.out.println(result);
}
catch(Exception e)
{
System.out.println("exception 2 caught");
}
try{
JSONArray jArray=new JSONArray(result);
int count=jArray.length();
for(int i=0;i<count;i++)
{
JSONObject json_data=jArray.getJSONObject(i);
temp+=json_data.getString("name")+":";
}
//System.out.println(temp);
arr=temp.split(":");
tv.setText(arr[1]);
tv2.setText(arr[2]);
ArrayAdapter my_Adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item,
arr);
My_spinner.setAdapter(my_Adapter);
}
catch(Exception e)
{
System.out.println("m so boread");
//System.out.println("hello");
}
}
//###############################################################################################################
}
// log cat after editing the code as suggested
01-17 21:27:32.939: D/dalvikvm(1895): GC_FOR_ALLOC freed 172K, 3% free 9493K/9692K, paused 3ms, total 3ms
01-17 21:27:33.019: W/EGL_genymotion(1895): eglSurfaceAttrib not implemented
01-17 21:27:33.075: D/AndroidRuntime(1895): Shutting down VM
01-17 21:27:33.075: W/dalvikvm(1895): threadid=1: thread exiting with uncaught exception (group=0xa4be7648)
01-17 21:27:33.075: E/AndroidRuntime(1895): FATAL EXCEPTION: main
01-17 21:27:33.075: E/AndroidRuntime(1895): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
01-17 21:27:33.075: E/AndroidRuntime(1895): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
01-17 21:27:33.075: E/AndroidRuntime(1895): at java.util.ArrayList.get(ArrayList.java:308)
01-17 21:27:33.075: E/AndroidRuntime(1895): at com.example.gcmclientapp.GcmServer$1.onItemSelected(GcmServer.java:123)
01-17 21:27:33.075: E/AndroidRuntime(1895): at android.widget.AdapterView.fireOnSelected(AdapterView.java:892)
01-17 21:27:33.075: E/AndroidRuntime(1895): at android.widget.AdapterView.access$200(AdapterView.java:49)
01-17 21:27:33.075: E/AndroidRuntime(1895): at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:860)
01-17 21:27:33.075: E/AndroidRuntime(1895): at android.os.Handler.handleCallback(Handler.java:730)
01-17 21:27:33.075: E/AndroidRuntime(1895): at android.os.Handler.dispatchMessage(Handler.java:92)
01-17 21:27:33.075: E/AndroidRuntime(1895): at android.os.Looper.loop(Looper.java:137)
01-17 21:27:33.075: E/AndroidRuntime(1895): at android.app.ActivityThread.main(ActivityThread.java:5103)
01-17 21:27:33.075: E/AndroidRuntime(1895): at java.lang.reflect.Method.invokeNative(Native Method)
01-17 21:27:33.075: E/AndroidRuntime(1895): at java.lang.reflect.Method.invoke(Method.java:525)
01-17 21:27:33.075: E/AndroidRuntime(1895): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-17 21:27:33.075: E/AndroidRuntime(1895): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-17 21:27:33.075: E/AndroidRuntime(1895): at dalvik.system.NativeStart.main(Native Method)
Try to populate values into the Spinner, not inside any other method, but inside the onCreate() method. Try to change your program as belows:
Change the getTableValues() method as:
public String[] getTableValues() {
Remove these lines from that method:
ArrayAdapter my_Adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, arr);
My_spinner.setAdapter(my_Adapter);
And return the array "arr" at the end of the method;
return arr;
and then populate values to Spinner at the onCreate() method after initializing the My_spinner object as belows
My_spinner = (Spinner) findViewById(R.id.spinner1);
arr = getTableValues();
ArrayAdapter my_Adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, arr);
My_spinner.setAdapter(my_Adapter);
Try to make this code working as I cannot debug this at the moment. It's a pleasure to help with this...
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class GcmServer extends Activity {
void showToast(CharSequence msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
// declarations for creating the database
SQLiteDatabase mydb;
String name_from_spinner; // this will be used to filter the database for the required registrationID
private static String DBNAME = "new1.db"; // this is our database..change it when you use
private static String TABLE = "MY_TABLE";
//end of dec
EditText et;
String regId,userName;
Button b;
TextView tv,tv2;
String temp="";
String[] arr;
Spinner My_spinner;
InputStream is=null;
ArrayList<String> my_array1 = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gcmserver);
b= (Button)findViewById(R.id.button1);
et=(EditText)findViewById(R.id.editText1);
tv=(TextView)findViewById(R.id.textView1);
tv2=(TextView)findViewById(R.id.textView2);
regId = getIntent().getStringExtra("REGID");
userName = getIntent().getStringExtra("USER");
insertvalues();
My_spinner = (Spinner) findViewById(R.id.spinner1);
List<String> list = getTableValues();
ArrayAdapter my_Adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, list);
My_spinner.setAdapter(my_Adapter);
//setting on click listeners for the items of the spinner
My_spinner.setOnItemSelectedListener(
new OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
name_from_spinner=my_array1.get(position);
showToast(name_from_spinner);// get the name that has been clicked in the spinner
}
public void onNothingSelected(AdapterView<?> parent) {
showToast("Please enter contact");
}
});
// when the send button is clicked,we will extract the message from editText,regID and send to sendtoserver
// send button
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String ID = null;
String REGID=null;
String NAME=null;
String message =et.getText().toString(); //extract message from edit text
// extract registration number
try {
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
Cursor allrows = mydb.rawQuery("SELECT * FROM " + TABLE, null);
if (allrows.moveToFirst()) {
do {
ID = allrows.getString(0);
REGID = allrows.getString(1);
NAME = allrows.getString(2);
if(NAME.equals(name_from_spinner)) // string comparison
{
break;
}
} while (allrows.moveToNext());
showToast("left loop");
}
allrows.close();
mydb.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error encountered.",
Toast.LENGTH_LONG);
}
//tv.setText(REGID);
System.out.print(REGID);
sendToServer(message,REGID);
}
});
}
//#########################################INSERT############################################################
public void insertvalues()
{
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("regid", regId));
nameValuePairs.add(new BasicNameValuePair("name", userName));
try {
//tv2.setText(regId);
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost("http://192.168.1.3/new.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpClient.execute(httpPost);
HttpEntity entity=response.getEntity();
is=entity.getContent();
showToast("data inserted successfully");
}
catch(ClientProtocolException e)
{
Log.e("clientProtocol","Log_tag");
e.printStackTrace();
}catch(IOException e)
{
Log.e("log_tag","ioexception");
e.printStackTrace();
}
}
public void sendToServer(final String message,final String ID){
//tv2.setText(ID);
new AsyncTask<String, Void, String>(){
// changes are needed here
#Override
protected String doInBackground(String... params) {
try {
HttpResponse response = null;
HttpParams httpParameters = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(httpParameters);
String url="http://192.168.1.3/GCM/gcm.php?" + "®ID="+ ID + "&message="+ message; // changes needed here
Log.i("Send URL:", url);
HttpGet request = new HttpGet(url);
response = client.execute(request);
Log.i("responce URL:"," ");
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String webServiceInfo = "";
while ((webServiceInfo = rd.readLine()) != null) {
Log.d("****Status Log***", "Webservice: " + webServiceInfo);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute(null,null,null);
}
// ################################THIS FUNCTION SHOWS DATA FROM THE DATABASE#####################################
public List<String> getTableValues() {
InputStream iss=null;
String line=null;
String result=null;
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost("http://192.168.1.3/retrieve.php");
HttpResponse response=httpClient.execute(httpPost);
HttpEntity entity=response.getEntity();
iss=entity.getContent();
}
catch(ClientProtocolException e)
{
System.out.println("exception 1 caught");
}
catch(IOException e)
{
Log.e("log_tag","ioexception");
e.printStackTrace();
}
try{
BufferedReader reader=new BufferedReader(new InputStreamReader(iss,"iso-8859-1"),8);
StringBuilder sb=new StringBuilder();
while((line=reader.readLine())!=null)
sb.append(line+"\n");
result=sb.toString();
//result now contains the data in the form of json
iss.close();
System.out.println("here is my data");
System.out.println(result);
}
catch(Exception e)
{
System.out.println("exception 2 caught");
}
List<String> list = new ArrayList<String>();
try{
JSONArray jArray=new JSONArray(result);
int count=jArray.length();
for(int i=0;i<count;i++)
{
JSONObject json_data=jArray.getJSONObject(i);
list.add(json_data.getString("name"));
}
//System.out.println(temp);
tv.setText(arr[1]);
tv2.setText(arr[2]);
}
catch(Exception e)
{
System.out.println("m so boread");
//System.out.println("hello");
}
return list;
}
//###############################################################################################################
}
hi i want to download a json file from my server and add this json to list view i handle this on fragment with asyncktask method and list adapter
but i get this error
10-27 14:45:30.385: E/AndroidRuntime(2074): FATAL EXCEPTION: main
10-27 14:45:30.385: E/AndroidRuntime(2074): java.lang.NullPointerException
10-27 14:45:30.385: E/AndroidRuntime(2074): at com.mihanServer.Fragments.NewsFragment$JsonReader.onPostExecute(NewsFragment.java:89)
10-27 14:45:30.385: E/AndroidRuntime(2074): at com.mihanServer.Fragments.NewsFragment$JsonReader.onPostExecute(NewsFragment.java:1)
10-27 14:45:30.385: E/AndroidRuntime(2074): at android.os.AsyncTask.finish(AsyncTask.java:631)
10-27 14:45:30.385: E/AndroidRuntime(2074): at android.os.AsyncTask.access$600(AsyncTask.java:177)
10-27 14:45:30.385: E/AndroidRuntime(2074): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
10-27 14:45:30.385: E/AndroidRuntime(2074): at android.os.Handler.dispatchMessage(Handler.java:99)
10-27 14:45:30.385: E/AndroidRuntime(2074): at android.os.Looper.loop(Looper.java:137)
10-27 14:45:30.385: E/AndroidRuntime(2074): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-27 14:45:30.385: E/AndroidRuntime(2074): at java.lang.reflect.Method.invokeNative(Native Method)
10-27 14:45:30.385: E/AndroidRuntime(2074): at java.lang.reflect.Method.invoke(Method.java:511)
10-27 14:45:30.385: E/AndroidRuntime(2074): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-27 14:45:30.385: E/AndroidRuntime(2074): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-27 14:45:30.385: E/AndroidRuntime(2074): at dalvik.system.NativeStart.main(Native Method)
this is my fragment code
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.mihanServer.sedasema.CustomListAdapter;
import com.mihanServer.sedasema.JSONParser;
import com.mihanServer.sedasema.MainActivity;
import com.mihanServer.sedasema.News;
import com.mihanServer.sedasema.R;
import android.app.ProgressDialog;
import android.database.DataSetObservable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.ListView;
public class NewsFragment extends Fragment {
private static final String url = "http://192.168.1.6/web/app_dev.php/news/list";
private List<News> newsList = new ArrayList<News>();
private ListView listView;
private CustomListAdapter adapter;
private JSONArray jArray;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.news , container, false);
listView = (ListView)rootView.findViewById(R.id.list);
try
{
adapter = new CustomListAdapter(getActivity(),newsList);
listView.setAdapter(adapter);
}
catch(Exception ex)
{
ex.printStackTrace();
}
new JsonReader().execute();
return rootView;
}
public class JsonReader extends AsyncTask<String, String, JSONObject>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
jArray = json.getJSONArray("news");
for (int i = 0; i < jArray.length(); i++) {
try {
News news = new News();
JSONObject obj = jArray.getJSONObject(i);
news.setNewsTitle(obj.getString("title"));
news.setNewsThumbnailUrl(obj.getString("thumbnail"));
news.setNewsReleaseTime( obj.getString("created"));
news.setNewsBody(obj.getString("body"));
news.setNewsId(obj.getInt("id"));
// adding app to app array
newsList.add(news);
}
catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}
catch (JSONException ex){
ex.printStackTrace();
}
}
}
}
after line notify data set changed i get error.
this is my list adapter code
import com.mihanServer.sedasema.R;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.mihanServer.sedasema.MainActivity;
import com.mihanServer.sedasema.AppController;
import com.mihanServer.sedasema.News;
public class CustomListAdapter extends BaseAdapter {
private final Activity actitity;
private LayoutInflater inflater;
private List<News> newsItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
News news;
public CustomListAdapter(Activity activity,List<News> newsItems) {
this.newsItems = newsItems;
this.actitity =activity;
imageLoader = new AppController().getImageLoader();
}
#Override
public int getCount() {
return newsItems.size();
}
#Override
public Object getItem(int location) {
return newsItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Context context = parent.getContext();
inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
//inflater = (LayoutInflater) activity
// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.news_list, null);
//comment for image reading
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView newsthumbnail = (NetworkImageView) convertView
.findViewById(R.id.news_image);
TextView newsTitle = (TextView) convertView.findViewById(R.id.news_title);
//TextView newsBody = (TextView) convertView.findViewById(R.id.news_body);
TextView newsReleaseTime = (TextView) convertView.findViewById(R.id.news_release_time);
// getting news data for the row
news = newsItems.get(position);
//comment for image reading
newsthumbnail.setImageUrl(news.getNewsThumbnailUrl(), imageLoader);
newsTitle.setText(news.getNewsTitle());
newsReleaseTime.setText( news.getNewsReleaseTime());
//newsBody.setText(news.getNewsBody());
convertView.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View arg0) {
news=newsItems.get(position);
Intent intent = new Intent(actitity.getApplicationContext(),NewsDetails.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("title",news.getNewsTitle());
intent.putExtra("body", news.getNewsBody());
intent.putExtra("newsimage", news.getNewsThumbnailUrl());
intent.putExtra("releasedtime", news.getNewsReleaseTime());
actitity.getApplicationContext().startActivity(intent);
}
});
return convertView;
}
}
and this is my json parser
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
static Socket socket = null;
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
try{
//try {
//URL urlS = new URL(url);
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
/*catch (UnknownHostException e) {
e.printStackTrace();
json = "UnknownHostException: " + e.toString();
}*/
//is = urlS.openStream();
//}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "");
}
is.close();
json = sb.toString();
//json = json.replace(""", "\"");
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
}/*catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
json = "IOException: " + e.toString();*/
// }
finally{
if(socket != null){
try {
socket.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return jObj;
}
}
i also use volley lib for download images like this
http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/
try with below changes in your adapter class:
public class CustomListAdapter extends BaseAdapter {
private final Activity actitity;
private LayoutInflater inflater;
private List<News> newsItems;
private AQuery aQuery;
//ImageLoader imageLoader = AppController.getInstance().getImageLoader();
News news;
public CustomListAdapter(Activity activity,List<News> newsItems) {
this.newsItems = newsItems;
this.actitity =activity;
aQuery=new AQuery(activity);
// imageLoader = new AppController().getImageLoader();
}
#Override
public int getCount() {
return newsItems.size();
}
#Override
public Object getItem(int location) {
return newsItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final Context context = parent.getContext();
inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
//inflater = (LayoutInflater) activity
// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.news_list, null);
//comment for image reading
/*if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();*/
NetworkImageView newsthumbnail = (NetworkImageView) convertView
.findViewById(R.id.news_image);
TextView newsTitle = (TextView) convertView.findViewById(R.id.news_title);
//TextView newsBody = (TextView) convertView.findViewById(R.id.news_body);
TextView newsReleaseTime = (TextView) convertView.findViewById(R.id.news_release_time);
// getting news data for the row
news = newsItems.get(position);
if(news.getNewsThumbnailUrl().length()>0){
aQuery.id(newsthumbnail).image(news.getNewsThumbnailUrl(),true,true);
}else{
newsthumbnail.setVisibility(View.GONE);
}
//comment for image reading
//newsthumbnail.setImageUrl(news.getNewsThumbnailUrl(), imageLoader);
newsTitle.setText(news.getNewsTitle());
newsReleaseTime.setText( news.getNewsReleaseTime());
//newsBody.setText(news.getNewsBody());
convertView.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View arg0) {
news=newsItems.get(position);
Intent intent = new Intent(actitity.getApplicationContext(),NewsDetails.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("title",news.getNewsTitle());
intent.putExtra("body", news.getNewsBody());
intent.putExtra("newsimage", news.getNewsThumbnailUrl());
intent.putExtra("releasedtime", news.getNewsReleaseTime());
actitity.getApplicationContext().startActivity(intent);
}
});
return convertView;
}
}
Hie Friends
I have one ListView which displays image data from JSON parser for that I use Custom Base Adapter.
But I got following exception.
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.ecard.ECard_main$AsycLove.onPostExecute(ECard_main.java:193)
at com.example.ecard.ECard_main$AsycLove.onPostExecute(ECard_main.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:602)
at android.os.AsyncTask.access$600(AsyncTask.java:156)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
My Code Is:
package com.example.ecard;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import com.loopj.android.image.SmartImageView;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ECard_main extends Activity
{
String catagories;
String anim_id,album_id,anim_name,anim_thumb,anim_url;
TextView title;
SmartImageView image;
ListView hlv;
ArrayList<HashMap<String, String>> albumList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.ecard_main);
Intent i=getIntent();
catagories=i.getExtras().getString("Catagories");
title=(TextView)findViewById(R.id.tv_main_title);
image=(SmartImageView)findViewById(R.id.IV_image);
title.setText(catagories);
//hlv = getListView();
hlv = (ListView) findViewById(android.R.id.list);
albumList = new ArrayList<HashMap<String, String>>();
new AsycLove().execute();
}
class AsycLove extends AsyncTask<String, String, String>
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(ECard_main.this);
progressDialog.setTitle("Loading");
progressDialog.setMessage("Please wait");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected String doInBackground(String... aurl)
{
try
{
HttpPost postMethod = new HttpPost("http://demo1.idevtechnolabs.com/smartecard/love.php");
BufferedReader bufferedReader = null;
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
response = client.execute(postMethod);
final int statusCode = response.getStatusLine().getStatusCode();
Log.v("Album ::","Response:::--->"+response.toString());
Log.v("Album ::","Status Code:::--->"+statusCode);
bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer("");
String line = "";
String LineSeparator = System.getProperty("line.separator");
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line + LineSeparator);
}
bufferedReader.close();
//-------------CONVERT DATA TO JSON---------------------------------
try
{
String myjsonstring = stringBuffer.toString();
JSONArray jsonArray = new JSONArray(myjsonstring);
JSONObject jsonObj = null;
albumList.clear();
jsonObj = jsonArray.getJSONObject(0);
for(int i=0; i<jsonArray.length();i++)
{
jsonObj = jsonArray.getJSONObject(i);
anim_id = jsonObj.getString("animation_id");
album_id = jsonObj.getString("album_id");
anim_name = jsonObj.getString("animation_name");
anim_thumb= jsonObj.getString("animation_thumb");
anim_url = jsonObj.getString("animation_url");
anim_url=anim_url.replaceAll("\"","");
Log.v("Anim URL","Anim URL::"+anim_url);
Log.v("Anim Name","Anim Name::"+anim_name);
HashMap<String, String> tmp_album = new HashMap<String, String>();
tmp_album.put("anim_id", anim_id);
tmp_album.put("anim_thumb", anim_thumb);
albumList.add(tmp_album);
}
}
catch (Exception e)
{
Log.v("Home ::","Call JSON Exception in get Album in List--->"+e.toString());
e.printStackTrace();
}
}
catch (IOException e)
{
Log.v("Exception: Get get Album in List","Name-"+e.toString());
e.printStackTrace();
}
return "0";
}
#Override
protected void onPostExecute(String code)
{
Toast.makeText(getApplicationContext(), "Image URL Call Successfully", Toast.LENGTH_LONG).show();
Log.v("Album","Album List::"+albumList);
ECard_main_Custom_Adapter adapter =new ECard_main_Custom_Adapter(getApplicationContext(),albumList);
hlv.setAdapter(adapter);
progressDialog.dismiss();
progressDialog = null;
}
}
}
And My Adapter Is:
import java.util.ArrayList;
import java.util.HashMap;
import com.loopj.android.image.SmartImageView;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class ECard_main_Custom_Adapter extends BaseAdapter
{
private Context context;
ArrayList<HashMap<String, String>> listAlbum;
ViewHolder vholder;
Drawable image;
public ECard_main_Custom_Adapter(Context context, ArrayList<HashMap<String, String>> albumList)
{
this.context = context;
this.listAlbum=albumList;
}
#Override
public int getCount()
{
Log.v("1","1");
return listAlbum.size();
}
#Override
public Object getItem(int position)
{
Log.v("1","2");
return position;
}
#Override
public long getItemId(int position)
{
Log.v("1","3");
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
Log.v("1","1");
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi=convertView;
vi = inflater.inflate(R.layout.ecard_main_adapter, null);
vholder = new ViewHolder();
vholder.img_album=(SmartImageView)vi.findViewById(R.id.IV_image);
vi.setTag(vholder);
try
{
String anim_id=listAlbum.get(position).get("anim_id");
String url=listAlbum.get(position).get("anim_thumb");
Log.v("Anim ID and Anim URL","Id:"+anim_id+" URL:"+url);
vholder.img_album.setImageUrl(url);
}
catch (Exception e)
{
// TODO: handle exception
Log.v("Error Ecard","Error is:::"+e);
}
return vi;
}
static class ViewHolder
{
SmartImageView img_album;
}
}
Please tell me where I am wrong.
Any help is appreciated.
Thanks In advance.
First correct this
hlv = (ListView) findViewById(android.R.id.list);
to
hlv = (ListView) findViewById(R.id.list);
It might cause an error. and make sure your ecard_main.xml layout contains ListView with id list