I need to set my app content offline - android

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;
}

Related

Unable to parse JSON data into Listview

im trying to parse data from SQL Database into Listview.
My PHP script is working because if i run it in the browser i get the content.
If im trying to get the data from my SQL Databse into the listview my app shows nothing.
Here is my MainActivity:
public class Locations extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<productforloc> arrayList;
ListView lv;
private String TAG = Locations.class.getSimpleName();
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
int i = 1;
private ProgressDialog pDialog;
String name;
// URL to get contacts JSON
private static String url = "Mylink";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Intent i = getIntent();
String cityname = i.getExtras().getString("cityname");
TextView city = (TextView) findViewById(R.id.ort);
city.setText(cityname);
pDialog = new ProgressDialog(Locations.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(true);
pDialog.show();
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener((AdapterView.OnItemClickListener) this);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
final ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.VISIBLE);
ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setVisibility(View.VISIBLE);
filteropen.setVisibility(View.INVISIBLE);
}
});
final ImageButton filterclose = (ImageButton) findViewById(R.id.zuklappen);
filterclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout filter = (RelativeLayout) findViewById(R.id.filterloc);
filter.setVisibility(View.INVISIBLE);
ImageButton filteropen = (ImageButton) findViewById(R.id.aufklaupen);
filteropen.setVisibility(View.VISIBLE);
filterclose.setVisibility(View.INVISIBLE);
}
});
}
class ReadJSON extends AsyncTask<String,Integer,String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try{
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
arrayList.add(new productforloc(
po.getString("imageurl"),
po.getString("name"),
po.getString("street"),
po.getString("postalcode"),
po.getString("musicstyle"),
po.getString("musicsecond"),
po.getString("entry"),
po.getString("opening"),
po.getString("agegroup"),
po.getString("urlbtn"),
po.getString("Fsk"),
po.getString("city"),
po.getString("bg")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
final CustomListAdapterforloc adapter = new CustomListAdapterforloc(getApplicationContext(),R.layout.model,arrayList);
lv.setAdapter(adapter);
if(pDialog.isShowing()){
pDialog.dismiss();
}
}
}
private String readURL(String url){
StringBuilder content = new StringBuilder();
try{
URL uri = new URL(url);
URLConnection urlConnection = uri.openConnection();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) !=null){
content.append(line+"\n");
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productforloc pForloc = arrayList.get(position);
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",pForloc.getName());
intent.putExtra("imageurl",pForloc.getImage());
intent.putExtra("street",pForloc.getStreet());
intent.putExtra("postalcode",pForloc.getPostalcode());
intent.putExtra("entry",pForloc.getEntry());
intent.putExtra("agegroup",pForloc.getAgegroup());
intent.putExtra("opening",pForloc.getOpening());
intent.putExtra("urlbtn",pForloc.getUrlbtn());
intent.putExtra("Fsk",pForloc.getFsk());
intent.putExtra("city",pForloc.getCity());
intent.putExtra("musicstyle",pForloc.getMusicstyle());
intent.putExtra("musicsecond",pForloc.getMusicsecond());
intent.putExtra("bg",pForloc.getBg());
startActivity(intent);
}
/**
* Async task class to get json by making HTTP call
}
*/
}
and here is my Customlistadapter Activity:
public class CustomListAdapterforloc extends ArrayAdapter<productforloc>{
ArrayList<productforloc> products;
Context context;
int resource;
public CustomListAdapterforloc(Context context, int resource, List<productforloc> products) {
super(context, resource, products);
this.products = (ArrayList<productforloc>) products;
this.context = context;
this.resource = resource;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView== null){
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.model,null,true);
}
productforloc product = getItem(position);
ImageView imageView = (ImageView) convertView.findViewById(R.id.imagelist);
Picasso.with(context).load(product.getImage()).into(imageView);
TextView txtName= (TextView) convertView.findViewById(R.id.namelist);
txtName.setText(product.getName());
return convertView;
}
}
i solved it using this code in my MAinActivity:
public class Locations extends AppCompatActivity {
private String TAG = Locations.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://partypeople.bplaced.net/loli.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
new GetContacts().execute();
}
/**
* 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(Locations.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray contacts = new JSONArray(jsonStr);
// Getting JSON Array node
// 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");
// 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);
// 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();
/**3
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Locations.this, contactList,
R.layout.model, new String[]{"name", "email",
"mobile"}, new int[]{R.id.namelist,
});
lv.setAdapter(adapter);
}
}
and used in my CustomlistadapterActivity:
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Thanks for your input
Override getCount method into adapter class.

code which one should I change to throw button and instantly displays my listview without having to click a button

code which one should I change to throw button and instantly displays my listview without having to click a button
public class MainActivity extends AppCompatActivity {
Button btnLoadFeed; <<<<<------------- Which should I remove associated with this code?
TextView textViewFeedUrl;
ListView listViewFeed;
List<FeedItem> listFeedItems;
ListAdapter adapterFeed;
String myFeed = "http://temfilm.blogspot.co.id/feeds/posts/default?alt=json";
//String myFeed = "http://arduino-er.blogspot.com/feeds/posts/default?alt=json";
//String myFeed = "http://helloraspberrypi.blogspot.com/feeds/posts/default?alt=json";
//String myFeed = "http://photo-er.blogspot.com/feeds/posts/default?alt=json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLoadFeed = (Button)findViewById(R.id.loadfeed);
textViewFeedUrl = (TextView)findViewById(R.id.feedurl);
setContentView(R.layout.layout_feed);
listViewFeed = (ListView)findViewById(R.id.listviewfeed);
listFeedItems = new ArrayList<>();
adapterFeed = new ArrayAdapter<FeedItem>(
this, android.R.layout.simple_list_item_1, listFeedItems);
listViewFeed.setAdapter(adapterFeed);
btnLoadFeed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textViewFeedUrl.setText(myFeed);
new JsonTask(listFeedItems, listViewFeed).execute(myFeed);
}
});
}
/*
JsonTask:
AsyncTask to download and parse JSON Feed of blogspot in background
*/
private class JsonTask extends AsyncTask<String, FeedItem, String> {
List<FeedItem> jsonTaskList;
ListView jsonTaskListView;
public JsonTask(List<FeedItem> targetList, ListView targetListView) {
super();
jsonTaskList = targetList;
jsonTaskListView = targetListView;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
jsonTaskList.clear();
jsonTaskListView.invalidateViews();
}
#Override
protected String doInBackground(String... params) {
try {
final String queryResult = sendQuery(params[0]);
parseQueryResult(queryResult);
} catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
eString,
Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
final String eString = e.toString();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
eString,
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onProgressUpdate(FeedItem... values) {
FeedItem newItem = values[0];
jsonTaskList.add(newItem);
jsonTaskListView.invalidateViews();
}
private String sendQuery(String query) throws IOException {
String queryReturn = "";
URL queryURL = new URL(query);
HttpURLConnection httpURLConnection = (HttpURLConnection)queryURL.openConnection();
if(httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader inputStreamReader =
new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader, 8192);
String line = null;
while((line = bufferedReader.readLine()) != null){
queryReturn += line;
}
bufferedReader.close();
}
return queryReturn;
}
private void parseQueryResult(String json) throws JSONException {
JSONObject jsonObject = new JSONObject(json);
final JSONObject jsonObject_feed = jsonObject.getJSONObject("feed");
final JSONArray jsonArray_entry = jsonObject_feed.getJSONArray("entry");
runOnUiThread(new Runnable() {
#Override
public void run() {
if(jsonArray_entry == null){
Toast.makeText(MainActivity.this,
"jsonArray_entry == null",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this,
String.valueOf(jsonArray_entry.length()),
Toast.LENGTH_LONG).show();
for(int i=0; i<jsonArray_entry.length(); i++){
try {
JSONObject thisEntry = (JSONObject) jsonArray_entry.get(i);
JSONObject thisEntryTitle = thisEntry.getJSONObject("title");
String thisEntryTitleString = thisEntryTitle.getString("$t");
JSONArray jsonArray_EntryLink = thisEntry.getJSONArray("link");
//search for the link element with rel="alternate"
//I assume it's one and only one element with rel="alternate",
//and its href hold the link to the page
for(int j=0; j<jsonArray_EntryLink.length(); j++){
JSONObject thisLink = (JSONObject) jsonArray_EntryLink.get(j);
try{
String thisLinkRel = thisLink.getString("rel");
if(thisLinkRel.equals("alternate")){
try{
String thisLinkHref = thisLink.getString("href");
FeedItem thisElement = new FeedItem(
thisEntryTitleString.toString(),
thisLinkHref);
publishProgress(thisElement);
break;
}catch (JSONException e){
//no such mapping exists
}
}
}catch (JSONException e){
//no such mapping exists
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
});
}
}
}

Solve startActivity in fragment

I have a problem in my code. My problem is related to the startActivity(). When the app is running on the emulator, it does not work. The line causing the problem is described in the end.
I tried to open a new activity (this, newactivity.class), however the problem persists.
UpdateAnsList
public class UpdateAnsList extends Fragment{
/**
* #param args
*/
final static String ARG_POSITION_ANSWER = "position";
private String jsonResult;
private ListView listView;
public int selsub;
public Activity activity;
public String tagsub;
private Context mContext;
private Activity mact;
public UpdateAnsList(Activity _activity){
mact = _activity;
this.activity = _activity;
super.onAttach(_activity);
mContext = this.activity.getApplicationContext();
}
public enum SubSectionAnswer {
TagArt,
TagBio
}
public void StartUpdateAnsList(int v, String o){
tagsub = o;
selsub = v;
SubSectionAnswer currentSub = SubSectionAnswer.valueOf(tagsub);
listView = (ListView) this.activity.findViewById(R.id.listView11);
selectItemAns(selsub,currentSub);
accessWebService();
}
private void selectItemAns(int position, SubSectionAnswer currentSub) {
switch(currentSub){
case TagArt:
switch(position){
case R.id.buttonArt001:
url = "myip/newfolder/question_2.php";
tagdb = "info_general";
break;
case R.id.buttonArt002:
url = "http://myip/newfolder/question_1.php";
tagdb = "info_animation";
break;
case 2:
break;
}
break;
case TagBio:
switch(position){
case R.id.ButtonBio001:
url = "http://myip/newfolder/question_4.php";
tagdb = "info_general";
break;
case R.id.buttonBio002:
url = "http://myip/newfolder/question_5.php";
tagdb = "info_evolution";
break;
case 2:
break;
}
break;
}
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
//Toast.makeText(getApplicationContext(),
// "Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray(tagdb);
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("employee name");
String number = jsonChildNode.optString("content_text");
//String outPut = name + "-" + number;
String outPut = name;
String outPut1 = number;
employeeList.add(createEmployee("Question", outPut,"textlong",number));
}
} catch (JSONException e) {
Toast.makeText(this.activity, "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
//new String[] { "employees" }
//new int[] { android.R.id.text1 }
String[] de = {"Question", "textlong"};
int[] para ={R.id.textView1list11, R.id.textView11 };
SimpleAdapter simpleAdapter = new SimpleAdapter(this.activity, employeeList,
R.layout.activity_item_list_answer,
de, para);
listView.setAdapter(simpleAdapter);
listView.setOnItemClickListener(new ListClickHandler());
//Toast.makeText(getApplication(), "c", Toast.LENGTH_SHORT).show();
}
public class ListClickHandler implements OnItemClickListener{
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) {
// TODO Auto-generated method stub
int a =1 ;
//Toast.makeText(mContext, "c", Toast.LENGTH_SHORT).show();
//Intent i = new Intent(mact, QuestionActivity.class);
//mContext.startActivity(i);
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, "test");
// catch event that there's no activity to handle intent
mContext.startActivity(intent);
}
}
private HashMap<String, String> createEmployee(String s1, String s2, String s3,String s4) {
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(s1, s2);
employeeNameNo.put(s3, s4);
return employeeNameNo;
}
}
This is the line causing the problem:
mContext.startActivity(intent);
Screen of debug:
Screen when I use getActivity():
You should start new Activity using Activity context:
getActivity.startActivity(intent);
This is a Fragment class, so you are not able to pass an Intentby simply writing this.startActivity();
What you need to do is to get the Activity of this Fragment class.
So instead of mContext.startActivity(intent); you should write :
getActivity().startActivity(intent);
Basically you are working with Fragment:
How to Start Activity from Fragment:
mContext.startActivity(intent);
Edit 1:
private Context mContext;
public void StartUpdateAnsList(Context ctx, int v, String o){
mContext = ctx;
tagsub = o;
selsub = v;
SubSectionAnswer currentSub = SubSectionAnswer.valueOf(tagsub);
listView = (ListView) this.activity.findViewById(R.id.listView11);
selectItemAns(selsub,currentSub);
accessWebService();
}
Now you can use: mContext.startActivity(intent);
Hope this will help you.

Android - get photos from database with AsyncTask - doInBackGround not starting

I'm having a problem with my program. I'm calling my getImages() function in onCreate() but when I tried debugging it, I discovered that doInBackground() function doesn't actually start. I've seen many people had the same problem but none of the solutions provided were of any help.
Here is how my main activity looks like:
public class poi_photos extends ActionBarActivity {
public static ArrayList<String> image_urls = new ArrayList<>();
public static GridView gridView;
// Retrieve PHOTOS from database
String myJSON;
private static final String TAG_RESULTS = "result";
private static final String TAG_EMAIL_USER = "email_user";
private static final String TAG_POI_NAME = "poi_name";
private static final String TAG_PHOTO_URL = "photo_url";
JSONArray photos = null;
ArrayList<HashMap<String, String>> photoList;
ArrayList<HashMap<String, Integer>> numsList;
// GALLERY
private FeatureCoverFlow mCoverFlow;
private CoverFlowAdapter Adapter;
private ArrayList<GameEntity> mData = new ArrayList<>(0);
private TextSwitcher mTitle;
String photo_url2;
// Camera Activity
Button btpic, btnup;
private Uri fileUri;
String picturePath;
Uri selectedImage;
Bitmap photo;
String ba1;
static int TAKE_PICTURE = 1;
// MENU
String TITLES[] = {"Home", "Profile", "Travel", "POIs Map", "Find your friends!", "Take Picture"};
int ICONS[] = {R.drawable.ic_home, R.drawable.ic_prof, R.drawable.ic_travel, R.drawable.ic_poi, R.drawable.ic_friends_map, R.drawable.ic_photo};
String NAME = MainActivity.username;
String EMAIL = MainActivity.user_email;
private Toolbar toolbar; // Declaring the Toolbar Object
RecyclerView mRecyclerView; // Declaring RecyclerView
RecyclerView.Adapter mAdapter; // Declaring Adapter For Recycler View
RecyclerView.LayoutManager mLayoutManager; // Declaring Layout Manager as a linear layout manager
DrawerLayout Drawer; // Declaring DrawerLayout
ActionBarDrawerToggle mDrawerToggle; // Declaring Action Bar Drawer Toggle
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poi_photos);
FloatingActionButton add_comment = (FloatingActionButton) findViewById(R.id.button_poi_comments);
add_comment.setBackgroundTintList(getResources().getColorStateList(R.color.Blonde));
add_comment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(poi_photos.this, MarkerActivity.class));
}
});
FloatingActionButton see_photos = (FloatingActionButton) findViewById(R.id.button_add_photo);
see_photos.setBackgroundTintList(getResources().getColorStateList(R.color.Blonde));
see_photos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takepic();
}
});
image_urls.clear();
if (image_urls.isEmpty())
{
getImages();
}
gridView = (GridView) findViewById(R.id.gridview);
final ImageAdapter adapter = new ImageAdapter(this);
// adapter.notifyDataSetChanged();
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(poi_photos.this, ImageActivity.class);
intent.putExtra("url", adapter.imageUrls.get(position));
startActivity(intent);
}
});
// MENU
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); // Assigning the RecyclerView Object to the xml View
mRecyclerView.setHasFixedSize(true); // Letting the system know that the list objects are of fixed size
mAdapter = new MyAdapter(TITLES, ICONS, NAME, EMAIL, this); // Creating the Adapter of MyAdapter class(which we are going to see in a bit)
// And passing the titles,icons,header view name, header view email,
// and header view profile picture
mRecyclerView.setAdapter(mAdapter); // Setting the adapter to RecyclerView
mLayoutManager = new LinearLayoutManager(this); // Creating a layout Manager
mRecyclerView.setLayoutManager(mLayoutManager); // Setting the layout Manager
final GestureDetector mGestureDetector = new GestureDetector(poi_photos.this, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
View child = recyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if (child != null && mGestureDetector.onTouchEvent(motionEvent)) {
Drawer.closeDrawers();
// Toast.makeText(map.this,"The Item Clicked is: "+recyclerView.getChildPosition(child),Toast.LENGTH_SHORT).show();
switch (recyclerView.getChildPosition(child)) {
case 1:
Intent a = new Intent(poi_photos.this, myprofile.class);
startActivity(a);
break;
case 2:
Intent b = new Intent(poi_photos.this, profile.class);
startActivity(b);
break;
case 3:
Intent c = new Intent(poi_photos.this, ShortPath.class);
startActivity(c);
break;
case 5:
Intent e = new Intent(poi_photos.this, FriendsMap.class);
startActivity(e);
break;
case 6:
//Camera Activity
if (hasCamera()) {
// create intent with ACTION_IMAGE_CAPTURE action
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// start camera activity
startActivityForResult(intent, TAKE_PICTURE);
}
break;
}
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
mLayoutManager = new LinearLayoutManager(this); // Creating a layout Manager
mRecyclerView.setLayoutManager(mLayoutManager); // Setting the layout Manager
Drawer = (DrawerLayout) findViewById(R.id.DrawerLayout); // Drawer object Assigned to the view
mDrawerToggle = new ActionBarDrawerToggle(this, Drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
// code here will execute once the drawer is opened( As I dont want anything happened whe drawer is
// open I am not going to put anything here)
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
// Code here will execute once drawer is closed
}
}; // Drawer Toggle Object Made
Drawer.setDrawerListener(mDrawerToggle); // Drawer Listener set to the Drawer toggle
mDrawerToggle.syncState(); // Finally we set the drawer toggle sync State
}
#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_poi_photos, 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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// method to check if you have a Camera
private boolean hasCamera() {
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
}
// CAMERA ACTIVITY
private void takepic() {
// Check Camera
if (getApplicationContext().getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// Open default camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, 100);
} else {
Toast.makeText(getApplication(), "Camera not supported", Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100 && resultCode == RESULT_OK) {
selectedImage = data.getData();
photo = (Bitmap) data.getExtras().get("data");
// Cursor to get image uri to display
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap photo = (Bitmap) data.getExtras().get("data");
// Show pop up window
LayoutInflater layoutInflater = LayoutInflater.from(poi_photos.this);
View promptView = layoutInflater.inflate(R.layout.input_photo, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(poi_photos.this);
alertDialogBuilder.setView(promptView);
ImageView imageView = (ImageView) promptView.findViewById(R.id.imageView_photo);
imageView.setImageBitmap(photo);
alertDialogBuilder.setCancelable(false)
.setPositiveButton("Keep the photo!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
upload(); // upload photo to folder
upload2(); // upload photo to database
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
// upload photo to database
private void upload() {
// Image location URL
Log.e("path", "----------------" + picturePath);
// Image
Bitmap bm = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
ba1 = Base64.encodeToString(ba, Base64.DEFAULT);
Log.e("base64", "-----" + ba1);
// Upload image to server
new uploadToServer().execute();
}
public class uploadToServer extends AsyncTask<Void, Void, String> {
private ProgressDialog pd = new ProgressDialog(poi_photos.this);
protected void onPreExecute() {
super.onPreExecute();
pd.setMessage("Wait uploading image!");
pd.show();
}
// insert photo
#Override
protected String doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
photo_url2 = map.markername + "_" + System.currentTimeMillis() + ".jpg";
nameValuePairs.add(new BasicNameValuePair("base64", ba1));
nameValuePairs.add(new BasicNameValuePair("ImageName", photo_url2));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxxx/photo.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String st = EntityUtils.toString(response.getEntity());
Log.v("log_tag", "In the try Loop " + st);
} catch (Exception e) {
Log.v("log_tag", "Error in http connection " + e.toString());
}
return "Success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
pd.hide();
pd.dismiss();
}
}
// insert photo
private void upload2() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("email_user", MainActivity.user_email));
nameValuePairs.add(new BasicNameValuePair("poi_name", map.markername));
nameValuePairs.add(new BasicNameValuePair("photo_url", photo_url2));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http:xxxxx/photo_out.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
String msg = "Data has been sent successfully";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
Log.e("ClientProtocol", "Log_Tag");
e.printStackTrace();
String msg2 = "Log_Tag";
Toast.makeText(getApplicationContext(), msg2, Toast.LENGTH_LONG).show();
} catch (IOException e) {
Log.e("Log_Tag", "IOException");
e.printStackTrace();
String msg3 = "IOException";
Toast.makeText(getApplicationContext(), msg3, Toast.LENGTH_LONG).show();
}
}
// GETTING PHOTOS FROM DATABASE
protected void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON);
photos = jsonObj.getJSONArray(TAG_RESULTS);
for (int i = 0; i < photos.length(); i++) {
JSONObject c = photos.getJSONObject(i);
String email_user = c.getString(TAG_EMAIL_USER);
String poi_name = c.getString(TAG_POI_NAME);
String photo_url = c.getString(TAG_PHOTO_URL);
if ((poi_name.substring(0, 4)).equals(map.markername) && photo_url!=null) {
// add to the picasso gallery
photo_url="http://romcad.ro/poi/photos/"+photo_url;
image_urls.add(photo_url);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getImages() {
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://xxxxx/table_photo_out.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;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
}
Any idea/ tip what might be the problem here?
Why do you write the class GetDataJSON into the method getImages()?
Try to delete the method around your class and instead of calling getImages() call
new getDataJSON().execute(yourString);

Show data on Listview is duplication

I'm doing a app can update data every 1 minutes, data will from database mysql on server to show on listview of my app android. My problem is when show data the first is ok but when show data the second on listview, data of the first and the second is duplication.Can you help me!
Source code:
public class Hoadon extends Activity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> al1 = new ArrayList<String>();
ArrayList<String> al2 = new ArrayList<String>();
ArrayList<String> al3 = new ArrayList<String>();
ArrayList<String> al1a = new ArrayList<String>();
String date;
String name;
String address;
String url;
String code;
int responseCode;
private String IDinvoice;
private TimerTask mTimerTask;
private Timer t=new Timer();
private final Handler handler=new Handler();
private ListView listview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hoadon);
int currentOrientation = getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
try {
URL url = new URL("http://longvansolution.tk/monthlytarget.php");
URLConnection connection = url.openConnection();
connection.setConnectTimeout(2000);
HttpURLConnection httpConnection = (HttpURLConnection) connection;
responseCode = httpConnection.getResponseCode();
} catch (Exception e) {
}
try {
if (isNetworkAvailable() == true
//&& responseCode == HttpURLConnection.HTTP_OK
) {
//new LoadData().execute();
al.clear();
al1.clear();
al2.clear();
al3.clear();
al1a.clear();
doTimerTask();
} else {
AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setMessage("No Internet Connection available!!!");
ad.show();
}
} catch (Exception e) {
}
Bundle extras = getIntent().getExtras();
if (extras != null) {
IDinvoice = extras.getString("IDinvoice");
}
}
public void doTimerTask(){
mTimerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
new LoadData().execute();
Log.d("TIMER", "TimerTask run");
}
});
}};
// public void schedule (TimerTask task, long delay, long period)
t.schedule(mTimerTask, 500, 10000); //
}
#Override
public void onBackPressed() {
//do something with bitmap
}
private class LoadData extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
// can use UI thread here
protected void onPreExecute() {
this.progressDialog = ProgressDialog.show(
Hoadon.this, "", " Loading...");
}
#Override
protected void onPostExecute(final Void unused) {
this.progressDialog.dismiss();
try {
listview = (ListView) findViewById(R.id.listView1);
this.progressDialog.dismiss();
listview.setAdapter(new DataAdapter(Hoadon.this,
al.toArray(new String[al.size()]), al1a
.toArray(new String[al1a.size()]), al1
.toArray(new String[al1.size()]), al2
.toArray(new String[al2.size()])));
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String t = al3.get(position);
Intent i = new Intent(Hoadon.this,
Signature.class);
i.putExtra("url", t);
startActivity(i);
}
});
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// HTTP post
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(
"http://longvansolution.tk/monthlytarget.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
// buffered reader
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 80);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
date = json_data.getString("date");
address = json_data.getString("address");
name = json_data.getString("name");
url = json_data.getString("url");
code = json_data.getString("code");
al.add(date);
al1a.add(code);
al1.add(name);
al2.add(address);
al3.add(url);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
} catch (ParseException e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
return null;
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null, otherwise check
// if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
// Log.i("net status:", "Online...!!!");
return true;
}
// Log.i("net status:", "offline...!!!");
return false;
}
}
Source DataAdapter
public class DataAdapter extends BaseAdapter {
Context mContext;
private LayoutInflater mInflater;
String[] date;
String[] code;
String[] address;
String[] name;
public DataAdapter(Context c, String[] date,String[] code, String[] name, String[] address) {
this.date = date;
this.code=code;
this.name = name;
this.address = address;
mContext = c;
mInflater = LayoutInflater.from(c);
}
public void clearData() {
// clear the data
Arrays.fill(date, null);
Arrays.fill(code, null);
Arrays.fill(address, null);
Arrays.fill(name, null);
}
public int getCount() {
return date.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.customgrid, parent, false);
holder = new ViewHolder();
holder.date = (TextView) convertView.findViewById(R.id.date);
holder.code=(TextView)convertView.findViewById(R.id.mahd);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.address = (TextView) convertView.findViewById(R.id.address);
if (position == 0) {
convertView.setTag(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
holder.date.setText(date[position]);
holder.code.setText(code[position]);
holder.name.setText(name[position]);
holder.address.setText(address[position]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return convertView;
}
static class ViewHolder {
TextView date,code;
TextView name, address;
}
}
you should clear your arralist every LoadData task.
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
al.clear();
al1.clear();
al2.clear();
al3.clear();
al1a.clear();
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
date = json_data.getString("date");
address = json_data.getString("address");
name = json_data.getString("name");
url = json_data.getString("url");
code = json_data.getString("code");
al.add(date);
al1a.add(code);
al1.add(name);
al2.add(address);
al3.add(url);
}

Categories

Resources