Change the content of text file in onclick() method of dialogue box - java

Problem is the string which writes to outputstreamswriter has correct value but in try/catch block within onclick() method of dialogue box outputstreamwriter is not working. My file name is default.txt i'm sure file name has nothing to do with the problem. outputstreamwriter does not change the content of file whatsoever i've tried bufferwriter or fileoutputstream but nothing seems to work. Kindly help i'm losing my mind from days now!
here's the code.
package zafus.personalitymeter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout.LayoutParams;
public class ChoseAnswers extends Activity {
private final String TAG="";
public String vale;
public List<String> obj;
public int numOfAnswers=0;
//public RelativeLayout mylayout =(RelativeLayout)findViewById(R.id.calayout);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chose_answers);
obj=null;
obj=readFromFile("answer.txt", this);
numOfAnswers=Integer.valueOf(obj.get(0).toString());
int i=1;
LinearLayout mylayout =(LinearLayout)findViewById(R.id.linearLayout1);
while(i<=numOfAnswers){
Button tt = new Button(this);
tt.setText(obj.get(i));
tt.setId(i+1);
tt.setPadding(5, 10, 5, 10);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
tt.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
vale=((Button)v).getText().toString();
AlertDialog.Builder dlgAlert1 = new AlertDialog.Builder(ChoseAnswers.this);
dlgAlert1.setMessage("Show this answer as a result of next test?");
dlgAlert1.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
obj=null;
obj=readFromFile("default.txt", ChoseAnswers.this);
obj.set(1,vale);
String receiveString = "";
int num=Integer.valueOf(obj.get(0))+2;
StringBuilder ab = new StringBuilder();
int i=0;
for(;i<num;i++){
ab.append(obj.get(i)+"\n");
}
receiveString=ab.toString();
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("default.txt", Context.MODE_PRIVATE));
//outputStreamWriter.write("");
outputStreamWriter.write(receiveString);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e(TAG, "File write failed: " + e.toString());
}
ChoseAnswers.this.finish();
}});
dlgAlert1.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}});
dlgAlert1.show();
}
});
if (i == 1){
params.setMargins(0, 150, 0, 20);
}
else{
params.setMargins(0, 20, 0, 20);
}
tt.setLayoutParams(params);
tt.setBackgroundResource(R.drawable.bxml);
tt.setTextColor(Color.parseColor("#330011"));
mylayout.addView(tt);
i++;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.choseanswers, menu);
return true;
}
public static List<String> readFromFile(String fileName, Context context) {
List<String> words = new ArrayList<String>();
InputStream fIn = null;
InputStreamReader isr = null;
BufferedReader input = null;
try {
fIn = context.getResources().getAssets().open(fileName, context.MODE_WORLD_READABLE);
isr = new InputStreamReader(fIn);
input = new BufferedReader(isr);
String line = "";
while ((line = input.readLine()) != null) {
words.add(line);
}
} catch (Exception e) {
e.getMessage();
} finally {
try {
if (isr != null)
isr.close();
if (fIn != null)
fIn.close();
if (input != null)
input.close();
} catch (Exception e2) {
e2.getMessage();
}
}
return words;
}
}

In your onClick you read a file from assets and save it to internal memory.
On the next click the same happens.
You should read the file from internal memory too if you want to check if the write succeeded.

Related

Send an image and other string parameters to server using HttpURLConnection and Base64

