我从json到服务器获取我的内容。我的layout.i中有两个TextView和一个ImageView,它已将json中的内容写入文件。但我无法在离线时设置我的数据 我也从文件中获取数据。
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);
}*/
适配器类
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());
}
}
答案 0 :(得分:0)
当设备脱机时,您可以从包含此json值的文件或数据库导入/读取。获取互联网更新数据库或文件后。
对于文件,您必须在
中制作或移动文件Environment.getExternalStorageDirectory();
要写入文件,请按照代码
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());
}
}
从外部存储中读取以下代码
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;
}