JSON parsing data requires restart application - android

Sorry for my poor English... here is some part of data view activity
DataView Activity :
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
/*
* StrictMode is most commonly used to catch accidental disk or network
* access on the application's main thread
*/
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
name = (TextView) findViewById(R.id.tv_name);
fb = (ImageButton) findViewById(R.id.btn_fb);
name1 = (TextView) findViewById(R.id.tv_name1);
favo = (ImageButton) findViewById(R.id.btn_fav);
contact = (TextView) findViewById(R.id.tv_contact);
address = (TextView) findViewById(R.id.tv_address);
category = (TextView) findViewById(R.id.tv_category);
view_map = (ImageButton) findViewById(R.id.view_direction);
db = new SQLController(this);
url = getResources().getString(R.string.url);
Bundle b = getIntent().getExtras();
data = b.getString("itemName");
new async_dataDetail(DataViewActivity.this).execute();
favo.setOnClickListener(this);
view_map.setOnClickListener(this);
fb.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_fav:
String myUser = name.getText().toString();
String storedUser = db.Exist(myUser);
// If Username exist
if (myUser.equals(storedUser)) {
Toast.makeText(getApplicationContext(), "Already exists !!!",
Toast.LENGTH_SHORT).show();
} else {
db.adddata(context, name.getText().toString(), category
.getText().toString(), id, MainActivity.a);
favoriteList = db.getFavList();
Log.d("aaaa", name.getText().toString()
+ category.getText().toString() + MainActivity.a);
Toast.makeText(getApplicationContext(),
"Successfully, added to Favourities", 0).show();
}
break;
}
}
class async_dataDetail extends AsyncTask<String, Void, Boolean> {
public async_dataDetail(DataViewActivity activity) {
context = activity;
}
#Override
protected Boolean doInBackground(String... arg0) {
// declare parameters that are passed to PHP script i.e. the
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
if (MainActivity.a == 1) {
postParameters.add(new BasicNameValuePair("777", data));
try {
CustomHttpClient.executeHttpGet("777");
} catch (Exception e1) {
e1.printStackTrace();
}
} else if (Favourite.a == 1) {
postParameters.add(new BasicNameValuePair("524", data));
try {
CustomHttpClient.executeHttpGet("524");
} catch (Exception e1) {
e1.printStackTrace();
}
}
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
url,
postParameters);
// store the result returned by PHP script that runs
// MySQL query
String result = response.toString();
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
st_name = " " + json_data.getString("name");
id = json_data.getString("id");
st_name1 = " Name : "
+ json_data.getString("name");
st_contact = " Contact : " + " "
+ json_data.getString("contact");
st_category = " Category : "
+ json_data.getString("Category");
st_address = " Address : "
+ json_data.getString("address");
Log.d("favourite_data", st_name + " " + st_contact
+ " " + st_category + " " + st_address);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
} catch (Exception e) {
Log.e("log_tag", "Error in http connection!!" + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
progressdialog.dismiss();
try {
name.setText(st_name);
name1.setText(st_name1);
contact.setText(st_contact);
category.setText(st_category);
address.setText(st_address);
} catch (Exception e) {
Log.e("log_tag", "Error in Display!" + e.toString());
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressdialog = new ProgressDialog(DataViewActivity.this);
progressdialog.setTitle("Processing....");
progressdialog.setMessage("Please Wait.....");
progressdialog.setCancelable(false);
progressdialog.show();
}
}
Favourite Items Activity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fav);
setTitle("Favorites");
// listView = (ListView) findViewById(R.id.listView);
listView = getListView();
db = new SQLController(this);
favoriteList = db.getFavList();
listView.setAdapter(new ViewAdapter());
}
public class ViewAdapter extends BaseAdapter {
LayoutInflater mInflater;
public ViewAdapter() {
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return favoriteList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listitem, null);
}
nameText = (TextView) convertView.findViewById(R.id.nameText);
nameText.setText(" Name : "
+ favoriteList.get(position).getName());
final TextView ageText = (TextView) convertView
.findViewById(R.id.ageText);
ageText.setText(favoriteList.get(position).getAge());
final Button delete = (Button) convertView
.findViewById(R.id.delete);
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
db.removeFav(favoriteList.get(position).getId());
favoriteList = db.getFavList();
listView.setAdapter(new ViewAdapter());
}
});
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
a = 1;
String aa = favoriteList.get(position).getCateg()
.toString();
String bb = favoriteList.get(position).getTable()
.toString();
intent.putExtra("itemName", aa + bb);
startActivity(intent);
}
});
return convertView;
}
}
Logcat :
10-16 14:41:36.700: W/System.err(23063): at java.lang.Thread.run(Thread.java:864)
10-16 14:41:36.830: D/OpenGLRenderer(23063): Flushing caches (mode 0)
10-16 14:41:36.830: D/memalloc(23063): /dev/pmem: Unmapping buffer base:0x556ab000 size:6144000 offset:4608000
10-16 14:41:36.830: D/memalloc(23063): /dev/pmem: Unmapping buffer base:0x58d7c000 size:7680000 offset:6144000
10-16 14:41:36.830: D/memalloc(23063): /dev/pmem: Unmapping buffer base:0x54043000 size:4608000 offset:3072000
10-16 14:41:37.831: E/log_tag(23063): Error parsing data org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONArray
10-16 14:41:37.891: D/memalloc(23063): /dev/pmem: Unmapping buffer base:0x56291000 size:15728640 offset:15237120
10-16 14:41:37.891: D/memalloc(23063): /dev/pmem: Unmapping buffer base:0x594cf000 size:22794240 offset:22302720
10-16 14:41:37.901: D/memalloc(23063): /dev/pmem: Unmapping buffer base:0x5d32e000 size:24821760 offset:24330240
I am getting some data in ViewData activity from sql data base through json.. in this activity when i press favo button some details is added to SQLite db and shown in list view named favourite items activity..
problem is that when i add some data in favourite item it is added successfully. but when i clicked on item in list view to get details of the items it is not shown it give error . but when i restart my application and click item in listview it works fine .. Every time when i add some item detail is not shown but when i restart it works fine..