I am trying to send an image and some string values from android to a php script using HttpURLConnection. I have successfully done so with strings, but can't seem to get it right with the image. I am using Base64 (android.util.Base64) to convert my image to a string to send it. Now, I have a separate HttpParse.java file I use to send all my info to the server, and I think that is where the change needs to be made to allow the image, but I'm not sure, (I am newer to java/android development). I've researched several similar questions, but they aren't fully clicking for me for what I'm doing wrong. Also, I have tested that I am successfully converting the image to a string. Here is my code:
EDIT I got a little farther... After testing, I am getting the issue because the three variables I try to get with getArguments() are coming back as null... But, I can't figure out how to get them to come through successfully... I added the code for how I start my fragment and how I try to get my bundle
My fragment start:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_units);
Intent intent = getIntent();
LexaUser = intent.getStringExtra("UserName");
ReadOnly = intent.getStringExtra("ReadOnly");
Password = intent.getStringExtra("Password");
QA = intent.getStringExtra("QA");
SearchValue = intent.getStringExtra("SearchInput");
bottomNavigation = (BottomNavigationView)findViewById(R.id.bottom_navigation);
bottomNavigation.inflateMenu(R.menu.bottom_menu);
fragmentManager = getSupportFragmentManager();
bottomNavigation.getMenu().getItem(0).setChecked(true);
UnitDetailsHeader = findViewById(R.id.UnitDetailsViewTitle);
UnitDetailsHeader.setText(SearchValue);
UnitSizeText = findViewById(R.id.UnitSize);
UnitStatusText = findViewById(R.id.UnitStatus);
if (SearchValue.contains("-")) {
getUnitDetails(SearchValue, LexaUser);
} else {
getSiblings();
}
bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.action_search:
fragment = new NewUnitStatusFragment();
break;
case R.id.action_cart:
fragment = new PendingUnitStatusFragment();
break;
case R.id.action_hot_deals:
fragment = new FinalUnitStatusFragment();
break;
case R.id.action_siblings:
fragment = new SiblingUnitFragment();
break;
}
Bundle connBundle = new Bundle();
connBundle.putString("SearchValue", SearchValue);
connBundle.putString("LexaUser", LexaUser);
connBundle.putString("Password", Password);
connBundle.putString("QA", QA);
fragment.setArguments(connBundle);
final FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_container, fragment).commit();
return true;
}
});
}
And where I try to get my arguments: (I originally had in onCreateView but then tried to move it to onCreate. But the behavior was the same)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
SearchValue = getArguments().getString("SearchValue");
LexaUser = getArguments().getString("LexaUser");
Password = getArguments().getString("Password");
}
}
My fragment where I get the image and send my data:
package [my_package];
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import android.util.Base64;
import java.util.HashMap;
import static android.app.Activity.RESULT_OK;
public class NewUnitStatusFragment extends Fragment {
Context newUnitStatusContext;
Activity newUnitStatusActivity;
Intent cameraIntent;
ProgressDialog progressDialog;
String ReadOnly;
String LexaUser;
String Password;
String SearchValue;
String finalResultNewUnitStatus;
String HttpURLNewUnitStatus = "https://[path/to/file]/insertNewUnitStatus.php";
HashMap<String, String> hashMapNewUnitStatus = new HashMap<>();
HttpParse httpParse = new HttpParse();
Spinner statusSpinner;
Spinner generalCauseSpinner;
EditText newUSComment;
Button addPhotoBtn;
ImageView newUnitStatusImage;
Button addNewUnitStatus;
String newUnitStatus;
String generalCause;
String newUnitStatusComment;
String newUnitStatusPhoto;
String message;
private static final int PICK_FROM_GALLERY = 1;
public NewUnitStatusFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_newunitstatus, container, false);
newUnitStatusContext = getContext();
newUnitStatusActivity = getActivity();
statusSpinner = view.findViewById(R.id.Status);
generalCauseSpinner = view.findViewById(R.id.GeneralCause);
newUSComment = view.findViewById(R.id.NewComment);
newUnitStatusImage = view.findViewById(R.id.AddPhoto);
addPhotoBtn = view.findViewById(R.id.AddPhotosLabel);
addNewUnitStatus = view.findViewById(R.id.addBtnNewUnitStatus);
ArrayAdapter<CharSequence> statusSpinnerAdapter = ArrayAdapter.createFromResource(newUnitStatusContext,
R.array.new_unit_status_array, android.R.layout.simple_spinner_item);
statusSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
statusSpinner.setAdapter(statusSpinnerAdapter);
newUnitStatus = statusSpinner.getSelectedItem().toString();
ArrayAdapter<CharSequence> generalCauseSpinnerAdapter = ArrayAdapter.createFromResource(newUnitStatusContext,
R.array.status_general_cause_array, android.R.layout.simple_spinner_item);
generalCauseSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
generalCauseSpinner.setAdapter(generalCauseSpinnerAdapter);
generalCause = generalCauseSpinner.getSelectedItem().toString();
addPhotoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startGallery();
}
});
// Set a click listener for the text view
addNewUnitStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
newUnitStatus = statusSpinner.toString();
generalCause = generalCauseSpinner.toString();
newUnitStatusComment = newUSComment.toString();
if (getArguments() != null) {
SearchValue = getArguments().getString("SearchValue");
LexaUser = getArguments().getString("LexaUser");
Password = getArguments().getString("Password");
}
addNewUnitStatus(SearchValue, newUnitStatus, generalCause, newUnitStatusComment, newUnitStatusPhoto, LexaUser, Password);
}
});
return view;
}
private void startGallery() {
cameraIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
cameraIntent.setType("image/*");
cameraIntent.setAction(Intent.ACTION_GET_CONTENT);
if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(cameraIntent, 1000);
} else {
Toast.makeText(newUnitStatusContext, "Error: " + cameraIntent + " - cameraIntent.resolveActivity(getActivity().getPackageManager()) = null", Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//super method removed
if (resultCode == RESULT_OK) {
if (requestCode == 1000) {
Uri returnUri = data.getData();
try {
Bitmap bitmapImage = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), returnUri);
newUnitStatusImage.setImageBitmap(bitmapImage);
newUnitStatusImage.buildDrawingCache();
Bitmap bm = newUnitStatusImage.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
newUnitStatusPhoto = Base64.encodeToString(b, Base64.DEFAULT);
} catch (IOException ioEx) {
ioEx.printStackTrace();
Toast.makeText(newUnitStatusContext, "ioEx Error: " + ioEx, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(newUnitStatusContext, "Error: " + requestCode, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(newUnitStatusContext, "Error: " + resultCode, Toast.LENGTH_LONG).show();
}
}
public void addNewUnitStatus(String searchInput, String newUnitStatus, String generalCause, String newUnitStatusComment, String newUnitStatusPhoto, String lexaUser, String password) {
class NewUnitStatusClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(newUnitStatusContext, "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
if (httpResponseMsg != null) {
try {
JSONObject object = new JSONObject(httpResponseMsg);
message = object.getString("message");
Toast.makeText(newUnitStatusContext, httpResponseMsg, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
Toast.makeText(newUnitStatusContext, "Error: " + e.toString(), Toast.LENGTH_LONG).show();
} // catch (JSONException e)
progressDialog.dismiss();
} else {
progressDialog.dismiss();
Toast.makeText(newUnitStatusContext, "HttpResponseMsg is null.", Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
hashMapNewUnitStatus.put("searchinput", params[0]);
hashMapNewUnitStatus.put("newUnitStatus", params[1]);
hashMapNewUnitStatus.put("generalCause", params[2]);
hashMapNewUnitStatus.put("newUnitStatusComment", params[3]);
hashMapNewUnitStatus.put("newUnitStatusPhoto", params[4]);
hashMapNewUnitStatus.put("lexauser", params[5]);
hashMapNewUnitStatus.put("password", params[6]);
finalResultNewUnitStatus = httpParse.postRequest(hashMapNewUnitStatus, HttpURLNewUnitStatus);
return finalResultNewUnitStatus;
}
}
NewUnitStatusClass newUnitStatusClass = new NewUnitStatusClass();
newUnitStatusClass.execute(searchInput, newUnitStatus, generalCause, newUnitStatusComment, newUnitStatusPhoto, lexaUser, password);
}
}
And my code to do that actuall HttpURLConnection: HttpParse.java
package [my_package];
import android.app.ListActivity;
import android.widget.ArrayAdapter;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class HttpParse extends ListActivity {
String FinalHttpData = "";
String Result;
BufferedWriter bufferedWriter;
OutputStream outputStream;
BufferedReader bufferedReader;
StringBuilder stringBuilder = new StringBuilder();
URL url;
public String postRequest(HashMap<String, String> Data, String HttpUrlHolder) {
try {
url = new URL(HttpUrlHolder);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(14000);
httpURLConnection.setConnectTimeout(14000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
outputStream = httpURLConnection.getOutputStream();
bufferedWriter = new BufferedWriter(
new OutputStreamWriter(outputStream, "UTF-8"));
bufferedWriter.write(FinalDataParse(Data));
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
bufferedReader = new BufferedReader(
new InputStreamReader(
httpURLConnection.getInputStream()
)
);
FinalHttpData = bufferedReader.readLine();
}
else {
FinalHttpData = "Something Went Wrong";
}
} catch (Exception e) {
e.printStackTrace();
}
return FinalHttpData;
}
public String FinalDataParse(HashMap<String,String> hashMap2) throws UnsupportedEncodingException {
for(Map.Entry<String,String> map_entry : hashMap2.entrySet()){
stringBuilder.append("&");
stringBuilder.append(URLEncoder.encode(map_entry.getKey(), "UTF-8"));
stringBuilder.append("=");
stringBuilder.append(URLEncoder.encode(map_entry.getValue(), "UTF-8"));
}
Result = stringBuilder.toString();
return Result ;
}
}
All help is appreciated! Thank you!
P.S. my app shows the following error:
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
This then leads to this:
E/JSONException: Error: org.json.JSONException: End of input at character 0 of

what code would I need to add to be able to use this App on phone? [duplicate]

This question already has an answer here:
NetworkOnMainThreadException with AsyncTask
(1 answer)
Closed 6 years ago.
Would some one tell where and what code I would need to add to my Java file to make my app work using NetworkOnMainThreadException because I am really struggling. App crashed when it starts saying the app has stopped working.
package com.airrocketapps.matthillman.guessthecelebrity;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends Activity {
ArrayList<String> celebURLs = new ArrayList<String>();
ArrayList<String> celebNames = new ArrayList<String>();
int chosenCeleb = 0;
int locationOfCorrectAnswer = 0;
String[] answers = new String[4];
ImageView imageView;
Button button0;
Button button1;
Button button2;
Button button3;
public void celebChosen(View view) {
if (view.getTag().toString().equals(Integer.toString(locationOfCorrectAnswer))) {
Toast.makeText(getApplicationContext(), "Correct!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Wrong! It was " + celebNames.get(chosenCeleb), Toast.LENGTH_LONG).show();
}
createNewQuestion();
}
public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(inputStream);
return myBitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
button0 = (Button) findViewById(R.id.button);
button1 = (Button) findViewById(R.id.button2);
button2 = (Button) findViewById(R.id.button3);
button3 = (Button) findViewById(R.id.button4);
DownloadTask task = new DownloadTask();
String result = null;
try {
result = task.execute("http://www.posh24.com/celebrities").get();
String[] splitResult = result.split("<div class=\"sidebarContainer\">");
Pattern p = Pattern.compile("<img src=\"(.*?)\"");
Matcher m = p.matcher(splitResult[0]);
while (m.find()) {
celebURLs.add(m.group(1));
}
p = Pattern.compile("alt=\"(.*?)\"");
m = p.matcher(splitResult[0]);
while (m.find()) {
celebNames.add(m.group(1));
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
createNewQuestion();
}
public void createNewQuestion() {
Random random = new Random();
chosenCeleb = random.nextInt(celebURLs.size());
ImageDownloader imageTask = new ImageDownloader();
Bitmap celebImage;
try {
celebImage = imageTask.execute(celebURLs.get(chosenCeleb)).get();
imageView.setImageBitmap(celebImage);
locationOfCorrectAnswer = random.nextInt(4);
int incorrectAnswerLocation;
for (int i=0; i<4; i++) {
if (i == locationOfCorrectAnswer) {
answers[i] = celebNames.get(chosenCeleb);
} else {
incorrectAnswerLocation = random.nextInt(celebURLs.size());
while (incorrectAnswerLocation == chosenCeleb) {
incorrectAnswerLocation = random.nextInt(celebURLs.size());
}
answers[i] = celebNames.get(incorrectAnswerLocation);
}
}
button0.setText(answers[0]);
button1.setText(answers[1]);
button2.setText(answers[2]);
button3.setText(answers[3]);
} catch (Exception e) {
e.printStackTrace();
}
}
#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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Everything looks fine in your code.
Make sure you have active internet connection in your mobile where you are trying to run this application.
If you are using Internet, then don't forget to add this to your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
More help: https://stackoverflow.com/a/6343299/7004388

Rss Feeds reader gives blank screen for .xml link

I am following this tutorial (http://techiedreams.com/android-rss-reader-part-two-offline-reading-swipe-through-detail-views/)and try to implement rss feed reader
It working properly when I use
String RSSFEEDURL = "http://feeds.feedburner.com/androidcentral?format=xml";
instead of using
String RSSFEEDURL = "http://www.livescience.com/home/feed/health.xml";
This is my splash activity
package com.healthyhub.nadeesha.rsssave;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import com.healthyhub.nadeesha.rsssave.parser.DOMParser;
import com.healthyhub.nadeesha.rsssave.parser.RSSFeed;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SplashActivity extends Activity {
String RSSFEEDURL = "http://www.livescience.com/home/feed/health.xml";
// String RSSFEEDURL = "http://feeds.feedburner.com/androidcentral?format=xml";
RSSFeed feed;
String fileName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
fileName = "TDRSSFeed.td";
File feedFile = getBaseContext().getFileStreamPath(fileName);
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null) {
// No connectivity. Check if feed File exists
if (!feedFile.exists()) {
// No connectivity & Feed file doesn't exist: Show alert to exit
// & check for connectivity
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// No connectivty and file exists: Read feed from the File
Toast toast = Toast.makeText(this,
"No connectivity! Reading last update...",
Toast.LENGTH_LONG);
toast.show();
feed = ReadFeed(fileName);
startLisActivity(feed);
}
} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}
}
private void startLisActivity(RSSFeed feed) {
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
// launch List activity
Intent intent = new Intent(SplashActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
// kill this activity
finish();
}
private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Obtain feed
DOMParser myParser = new DOMParser();
feed = myParser.parseXml(RSSFEEDURL);
if (feed != null && feed.getItemCount() > 0)
WriteFeed(feed);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
startLisActivity(feed);
}
}
// Method to write the feed to the File
private void WriteFeed(RSSFeed data) {
FileOutputStream fOut = null;
ObjectOutputStream osw = null;
try {
fOut = openFileOutput(fileName, MODE_PRIVATE);
osw = new ObjectOutputStream(fOut);
osw.writeObject(data);
osw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Method to read the feed from the File
private RSSFeed ReadFeed(String fName) {
FileInputStream fIn = null;
ObjectInputStream isr = null;
RSSFeed _feed = null;
File feedFile = getBaseContext().getFileStreamPath(fileName);
if (!feedFile.exists())
return null;
try {
fIn = openFileInput(fName);
isr = new ObjectInputStream(fIn);
_feed = (RSSFeed) isr.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return _feed;
}
}
Here is my DOMParser.java
package com.healthyhub.nadeesha.rsssave.parser;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class DOMParser {
private RSSFeed _feed = new RSSFeed();
public RSSFeed parseXml(String xml) {
// _feed.clearList();
URL url = null;
try {
url = new URL(xml);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
// Create required instances
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Parse the xml
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
// Get all <item> tags.
NodeList nl = doc.getElementsByTagName("item");
int length = nl.getLength();
for (int i = 0; i < length; i++) {
Node currentNode = nl.item(i);
RSSItem _item = new RSSItem();
NodeList nchild = currentNode.getChildNodes();
int clength = nchild.getLength();
// Get the required elements from each Item
for (int j = 0; j < clength; j = j + 1) {
Node thisNode = nchild.item(j);
String theString = null;
String nodeName = thisNode.getNodeName();
/*newly added*/
/*here it returns NullPointer exception for theString*/
System.out.println( nchild.item(j).getFirstChild().getNodeValue());
/*end*/
theString = nchild.item(j).getFirstChild().getNodeValue();
if (theString != null) {
if ("title".equals(nodeName)) {
// Node name is equals to 'title' so set the Node
// value to the Title in the RSSItem.
_item.setTitle(theString);
} else if ("description".equals(nodeName)) {
_item.setDescription(theString);
// Parse the html description to get the image url
String html = theString;
org.jsoup.nodes.Document docHtml = Jsoup
.parse(html);
Elements imgEle = docHtml.select("img");
_item.setImage(imgEle.attr("src"));
} else if ("pubDate".equals(nodeName)) {
// We replace the plus and zero's in the date with
// empty string
String formatedDate = theString.replace(" +0000",
"");
_item.setDate(formatedDate);
}
}
}
// add item to the list
_feed.addItem(_item);
}
} catch (Exception e) {
e.printStackTrace();
}
// Return the final feed once all the Items are added to the RSSFeed
// Object(_feed).
return _feed;
}
}
Below part of the above code gives null pointer exception
for (int j = 0; j < clength; j = j + 1) {
Node thisNode = nchild.item(j);
String theString = null;
String nodeName = thisNode.getNodeName();
/*newly added*/
/*here it returns NullPointer exception for theString*/
System.out.println( nchild.item(j).getFirstChild().getNodeValue());
/*end*/
This is my DetailFragment.java
package com.healthyhub.nadeesha.rsssave;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.widget.ScrollView;
import android.widget.TextView;
import com.healthyhub.nadeesha.rsssave.parser.RSSFeed;
public class DetailFragment extends Fragment {
private int fPos;
RSSFeed fFeed;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fFeed = (RSSFeed) getArguments().getSerializable("feed");
fPos = getArguments().getInt("pos");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.detail_fragment, container, false);
// Initializr views
TextView title = (TextView) view.findViewById(R.id.title);
WebView desc = (WebView) view.findViewById(R.id.desc);
// Enable the vertical fading edge (by default it is disabled)
ScrollView sv = (ScrollView) view.findViewById(R.id.sv);
sv.setVerticalFadingEdgeEnabled(true);
// Set webview properties
WebSettings ws = desc.getSettings();
ws.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
ws.setLightTouchEnabled(false);
ws.setPluginState(PluginState.ON);
ws.setJavaScriptEnabled(true);
// Set the views
title.setText(fFeed.getItem(fPos).getTitle());
desc.loadDataWithBaseURL("http://www.livescience.com/health/", fFeed
.getItem(fPos).getDescription(), "text/html", "UTF-8", null);
return view;
}
}
Simply what the above code does is
DOM Parser to Parse the XML data.
method returns the feed(RSSFeed) object:
Splash Activity we now call the method parseXml(String xml) from the DOMParser class
feed has been obtained in the onPostExecute() method we need to start the ListActivity and pass it the feed we
got, we do that by bundling the feed object and attaching it to the Intent

Writing multiple strings to file in android

I am looking to write multiple strings to file for storage using android. Is it possible to add all strings to a toString using .getText and if so how. I am looking to create some edit text fields and take the information contained in these fields and write them to a file before then reading the file in a different activity. Any help would be greatly appreciated.
Here is my code so far if it is any help:
package app.project.newapp;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
public class AddActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
}
public void saveClick(String filename, EditText v){
EditText name = (EditText) findViewById(R.id.namet);
EditText tel = (EditText) findViewById(R.id.emerg_tel);
EditText cond = (EditText) findViewById(R.id.conditions);
EditText other = (EditText) findViewById(R.id.other);
String userDetails = "Hello_File";
String string = "";
FileOutputStream fos = null;
try {
fos = openFileOutput(userDetails, Context.MODE_PRIVATE);
} catch (FileNotFoundException e){
e.printStackTrace();
}
try {
string=name.getText().toString();
string=tel.getText().toString();
string=cond.getText().toString();
string=other.getText().toString();
fos.write(string.getBytes());
} catch (IOException e){
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e){
e.printStackTrace();
}
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(
openFileInput("hello_file")));
String inputString;
StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null) {
stringBuffer.append(inputString + "\n");
}
} catch(IOException e) {
e.printStackTrace();
}//end catch
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Try this in your saveClick method, in the second try:
try {
string=name.getText().toString() + "\n"
+ tel.getText().toString() + "\n"
+ cond.getText().toString() + "\n"
+ other.getText().toString();
fos.write(string.getBytes());
} catch(IOException e) {
e.printStackTrace();
}

onCreateOptionMenu android Issue

It's the usual activity. The problem is in onCreateOptionMenu. When I click the menu button nothing is done. I don't see where the problem is.
I also try to comment all code without menu but It's still don't work.
It is either a very strange problem or I don't see some simple things..
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.LinearLayout;
public class Izu4aikaActivity extends Activity implements OnClickListener {
public final int INFO = 101;
public final int BLOCK = 102;
public final int CLOSE = 103;
final String sdDir = Environment.getExternalStorageDirectory()+"/izuchaika/";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
// Thread to write files to SD
final String file = "Files";
File dir = new File(sdDir);
dir.mkdir();
dir.mkdirs();
new Thread(new Runnable() {
public void run() {
copyFileOrDir(file);
}
}).start();
LinearLayout ll = (LinearLayout) findViewById(R.id.main_layout);
ll.setOnClickListener(this);
}
//Menu
public boolean onCreateOptionMenu(Menu menu) {
menu.add(Menu.NONE, INFO, Menu.NONE, "О программе").setIcon(
R.drawable.info);
menu.add(Menu.NONE, BLOCK, Menu.NONE, "Блокировать").setIcon(
R.drawable.block);
menu.add(Menu.NONE, CLOSE, Menu.NONE, "Выход").setIcon(R.drawable.exit);
return super.onCreateOptionsMenu(menu);
}
#Override
public void onClick(View v) {
Intent i = new Intent(this, mScr.class);
startActivity(i);
}
private void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = sdDir + path;
File dir = new File(fullPath);
if (!dir.exists())
dir.mkdir();
for (int i = 0; i < assets.length; ++i) {
copyFileOrDir(path + "/" + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
String newFileName = sdDir + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
}
Help if you see a solution.
You've misspelled method name - it should be onCreateOptionsMenu(), not onCreateOptionMenu().
It's preferable to use #Override annotation to avoid such mistakes:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
This way it will give you compile time error if you misspell method name or use wrong parameters.
Change your onCreateOptionsMenu to:
//Menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, INFO, Menu.NONE, "О программе").setIcon(
R.drawable.info);
menu.add(Menu.NONE, BLOCK, Menu.NONE, "Блокировать").setIcon(
R.drawable.block);
menu.add(Menu.NONE, CLOSE, Menu.NONE, "Выход").setIcon(R.drawable.exit);
return true;
}
It should work now!
try to add
#Override to public boolean onCreateOptionMenu
And do you try to use MenuInflater and inflate menu from xml?

Categories