I got Solution after debugging, the problem was value of Mainactivity.a and Favourite.a was overlapping . so responce was null . but
finally i change value favourite.a = 1 to MainActvity.a =2 when Favourite list item is clicked
if (MainActivity.a == 1) {
postParameters.add(new BasicNameValuePair("777", data));
try {
CustomHttpClient.executeHttpGet("777");
} catch (Exception e1) {
e1.printStackTrace();
}
} else if (MainActivity.a == 2) {
postParameters.add(new BasicNameValuePair("524", data));
try {
CustomHttpClient.executeHttpGet("524");
} catch (Exception e1) {
e1.printStackTrace();
}
now its working fine .

Related

I need to set my app content offline

I am getting my content from json through server.I have two TextView and one ImageView in my layout.i have written the content from json to a file. but i not able to set my data while offline
I am getting the data from a file also.
MainActivity.java:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private Context context;
private NavigationView mNavigationView;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
NewsAdapter adapter;
ArrayList<News> Newslist;
private Toolbar mToolbar;
private ProgressDialog pDialog;
private String TAG = MainActivity.class.getSimpleName();
private static String url = "https://www.amrita.edu/amrita_api/v1/news_android.jsonp";
String image;
String imageurl;
ArrayList<HashMap<String, String>> arraylist;
// ArrayList<String> newsList = new ArrayList<String>();
WebView descWView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_json);
Newslist = new ArrayList<News>();
context=getApplicationContext();
//initViews();
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle(R.string.title);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.drawable.app_icon);
initViews();
initContentWebView();
setUpNavDrawer();
new GetContacts().execute();
}
private void initViews(){
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
}
void initContentWebView(){
String htmlText = " %s ";
// ArrayList<String> myData = newsList;
// descWView = (WebView) findViewById(R.id.content_wview);
// String htmlData= "<html><body style='text-align:justify;font-size:"+getResources().getInteger(R.integer.main_text)+"px'><p>'sajhdsakjc;osalcjklsx'</p>"+myData.toString()+"</body></Html >";
//descWView.getSettings().setDefaultTextEncodingName("utf-8");
// descWView.loadData(htmlData, "text/html", "utf-8");
// descWView.loadDataWithBaseURL(String.format(htmlText, htmlData), String.valueOf(myData), "text/html", "UTF-8", String.format(htmlText, htmlData));
// descWView.s(myData);
}
private void setUpNavDrawer() {
mDrawerToggle=new ActionBarDrawerToggle(this,mDrawerLayout,mToolbar,R.string.drawer_open,R.string.drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
mNavigationView.setNavigationItemSelectedListener(this);
}
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
String item=menuItem.getTitle().toString();
String dPath=menuItem.getTitleCondensed().toString();
if(item.equals("News")){
//this.finish();
mDrawerLayout.closeDrawers();
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
this.finish();
//Toast.makeText(getApplicationContext(), "god", Toast.LENGTH_SHORT).show();
}
else if(item.equals("Events")){
mDrawerLayout.closeDrawers();
Intent intent = new Intent(context, EventActivity.class);
startActivity(intent);
this.finish();
Toast.makeText(getApplicationContext(), "god1", Toast.LENGTH_SHORT).show();
}
else if(item.equals("Latest Publications")){
mDrawerLayout.closeDrawers();
Toast.makeText(getApplicationContext(), "god2", Toast.LENGTH_SHORT).show();
} else if(item.equals("Students Achivements")){
mDrawerLayout.closeDrawers();
Toast.makeText(getApplicationContext(), "god3", Toast.LENGTH_SHORT).show();
}
else if(item.equals("Important Announcements")){
mDrawerLayout.closeDrawers();
Toast.makeText(getApplicationContext(), "god4", Toast.LENGTH_SHORT).show();
}
else if(item.equals("Research")){
mDrawerLayout.closeDrawers();
Intent intent = new Intent(context, ResearchActivity.class);
startActivity(intent);
this.finish();
//Toast.makeText(getApplicationContext(), "god5", Toast.LENGTH_SHORT).show();
}
else if(item.equals("Ranking")){
mDrawerLayout.closeDrawers();
//Toast.makeText(getApplicationContext(), "god6", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, RankingActivity.class);
startActivity(intent);
this.finish();
}
else if(item.equals("International")){
mDrawerLayout.closeDrawers();
//Toast.makeText(getApplicationContext(), "god7", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, InternationalActivity.class);
startActivity(intent);
this.finish();
}
else if(item.equals("About")){
mDrawerLayout.closeDrawers();
Intent intent = new Intent(context, AboutActivity.class);
startActivity(intent);
this.finish();
// Toast.makeText(getApplicationContext(), "god8", Toast.LENGTH_SHORT).show();
}
else if(item.equals("Contact Us")) {
mDrawerLayout.closeDrawers();
// Toast.makeText(getApplicationContext(), "god9", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, ContactUs.class);
intent.putExtra("keyId", item);
intent.putExtra("descPath",dPath);
startActivity(intent);
// this.finish();
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_share) {
/*Intent intent=new Intent(context,AboutActivity.class);
startActivity(intent);
return true;*/ Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// arraylist = new ArrayList<HashMap<String, String>>();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(jsonStr);
for (int i = 0; i <jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
News news = new News();
JSONObject jsonobject = jsonarray.getJSONObject(i);
JSONObject jsonimage=jsonobject.getJSONObject("image");
//Log.d(String.valueOf(jsonimage), String.valueOf(jsonimage.length()));
String imageurl=jsonimage.getString("filename");
// System.out.println(imageurl);
// Retrive JSON Objects
news.setTitle(jsonobject.getString("title"));
news.setBody(jsonobject.getString("body"));
// news.setImage(jsonobject.getString("image"));
news.setImage(jsonimage.getString("filename"));
// Set the JSON Objects into the array
Newslist.add(news);
/*image = jsonobject.getString("image");
String title = jsonobject.getString("title");
String content = jsonobject.getString("content");
newsList.add(image);
newsList.add(title);
newsList.add(content);*/
// Log.d(newsList.get(i),"image");
// Log.d(title,"title");
// System.out.println("All MinQuantitiy"+newsList);
}
} catch (JSONException e) {
e.printStackTrace();
}
/* try {
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d(jsonStr,"json");
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("news");
// looping through All Contacts
*//*for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
// adding contact to contact list
contactList.add(contact);
}*//*
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}*/
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
int sizeofarray= Newslist.size();
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new CustomPagerAdapter(context,sizeofarray ));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
TextView tvtitle=(TextView)findViewById(R.id.tvtitle);
TextView tvbody=(TextView)findViewById(R.id.tvbody);
ImageView im=(ImageView)findViewById(R.id.NewsImage);
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
for(position=0;position<20;position++) {
tvtitle.setText(Newslist.get(position).getTitle());
tvbody.setText(Newslist.get(position).getBody());
// Toast.makeText(getApplicationContext(),position//, Toast.LENGTH_LONG).show();
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
// im.setImageResource(String.format("https://www.amrita.edu/sites/default/files/%s", Newslist.get().getImage()));
Toast.makeText(getApplicationContext(),"sizeNewslist"+sizeofarray, Toast.LENGTH_LONG).show();
// Updating parsed JSON data into ListView
/*for(int i=1;i<3;i++){
Toast.makeText(getApplicationContext(),
"aaa"+newsLists,
Toast.LENGTH_LONG)
.show();
}*/
/* ListAdapter adapter = new SimpleAdapter(
MainActivity.this, newsList,
R.layout.list_item, new String[]{"name", "email",
"content"}, new int[]{R.id.image,
R.id.title, R.id.co});
lv.setAdapter(adapter);*/
}
}
}
/* public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}*/
adapter class
public class CustomPagerAdapter extends PagerAdapter {
String image_url;
private Context mContext;
int size;
ArrayList<News> Newslist;
File file,file1;
StringBuffer buffer,buffer1;
DataHandler handler;
public CustomPagerAdapter(Context context, int arraysize, ArrayList<News> newslist) {
mContext = context;
size=arraysize;
Newslist=newslist;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
ModelObject modelObject = ModelObject.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.row, collection, false);
collection.addView(layout);
TextView tvtitle=(TextView)layout.findViewById(R.id.tvtitle);
TextView tvbody=(TextView)layout.findViewById(R.id.tvbody);
ImageView im=(ImageView)layout.findViewById(R.id.NewsImage);
im.setScaleType(ImageView.ScaleType.FIT_XY);
SugarContext.init(mContext);
ConnectivityManager ConnectionManager=(ConnectivityManager)mContext.getSystemService(mContext.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=ConnectionManager.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected()==true )
{
tvtitle.setText(Html.fromHtml(Newslist.get(position).getTitle()));
tvbody.setText(Html.fromHtml(Newslist.get(position).getBody()));
image_url = "https://www.amrita.edu/sites/default/files/" + Newslist.get(position).getImage();
Picasso.with(mContext).load(image_url).into(im);
/*****************88*/
ArrayList<News> content = Newslist;
// String content="hello";
File file,file1;
FileOutputStream outputStream,outputStream1;
try {
//file = File.createTempFile("MyCache", null,getCacheDir());
file = new File(mContext.getCacheDir(), "newstitle");
file1 = new File(mContext.getCacheDir(), "newsbody");
outputStream = new FileOutputStream(file);
outputStream1 = new FileOutputStream(file1);
outputStream.write(content.get(position).getTitle().getBytes());
outputStream1.write(content.get(position).getBody().getBytes());
//outputStream.write(Integer.parseInt(content.get(position).getImage()));
// outputStream.write(Integer.parseInt(content.get(position).getTitle()));
// outputStream.write(Integer.parseInt(content.get(position).getBody()));
outputStream.close();
Log.d("filecreated", String.valueOf(file));
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader input = null;
BufferedReader input1=null;
file = null;
file1=null;
try {
file = new File(mContext.getCacheDir(), "newstitle");
file1 = new File(mContext.getCacheDir(), "newsbody");// Pass getFilesDir() and "MyFile" to read file
input = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
input1 = new BufferedReader(new InputStreamReader(new FileInputStream(file1)));
String line,line1;
buffer = new StringBuffer();
buffer1 = new StringBuffer();
while ((line = input.readLine()) != null) {
buffer.append(line);
}
while ((line1 = input1.readLine()) != null) {
buffer1.append(line1);
}
String s=buffer.toString();
String t=buffer1.toString();
//Log.d("bufferdsample", buffer.toString());
Toast.makeText(mContext, "asas"+s, Toast.LENGTH_LONG).show();
Toast.makeText(mContext, "body"+t, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
/*****************************88*/
/* try {
handler = new DataHandler(mContext);
handler.open();
} catch (Exception e) {
Toast.makeText(mContext, "exc " + e,
Toast.LENGTH_SHORT).show();
}
handler.insertData(Newslist.get(position).getImage(),Newslist.get(position).getTitle(),Newslist.get(position).getBody());
*/
Toast.makeText(mContext, "Network Available", Toast.LENGTH_LONG).show();
}
else
{
BufferedReader input = null;
BufferedReader input1=null;
file = null;
file1=null;
try {
file = new File(mContext.getCacheDir(), "newstitle");
file1 = new File(mContext.getCacheDir(), "newsbody");// Pass getFilesDir() and "MyFile" to read file
input = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
input1 = new BufferedReader(new InputStreamReader(new FileInputStream(file1)));
String line,line1;
buffer = new StringBuffer();
buffer1 = new StringBuffer();
while ((line = input.readLine()) != null) {
buffer.append(line);
}
while ((line1 = input1.readLine()) != null) {
buffer1.append(line1);
}
String s=buffer.toString();
String t=buffer1.toString();
//Log.d("bufferdsample", buffer.toString());
Toast.makeText(mContext, "asas"+s, Toast.LENGTH_LONG).show();
Toast.makeText(mContext, "body"+t, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(mContext, "Network Available", Toast.LENGTH_LONG).show();
/* image_url = "https://www.amrita.edu/sites/default/files/" + Newslist.get(position).getImage();
Picasso.with(mContext).load(image_url).into(im);*/
}
/* String fileName="cachefile";
try {
cacheThis.writeObject(mContext, fileName, Newslist);
} catch (IOException e) {
e.printStackTrace();
}
try {
Newslist.addAll((List<News>) cacheThis.readObject(mContext, fileName));
Log.d("aaasasa", String.valueOf(Newslist));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}*/
// ImageLoader class instance
// whenever you want to load an image from url
// call DisplayImage function
// url - image url to load
// loader - loader image, will be displayed before getting image
// image - ImageView
//im.setImageBitmap(getBitmapFromURL("https://3.bp.blogspot.com/-yEE6FqiglKw/VeBH_MmGGzI/AAAAAAAAbHE/HUYcYvkIwl0/s1600/AndroidImageViewSetImageFromURL2.png"));
// im.setImageResource(Uri.parse("https://www.amrita.edu/sites/default/files/%s", Newslist.get(position).getImage()));
// new DownloadImageTask(im).execute("https://www.amrita.edu/sites/default/files/" + Newslist.get(position).getImage());
return layout;
}
/*public void ofline(View view){
String filr_name="newfile";
FileOutputStream fileOutputStream = mContext.OpenfileOutput(filr_name,MODE_PRIVATE)
}
public void readmessage(View view){
}*/
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return size;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
ModelObject customPagerEnum = ModelObject.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
}
When device is offline you can import /read from a File or database which contains this json value . After getting internet update the database or file .
For file you must make or move the file in
Environment.getExternalStorageDirectory();
And for writing in a file follow the code
private void writeToFile(String data,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("test.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
And reading from external storage follow the following code
private String readFromFile(Context context) {
String ret = "";
try {
InputStream inputStream = context.openFileInput("test.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}

How to save spinner selected item in mysql db?

Here,I already fetched data from mysql db and this data shows into the spinner Now the problem is, I want to save spinner selected item into mysql database with different table, the item which i select from spinner it should save to database, how can i do this? By using php mysql i insert record into spinner and i want to update the records of register table with spinner selected item.Can i update the register table with spinner selected item values? please suggest me.
java file
public class MainActivity_d3 extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
//Declaring an Spinner
private Spinner spinner2, spinner1;
private String str_spinner1, str_spinner2, s_name, s_course;
//An ArrayList for Spinner Items
private ArrayList<String> students1;
private ArrayList<String> students2;
Button mBtnSave;
//JSON Array
private JSONArray result1, result2, result;
//TextViews to display details
private TextView textViewName1;
private TextView textViewName2;
private TextView textViewCourse;
private TextView textViewSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity_d1);
//Initializing the ArrayList
students1 = new ArrayList<String>();
students2 = new ArrayList<String>();
//Initializing Spinner
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
spinner1.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);
mBtnSave = (Button) findViewById(R.id.button2);
mBtnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitForm();
}
});
//Initializing TextViews
textViewName1 = (TextView) findViewById(R.id.textViewName1);
textViewName2 = (TextView) findViewById(R.id.textViewName2);
// textViewCourse = (TextView) findViewById(R.id.textViewCourse);
// textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
getData1();
getData2();
}
private void submitForm() {
// Submit your form here. your form is valid
//Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
s_name = spinner1.getSelectedItem().toString();
s_course = spinner2.getSelectedItem().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new InsertActivity(this).execute(s_name, s_course);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
/*if(spinner1.getId()==R.id.spinner1) {
textViewName1.setText(getName(position));
}
else if(spinner2.getId()==R.id.spinner2)
{
textViewName2.setText(getCourse(position));
}
/* switch (view.getId()){
case R.id.spinner1:
getData1();
break;
case R.id.spinner2:
getData2();
break;
}*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
/* private String getName(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(Config.TAG_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
private String getCourse(int position){
String course="";
try {
JSONObject json = result.getJSONObject(position);
course = json.getString(Config.TAG_COURSE);
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}*/
private void getData1() {
//Creating a string request
StringRequest stringRequest1 = new StringRequest(Config.DATA_URL1,
new Response.Listener<String>() {
#Override
public void onResponse(String response1) {
JSONObject j1 = null;
try {
//Parsing the fetched Json String to JSON Object
j1 = new JSONObject(response1);
//Storing the Array of JSON String to our JSON Array
result1 = j1.getJSONArray(Config.JSON_ARRAY1);
//Calling method getStudents to get the students from the JSON Array
getStudents1(result1);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error1) {
}
});
//Creating a request queue
RequestQueue requestQueue1 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue1.add(stringRequest1);
}
private void getStudents1(JSONArray j1) {
//Traversing through all the items in the json array
for (int i = 0; i < j1.length(); i++) {
try {
//Getting json object
JSONObject json1 = j1.getJSONObject(i);
//Adding the name of the student to array list
students1.add(json1.getString(Config.TAG_COURSE));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner1.setAdapter(new ArrayAdapter<String>(MainActivity_d3.this, android.R.layout.simple_spinner_dropdown_item, students1));
}
//Initializing TextViews
// textViewCourse = (TextView) findViewById(R.id.textViewCourse);
// textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
private void getData2() {
//Creating a string request
StringRequest stringRequest2 = new StringRequest(Config.DATA_URL2,
new Response.Listener<String>() {
#Override
public void onResponse(String response2) {
JSONObject j2 = null;
try {
//Parsing the fetched Json String to JSON Object
j2 = new JSONObject(response2);
//Storing the Array of JSON String to our JSON Array
result = j2.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents2(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error1) {
}
});
//Creating a request queue
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue2.add(stringRequest2);
}
private void getStudents2(JSONArray j2) {
//Traversing through all the items in the json array
for (int i = 0; i < j2.length(); i++) {
try {
//Getting json object
JSONObject json2 = j2.getJSONObject(i);
//Adding the name of the student to array list
students2.add(json2.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner2.setAdapter(new ArrayAdapter<String>(MainActivity_d3.this, android.R.layout.simple_spinner_dropdown_item, students2));
}
}
//InsertActivity
public class InsertActivity extends AsyncTask<String, Void, String> {
private Context context;
Boolean error, success;
public InsertActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String s_name = arg0[0];
// String userName = arg0[1];
String s_course = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?s_name=" + URLEncoder.encode(s_name, "UTF-8");
// data += "&username=" + URLEncoder.encode(userName, "UTF-8");
data += "&s_course=" + URLEncoder.encode(s_course, "UTF-8");
link = "http://mangoair.in/Spinner/insert_s1.php" + data;
// link = "http://hostogen.com/mangoair10/tryrr.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
// return new String("Exception: " + e.getMessage());
// return null;
}
return null;
}
/* #Override
protected void onPostExecute(String result) {
String jsonStr = result;
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("success");
String message_result = jsonObj.getString("message");
if (query_result.equalsIgnoreCase("1")) {
Toast.makeText(context,message_result , Toast.LENGTH_LONG).show();
} else if (query_result.equalsIgnoreCase("-1")) {
Toast.makeText(context, message_result, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}*/
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equalsIgnoreCase("SUCCESS")) {
Toast.makeText(context, "Data inserted successfully. Signup successfully.", Toast.LENGTH_LONG).show();
} else if (query_result.equalsIgnoreCase("FAILURE")) {
Toast.makeText(context, "Data could not be inserted, fill all records.", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Get the value from the spinner as a string and just pass this string like a normal string

Trying to query for Facebook profiles and sort them into a ListView Android

I am using the Facebook Graph API to request a list of Facebook profiles and return them in a ListView displaying both names and profile pictures. I have two EditText fields in my main acitivty to enter both first and second names. A button starts my ListViewActivity when clicked and the names are passed. The ListView inflates and the request is sent to Facebook and each row in the ListView is updated using a custom adapter.
The problem is, I suspect, a memory leak. It is very temperamental as in, it would work once or twice if I'm lucky and any other attempts to update the ListView wouldn't work, the activity would remain blank. It doesn't work for some more common names either.
Below is my ListViewActivity:
public class ListViewActivity extends Activity implements OnItemClickListener {
public String firstname, secondname;
URL imageURL;
ArrayList<String> names = new ArrayList<String>();
ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
public static final String[] descriptions = new String[] {"Description"};
ListView listView;
List<RowItem> rowItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
loadData();
rowItems = new ArrayList<RowItem>();
listView = (ListView) findViewById(R.id.listview);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
public void loadData() {
Session session = Session.getActiveSession();
firstname = getIntent().getExtras().getString("firstname");
secondname = getIntent().getExtras().getString("secondname");
if(session==null){
session = Session.openActiveSessionFromCache(this);
} else if (session.isOpened()) {
Bundle params = new Bundle();
params.putString("fields", "name, picture, url, id");
params.putString("limit", "10");
Request request = new Request(session, "search?q="+ firstname + "%20" + secondname + "&limit=10&type=user&fields=name,picture", params, HttpMethod.GET, new Request.Callback() {
#Override
public void onCompleted(Response response) {
// TODO Auto-generated method stub
JSONObject jsonObject = null;
JSONArray jArray = null;
imageURL = null;
try {
jsonObject = new JSONObject(response.getGraphObject().getInnerJSONObject().toString());
jArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject element = null;
element = jArray.getJSONObject(i);
imageURL = new URL("http://graph.facebook.com/"+ element.get("id") +"/picture?type=large");
names.add(element.getString("name").toString());
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
bitmaps.add(BitmapFactory.decodeStream(imageURL.openConnection().getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
thread.start();
thread.join();
if (bitmaps.size() == jArray.length()) {
for (int j=0; j<jArray.length(); j++) {
RowItem item = new RowItem(bitmaps.get(j), names.get(j), descriptions[0]);
rowItems.add(item);
}
}
}
} catch (JSONException e) {
System.out.println("JSON EXCEPTION:"+ e);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
} else {
Log.d("close", " ");
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
Would appreciate it if someone could help spot a memory leak (if that is indeed the issue because i'm getting between 7 - 10% free) and advise whether there is a better way of implementing this? Thanks
EDIT: Just to clarify I'm updating the list by going back to the main activity to enter a new name in the edit text fields and clicking the button to start the list view again
Does scaling the images help any?
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
I added in those two lines at line 67
public class ListViewActivity extends Activity implements OnItemClickListener {
public String firstname, secondname;
URL imageURL;
ArrayList<String> names = new ArrayList<String>();
ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
public static final String[] descriptions = new String[] {"Description"};
ListView listView;
List<RowItem> rowItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
loadData();
rowItems = new ArrayList<RowItem>();
listView = (ListView) findViewById(R.id.listview);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.list_item, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
public void loadData() {
Session session = Session.getActiveSession();
firstname = getIntent().getExtras().getString("firstname");
secondname = getIntent().getExtras().getString("secondname");
if(session==null){
session = Session.openActiveSessionFromCache(this);
} else if (session.isOpened()) {
Bundle params = new Bundle();
params.putString("fields", "name, picture, url, id");
params.putString("limit", "10");
Request request = new Request(session, "search?q="+ firstname + "%20" + secondname + "&limit=10&type=user&fields=name,picture", params, HttpMethod.GET, new Request.Callback() {
#Override
public void onCompleted(Response response) {
// TODO Auto-generated method stub
JSONObject jsonObject = null;
JSONArray jArray = null;
imageURL = null;
try {
jsonObject = new JSONObject(response.getGraphObject().getInnerJSONObject().toString());
jArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject element = null;
element = jArray.getJSONObject(i);
imageURL = new URL("http://graph.facebook.com/"+ element.get("id") +"/picture?type=large");
names.add(element.getString("name").toString());
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
bitmaps.add(BitmapFactory.decodeStream(imageURL.openConnection().getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
thread.start();
thread.join();
if (bitmaps.size() == jArray.length()) {
for (int j=0; j<jArray.length(); j++) {
RowItem item = new RowItem(bitmaps.get(j), names.get(j), descriptions[0]);
rowItems.add(item);
}
}
}
} catch (JSONException e) {
System.out.println("JSON EXCEPTION:"+ e);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
} else {
Log.d("close", " ");
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}

Data load everytime when call activity from server

When I call asynctask function data is load and display in listview but whenever i go into this activity everytime that function execute and load data again. But I just want that function call only once and display in listview. So what is the solution for that.
This is My full class code:
public class Feed extends Fragment implements
PullToRefreshAttacher.OnRefreshListener {
Button btnSlider;
ListView lv;
String userid, success, message, eventType, feed_title, feed_desc,
timeDate, like, commemt, Feeduserid, photo, posted, hasLike,
latsId, noMore, feed_id, category_id, feedImg, result;
InputStream is;
ProgressDialog pDialog;
InterNetConnectionDetector isNet = new InterNetConnectionDetector(
getActivity());
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
FeedAdapter fdp;
HashMap<String, String> map;
private uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher mPullToRefreshAttacher;
int limit = 5;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
v = inflater.inflate(R.layout.feed, container, false);
if (android.os.Build.VERSION.SDK_INT > 8) {
StrictMode.ThreadPolicy stp = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(stp);
}
SharedPreferences pref = getActivity().getSharedPreferences("Login",
Activity.MODE_PRIVATE);
userid = pref.getString("user_id", "user_id");
btnSlider = (Button) v.findViewById(R.id.btnSlide);
lv = (ListView) v.findViewById(R.id.feed_ListView);
btnSlider.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
Sliding.viewActionsContentView.showActions();
} catch (Exception e) {
// TODO: handle exception
}
}
});
try {
if (fdp == null) {
new FeedData().execute();
} else {
lv.setAdapter(fdp);
}
} catch (Exception e) {
// TODO: handle exception
}
mPullToRefreshAttacher = new uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher(
getActivity(), lv);
// Set Listener to know when a refresh should be started
mPullToRefreshAttacher
.setRefreshListener((uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher.OnRefreshListener) this);
((LoadMore) lv)
.setOnLoadMoreListener(new com.example.getconnected.LoadImage.LoadMore.OnLoadMoreListener() {
public void onLoadMore() {
// Do the work to load more items at the end of list
// here
new LoadDataTask().execute();
}
});
return v;
}
/*
* #Override protected void onCreate(Bundle savedInstanceState) { // TODO
* Auto-generated method stub super.onCreate(savedInstanceState);
* setContentView(R.layout.feed);
*
* if (Build.VERSION.SDK_INT >= 8) { getActionBar().hide(); }
*
* if (android.os.Build.VERSION.SDK_INT > 8) {
*
* StrictMode.ThreadPolicy stp = new StrictMode.ThreadPolicy.Builder()
* .permitAll().build(); StrictMode.setThreadPolicy(stp);
*
* }
*
* try { new FeedData().execute();
*
* } catch (Exception e) { // TODO: handle exception }
*
* SharedPreferences pref = getSharedPreferences("Login",
* Activity.MODE_PRIVATE); userid = pref.getString("user_id", "user_id");
*
* btnSlider = (Button) findViewById(R.id.btnSlide); lv = (ListView)
* findViewById(R.id.feed_ListView); btnSlider.setOnClickListener(new
* OnClickListener() {
*
* #Override public void onClick(View arg0) { // TODO Auto-generated method
* stub
*
* int width = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
* 40, getResources() .getDisplayMetrics());
* SlideoutActivity.prepare(getActivity(), R.id.inner_content, width);
* startActivity(new Intent(getActivity(), MenuActivity.class));
* getoverridePendingTransition(0, 0);
*
* } });
*
* mPullToRefreshAttacher = new PullToRefreshAttacher(getActivity(), lv);
*
* // Set Listener to know when a refresh should be started
* mPullToRefreshAttacher .setRefreshListener((OnRefreshListener)
* getActivity());
*
* ((LoadMore) lv) .setOnLoadMoreListener(new
* com.example.getconnected.LoadImage.LoadMore.OnLoadMoreListener() { public
* void onLoadMore() { // Do the work to load more items at the end of list
* // here new LoadDataTask().execute(); } }); }
*/
public class FeedData extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = ProgressDialog.show(getActivity(), "", "Loading..");
pDialog.setCancelable(true);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// data=jobj.toString();
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://www.sevenstarinfotech.com/projects/demo/GetConnected/api/feed.php?user_id="
+ userid + "&" + "limit=" + limit;
HttpPost httppost = new HttpPost(url);
Log.v("Feed Url:", url);
httppost.addHeader("Content-Type",
"application/x-www-form-urlencoded");
httppost.addHeader("app-key",
"b51bc98b4d6fd0456f7f1b17278415fa49de57d5");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
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();
result = sb.toString();
Log.v("Response is:", result);
} catch (Exception e3) {
Log.e("log_tag", "Error converting result " + e3.toString());
}
// parse json data
try {
JSONObject ja = new JSONObject(result);
JSONObject jdata = ja.getJSONObject("data");
success = jdata.getString("Success");
message = jdata.getString("Message");
latsId = jdata.getString("lastId");
noMore = jdata.getString("nomore");
JSONArray jArray = jdata.getJSONArray("Feeddetails");
for (int i = 0; i < jArray.length(); i++) {
map = new HashMap<String, String>();
JSONObject me = jArray.getJSONObject(i);
map.put("sucess", success);
map.put("message", message);
map.put("latsId", latsId);
map.put("noMore", noMore);
eventType = me.getString("type");
feed_id = me.getString("feed_id");
feed_title = me.getString("feed_title");
category_id = me.getString("category_id");
feed_desc = me.getString("feed_desc");
timeDate = me.getString("timeposted");
posted = me.getString("postedby");
like = me.getString("likes");
photo = me.getString("photo");
commemt = me.getString("comments");
Feeduserid = me.getString("user_id");
hasLike = me.getString("hasliked");
map.put("eventType", eventType);
map.put("feed_id", feed_id);
map.put("feed_title", feed_title);
map.put("category_id", category_id);
map.put("feed_desc", feed_desc);
map.put("timeDate", timeDate);
map.put("posted", posted);
map.put("like", like);
map.put("photo", photo);
map.put("commemt", commemt);
map.put("Feeduserid", Feeduserid);
map.put("hasLike", hasLike);
Log.v("Data:", feed_id + "/" + "/" + "/" + Feeduserid
+ "/" + "/" + "/" + like + "/" + "/" + "/"
+ commemt);
contactList.add(map);
}
Log.v("Length", contactList.size() + "");
} catch (Exception e1) {
Log.e("log_tag",
"Error in http connection " + e1.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
pDialog.dismiss();
fdp = new FeedAdapter(getActivity(), contactList);
lv.setAdapter(fdp);
}
}
#Override
public void onRefreshStarted(View view) {
/**
* Simulate Refresh with 4 seconds sleep
*/
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Notify PullToRefreshAttacher that the refresh has finished
mPullToRefreshAttacher.setRefreshComplete();
}
}.execute();
}
private class LoadDataTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
if (isCancelled()) {
return null;
}
// Simulates a background task
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
limit += 5;
DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://www.sevenstarinfotech.com/projects/demo/GetConnected/api/feed.php?user_id="
+ userid + "&" + "limit=" + limit;
HttpPost httppost = new HttpPost(url);
Log.v("Feed Url:", url);
httppost.addHeader("Content-Type",
"application/x-www-form-urlencoded");
httppost.addHeader("app-key",
"b51bc98b4d6fd0456f7f1b17278415fa49de57d5");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
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();
result = sb.toString();
Log.v("Response is:", result);
} catch (Exception e3) {
Log.e("log_tag", "Error converting result " + e3.toString());
}
// parse json data
try {
JSONObject ja = new JSONObject(result);
JSONObject jdata = ja.getJSONObject("data");
success = jdata.getString("Success");
message = jdata.getString("Message");
latsId = jdata.getString("lastId");
noMore = jdata.getString("nomore");
JSONArray jArray = jdata.getJSONArray("Feeddetails");
for (int i = 0; i < jArray.length(); i++) {
map = new HashMap<String, String>();
JSONObject me = jArray.getJSONObject(i);
map.put("sucess", success);
map.put("message", message);
map.put("latsId", latsId);
map.put("noMore", noMore);
eventType = me.getString("type");
feed_id = me.getString("feed_id");
feed_title = me.getString("feed_title");
category_id = me.getString("category_id");
feed_desc = me.getString("feed_desc");
timeDate = me.getString("timeposted");
posted = me.getString("postedby");
like = me.getString("likes");
photo = me.getString("photo");
commemt = me.getString("comments");
Feeduserid = me.getString("user_id");
hasLike = me.getString("hasliked");
map.put("eventType", eventType);
map.put("feed_id", feed_id);
map.put("feed_title", feed_title);
map.put("category_id", category_id);
map.put("feed_desc", feed_desc);
map.put("timeDate", timeDate);
map.put("posted", posted);
map.put("like", like);
map.put("photo", photo);
map.put("commemt", commemt);
map.put("Feeduserid", Feeduserid);
map.put("hasLike", hasLike);
Log.v("Data:", feed_id + "/" + "/" + "/" + Feeduserid
+ "/" + "/" + "/" + like + "/" + "/" + "/"
+ commemt);
contactList.add(map);
}
pDialog.dismiss();
fdp = new FeedAdapter(getActivity(), contactList);
lv.setAdapter(fdp);
} catch (Exception e1) {
Log.e("log_tag",
"Error in http connection " + e1.toString());
}
} catch (Exception e) {
// TODO: handle exception
}
// mListItems.add("Added after load more");
// We need notify the adapter that the data have been changed
fdp.notifyDataSetChanged();
// Call onLoadMoreComplete when the LoadMore task, has finished
((LoadMore) lv).onLoadMoreComplete();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
((LoadMore) lv).onLoadMoreComplete();
}
}
}
Better option is like, just declare your ADAPTER as public static in your ROOT class or in your activity. This will make single copy. And you are done with.
Suppose you have following structure.
ABC (ROOT/SPLASH) Activity -> class Feed extends Fragment
So basically you are calling Feed from ABC. Inside ABC, declare like
public class ABC...{
public static FeedAdapter fdp;
//.. all other stuffs
}
public class Feed...{
//.. to use that object delcared in ABC
ABC.fdp = new FeedAdapter(...);
}

listView does not refresh with new values

I have a problem while refreshing the list view from old values to new values.
Through a search for many hours i have got that adapter.notifyDataSetChanged(); has to be used.
But i am unable to understand how do i use it as whenever i use it gives me an error
"The method notifyDataSetChanged() is undefined for the type ListAdapter"
i am not sure whether i am doing the right thing. please Help...
This is my Code
public class Slider extends Activity implements OnClickListener,
OnDrawerOpenListener, OnDrawerCloseListener {
Button mCloseButton;
Button mOpenButton;
MultiDirectionSlidingDrawer mDrawer;
ListView list;
TextView t1;
String data, query, is;
Spinner d;
String FILENAME = "http://24.php";
ArrayList<String> pos;
ListAdapter adapter;
ArrayList<HashMap<String, String>> mylist;
HashMap<String, String> map;
static String j_id = null;
static Object j_make = null;
static String j_model = null;
static String j_version = null;
static String j_price = null;
static String j_reg_plc = null;
String ID = "car_id";
String MAKE = "make";
String MODEL = "model";
String VERSION = "version";
String PRICE = "expected_price";
String PLACE_REG = "registration_place";
CheckBox cb1, cb2, cb3, cb4, cb5, cb6, cb7, cb8, cb9, cb10;
Spinner sp1;
int flag = 0;
String drive[] = new String[] { "Select Drive", "Two-Wheel Drive",
"Four-Wheel Drive", "All-Wheel Drive" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.slider);
t1 = (TextView) findViewById(R.id.noRec);
list = (ListView) findViewById(R.id.listView1);
cb1 = (CheckBox) findViewById(R.id.checkBox1);
cb2 = (CheckBox) findViewById(R.id.checkBox2);
cb3 = (CheckBox) findViewById(R.id.checkBox3);
cb4 = (CheckBox) findViewById(R.id.checkBox4);
cb5 = (CheckBox) findViewById(R.id.checkBox5);
cb6 = (CheckBox) findViewById(R.id.checkBox6);
cb7 = (CheckBox) findViewById(R.id.checkBox7);
cb8 = (CheckBox) findViewById(R.id.checkBox8);
cb9 = (CheckBox) findViewById(R.id.checkBox9);
cb10 = (CheckBox) findViewById(R.id.checkBox10);
d = (Spinner) findViewById(R.id.drive);
#SuppressWarnings("unchecked")
ArrayAdapter spdrv = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, drive);
d.setAdapter(spdrv);
t1.setVisibility(View.GONE);
mylist = new ArrayList<HashMap<String, String>>();
pos = new ArrayList<String>();
Bundle bundle = getIntent().getExtras();
String stuff = bundle.getString("stuff");
Toast.makeText(getApplicationContext(), "Stuff= |" + stuff + "|",
Toast.LENGTH_LONG).show();
if (stuff.contains("null")) {
t1.setVisibility(View.VISIBLE);
t1.setText("No Records Found");
Toast.makeText(getApplicationContext(), "No Records Found!",
Toast.LENGTH_LONG).show();
} else {
load_list(stuff); //Load list with values
}
mCloseButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
flag = 1;
query = "Select make, model, version, expected_price, registration_place FROM `used_cars` where registration_place ="
+ "'" + j_reg_plc + "'";
if (cb1.isChecked()) {
query = query + " AND transmission ='Yes'";
}
if (cb2.isChecked()) {
query = query + " AND ac ='Yes'";
}
if (cb3.isChecked()) {
query = query + " AND car_lockk ='Yes'";
}
if (cb4.isChecked()) {
query = query + " AND sunroof ='Yes'";
}
if (cb5.isChecked()) {
query = query + " AND window ='Yes'";
}
if (cb6.isChecked()) {
query = query + " AND seats ='Yes'";
}
if (cb7.isChecked()) {
query = query + " AND stearing ='Yes'";
}
if (cb8.isChecked()) {
query = query + " AND player ='Yes'";
}
if (cb9.isChecked()) {
query = query + " AND sound_system ='Yes'";
}
if (cb10.isChecked()) {
query = query + " AND wheels ='Yes'";
}
query = query + ";";
Toast.makeText(getApplicationContext(), "QUERY= " + query,
Toast.LENGTH_LONG).show();
System.out.println("QUERY= " + query);
startDownload();
mDrawer.animateClose();
}
});
mOpenButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!mDrawer.isOpened())
mDrawer.animateOpen();
}
});
}
private void startDownload() {
new AppTask().execute(FILENAME);
}
public class AppTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), "res" + result,
Toast.LENGTH_LONG).show();
pos = new ArrayList<String>();
mylist.clear();
load_list(result); //Refresh list with new values
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://animsinc.com/filter.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
5);
nameValuePairs.add(new BasicNameValuePair("Qry", query));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
}
return is;
}
}
#Override
public void onContentChanged() {
super.onContentChanged();
mCloseButton = (Button) findViewById(R.id.button_close);
mOpenButton = (Button) findViewById(R.id.button_open);
mDrawer = (MultiDirectionSlidingDrawer) findViewById(R.id.drawer);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onDrawerClosed() {
// TODO Auto-generated method stub
// demo.setVisibility(View.VISIBLE);
}
#Override
public void onDrawerOpened() {
// TODO Auto-generated method stub
// demo.setVisibility(View.GONE);
}
public void load_list(String lt) {
// list.setAdapter(null);
Toast.makeText(getApplicationContext(), "Inside load_list", 100).show();
try {
JSONArray jArray = new JSONArray(lt.toString());
for (int i = 0; i < jArray.length(); i++) {
Toast.makeText(getApplicationContext(),
"Inside load_list----FOR", 100).show();
map = new HashMap<String, String>();
JSONObject jObject = jArray.getJSONObject(i);
j_id = jObject.getString(ID);
j_make = jObject.getString(MAKE);
j_model = jObject.getString(MODEL);
j_version = jObject.getString(VERSION);
j_price = jObject.getString(PRICE);
j_reg_plc = jObject.getString(PLACE_REG);
data = j_make + "";
map.put("make", data);
data = j_model + "";
map.put("model", data);
data = j_version + "";
map.put("version", data);
data = j_price + "";
map.put("price", data);
data = j_reg_plc + "";
map.put("place", data);
mylist.add(map);
pos.add(j_id);
}
} catch (JSONException e) {
e.printStackTrace();
}
list = (ListView) findViewById(R.id.listView1);
String[] from = new String[] { "make", "model", "version", "price",
"place" };
int[] to = new int[] { R.id.text1, R.id.text5, R.id.text3, R.id.text4,
R.id.text2 };
adapter = new SimpleAdapter(this, mylist, R.layout.text_adaptr, from,
to);
Toast.makeText(getApplicationContext(), "B4 list setAdapter", 100)
.show();
// mylist.notifyDataSetChanged();
list.setAdapter(adapter);
// ---------------------------------
int[] colors = { 0, 0xff00ffff, 0 }; // red for the example
list.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
list.setDividerHeight(4);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String data = pos.get(position) + "";
Toast.makeText(getApplicationContext(), "data: " + data,
Toast.LENGTH_LONG).show();
// Display_Car dc=new Display_Car();
// dc.get_cid(data);
Intent myIntent = new Intent(Slider.this, Buy_View.class);
Bundle bundle = new Bundle();
// Add your data to bundle
bundle.putString("stuff", data);
// Add the bundle to the intent
myIntent.putExtras(bundle);
startActivity(myIntent);
}
});
// ---------------------------------
}
}
Try this,
You can use the runOnUiThread method as follows. If you're not using a ListActivity, just adapt the code to get a reference to your ArrayAdapter.
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
Try this:
list.setAdapter(adapter);
adapter.notifyDatasetChanged();
You have to remember notifyDataSetChanged() works only when the data inside the adapter has changed, and it rerenders the list. In your case you change the data externally, so you have to change the data inside the adapter.
In such cases, use something like
((ItemArrayAdapter)lv.getAdapter()).notifyDataSetChanged() instead of adapter.notifyDataSetChanged()
SimpleAdapter is a BaseAdapter. Change
ListAdapter adapter;
to
BaseAdapter adapter;
or SimpleAdapter adapter;

Categories

Resources