Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to implement search in my listview which is made by custom listadatper, I am parsing data from JSON and saving it into internal storage, here is my code
package life.quran.com.quranlife;
public class MainActivity extends ActionBarActivity {
List<Surah> surahList;
ListView lv;
EditText searchtxt;
ArrayList<String> surahNames;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar ab = getSupportActionBar();
ab.hide();
searchtxt = (EditText) findViewById(R.id.txtsearch);
surahList = new ArrayList<>();
lv = (ListView) findViewById(R.id.listView);
File f = getFilesDir();a
String filepath = f.getAbsolutePath();
File _file = new File(filepath + "/surah.json");
if (isOnline()) {
surahTask task = new surahTask();
task.execute("http://quran.life/surah.php");
} else {
String offline_data = readFromFile();
surahList = SurahJsonParser.parseData(offline_data);
displaySurah();
}
}
#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;
}
protected void displaySurah() {
final SurahAdapter adapter = new SurahAdapter(MainActivity.this,R.layout.item_template,surahList);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Surah surah = adapter.getItem(position);
String surahNo = surah.getSurah_no().toString();
String suranName = surah.getSurah_name().toString();
Intent intent = new Intent(MainActivity.this, SurahDetailsActivity.class);
intent.putExtra("_sno", surahNo);
intent.putExtra("_sname", suranName);
startActivity(intent);
}
});
searchtxt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
/* Surah surahItems = new Surah();
List<Surah> newlist = new ArrayList<Surah>();
ArrayList<String> temp = new ArrayList<String>();
int textlength = searchtxt.getText().length();
newlist.clear();
for(int i = 0; i < surahNames.size(); i++) {
if(textlength <= surahNames.get(i).length()) {
if(searchtxt.getText().toString().equalsIgnoreCase((String)surahNames.get(i).subSequence(0,textlength))) {
newlist.add(surahNames.get(i));
}
}
}
lv.setAdapter(new SurahAdapter(MainActivity.this,R.layout.item_template,surahList));
*/
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("surah.json", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
private String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("surah.json");
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;
}
#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);
}
private class surahTask extends AsyncTask<String, String, String> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
pd = new ProgressDialog(MainActivity.this);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setTitle("Please Wait...");
pd.setMessage("Preparing List Of Surah..");
pd.setIndeterminate(false);
pd.setCancelable(false);
pd.show();
}
#Override
protected String doInBackground(String... params) {
surahNames = new ArrayList<>();
String content = HttpManager.getData(params[0]);
for(Surah surah : surahList) {
surahNames.add("Surah " +surah.getSurah_name());
}
writeToFile(content);
return content ;
}
#Override
protected void onPostExecute(String s) {
surahList = SurahJsonParser.parseData(s);
displaySurah();
pd.dismiss();
}
}
}
Edited
To implement search, you need to use the textchanged event of the editText which will take the search word as an input. You can read the following links to learn about the action listeners:-
1)How to Apply the Textchange event on EditText
2)Counting Chars in EditText Changed Listener
After getting the search keyword go through the list and match the objects with the keywords. Then store the list item in a separate list which matches with the search keyword. After search is finished set the new adapter by using the newly created list.
Best of Luck!
Related
So I've got a project to make a simple job board app. I've retrieved my JSON data and have it displaying on my app but I want to be able to use a SearchView filter but I don't know how to access my SimpleAdapter from outside of an inner-class
Here is my code:
public class jobcategories extends Activity{
private TextView jobData;
private ProgressDialog myprocessingdialog;
ArrayAdapter<String> adapter;
ArrayList<HashMap<String, String>> jobList;
private ListView lv;
private SearchView sv;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jobcategories);
myprocessingdialog = new ProgressDialog(this);
jobList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
sv = (SearchView) findViewById(R.id.search);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
new JSONTask().execute("https://apidata.com");
}
public class JSONTask extends AsyncTask<String,String, String>{
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//Showing Progress dialogue
myprocessingdialog.setTitle("Please Wait..");
myprocessingdialog.setMessage("Loading");
myprocessingdialog.setCancelable(false);
myprocessingdialog.setIndeterminate(false);
myprocessingdialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try{
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentObject = new JSONArray(finalJson);
for (int i=0; i < parentObject.length(); i++) {
JSONObject job = parentObject.getJSONObject(i);
String JobTitle = job.getString("title");
String JobLocation = job.getString("location");
String finalTitle = JobTitle + " in " + JobLocation;
String JobCompany = "advert by "+job.getString("company");
String JobDescription = job.getString("description");
String JobApply = "How to Apply: " + job.getString("apply");
HashMap<String, String> jobs = new HashMap<>();
jobs.put("title", finalTitle);
jobs.put("company", JobCompany);
jobs.put("description", JobDescription);
jobs.put("apply", JobApply);
jobList.add(jobs);
}
}catch (MalformedURLException e){
Toast.makeText(getApplicationContext(), "Error...the job server is down..." + e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "error parsing..." + e.toString(), Toast.LENGTH_LONG).show();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String results) {
super.onPostExecute(results);
myprocessingdialog.cancel();
ListAdapter adapter = new SimpleAdapter(
jobcategories.this, jobList,
R.layout.list_item, new String[]{"title", "company", "description", "apply"},
new int[]{R.id.title, R.id.company, R.id.description, R.id.apply});
lv.setAdapter(adapter);
}
}
}
Any help would be appreciated, am pretty new to android so if there is a better way for me to filter the data then I am open to changing the code.
Create an interface called OnJsonResultListener like so:
public interface OnJsonResultListener {
void onResult(String result);
}
Then make your Activity/Fragment implement that interface and do whatever with your simple adapter and the result from there. Then make the AsyncTask take a OnJsonResultListener in the constructor. Then in the onPostExecute method, call listener.onResult(results);
This is a simple way of making a callback.
I have this application the app bring data from database and store it in a list view then every record have a history i want when i click on the record in the ListView to show me the history of that record. for now i made it when i click on a record then click find id button it will give me the id of the record then i will click History to clear this ListView and showing the history of this record on the same ListView.
Screen Shot for the app1 ,
Screen Shot for the app2
Any one Can help me, my app run but when i want to show the history it don't pass this (if) i don't know why
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer == 1){
ArrayAdapter<String > adapter= new ArrayAdapter<String>(c,android.R.layout.simple_list_item_1, patients );
lv.setAdapter(null);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Snackbar.make(view,patients.get(i), Snackbar.LENGTH_SHORT).show();
}
});
}else{
Toast.makeText(c,"Unable to parse data", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
the PHP side
<?php
$host='127.0.0.1';
$username='root';
$password='';
$database='app';
$con =mysqli_connect($host, $username, $password, $database) or die ('unable to connect');
if (mysqli_connect_error($con))
{
echo "Failed to connect to Database ".mysqli_connect_error();
}
$patientID = $_GET['patientID'];
$query= mysqli_query($con, "SELECT * FROM history where
patientID='$patientID' ");
if ($query)
{
while ($row = mysqli_fetch_array($query))
{
$flag[]= $row;
}
print(json_encode($flag));
}
mysqli_close($con);
?>
HistoryDownloader Java Class
public class HistoryDownloader extends AsyncTask<Void, Integer, String> {
Context c;
String address;
ListView lv;
ProgressDialog progressDialog;
public HistoryDownloader(Context c, String address, ListView lv) {
this.c = c;
this.address = address;
this.lv = lv;
}
//Before the job start
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog= new ProgressDialog(c);
progressDialog.setTitle("Fetch Data");
progressDialog.setMessage("Fetching data .... Please wait ");
progressDialog.show();
}
#Override
protected String doInBackground(Void... strings) {
String data= downloadData();
return data;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
if (s != null){
HistoryParser h= new HistoryParser(c,lv,s);
h.execute();
}else{
Toast.makeText(c, "Unable to download data ", Toast.LENGTH_SHORT).show();
}
}
private String downloadData(){
//connect and get a stream
InputStream is= null;
String line =null;
try{
URL url = new URL(address);
HttpURLConnection con= (HttpURLConnection) url.openConnection();
is =new BufferedInputStream( con.getInputStream());
BufferedReader br= new BufferedReader(new InputStreamReader(is));
StringBuffer sb= new StringBuffer() ;
if(br !=null){
while((line=br.readLine()) !=null){
sb.append(line+"\n");
}
}
else{
return null;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
HistoryParser java Class
public class HistoryParser extends AsyncTask<Void, Integer, Integer> {
String lls;
Context c;
ListView lv;
String data;
ArrayList<String > patients= new ArrayList<>();
ProgressDialog progressDialog;
public HistoryParser (Context c, ListView lv, String data) {
this.c = c;
this.lv = lv;
this.data = data;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog= new ProgressDialog(c);
progressDialog.setTitle("Parser");
progressDialog.setMessage("Parsing the data ... please wait");
progressDialog.show();
}
#Override
protected Integer doInBackground(Void... voids) {
return this.histoParse();
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer == 1){
ArrayAdapter<String > adapter= new ArrayAdapter<String>(c,android.R.layout.simple_list_item_1, patients );
lv.setAdapter(null);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Snackbar.make(view,patients.get(i), Snackbar.LENGTH_SHORT).show();
}
});
}else{
Toast.makeText(c,"Unable to parse data", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
// parse the reciv
private int histoParse (){
try {
//adding the data to json aray first
JSONArray js= new JSONArray(data);
//create json object to hold a singel item
JSONObject jo= null;
patients.clear();
// loop the array
for(int i=0 ;i<js.length();i++){
jo= js.getJSONObject(i);
//retriving the name
//TODO: write the strring depend on the column name in the database
// write the strring depend on the column name in the database
String case1=jo.getString("case1");
/* String case2=jo.getString("case2");
String case3=jo.getString("Case3");
String case4=jo.getString("Case4");
String case5=jo.getString("Case5");
String case6=jo.getString("Case6");
String case7=jo.getString("Case7");
String case8=jo.getString("Case8");
String case9=jo.getString("Case9");
String case10=jo.getString("Case10");
String trt1=jo.getString("trt1");
String trt2=jo.getString("trt2");
String trt3=jo.getString("trt3");
String trt4=jo.getString("trt4");
String trt5=jo.getString("trt5");
String trt6=jo.getString("trt6");
String trt7=jo.getString("trt7");
String trt8=jo.getString("trt8");
String trt9=jo.getString("trt9");
String trt10=jo.getString("trt10");
//add it to our array list
patients.add("Patient History");
patients.add("");
patients.add("Cases");
patients.add("");
*/ patients.add(case1);
/* patients.add(case2);
players.add(case3);
players.add(case4);
players.add(case5);
players.add(case6);
players.add(case7);
players.add(case8);
players.add(case9);
players.add(case10);
players.add("");
players.add("Treatments");
players.add("");
players.add(trt1);
players.add(trt2);
players.add(trt3);
players.add(trt4);
players.add(trt5);
players.add(trt6);
players.add(trt7);
players.add(trt8);
players.add(trt9);
players.add(trt10);
*/
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
Main Class Java
public class MainActivity extends AppCompatActivity {
Context context;
String url="http://10.0.2.2/Android/Fetch.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final TextView textView= (TextView) findViewById(R.id.textView);
final ListView lv=(ListView) findViewById(R.id.lv);
final Downloader d= new Downloader(this,url,lv);
String urlHistory="http://10.0.2.2/Android/History.php?patientID="+textView.getText().toString().trim();
final HistoryDownloader dd= new HistoryDownloader(this,urlHistory,lv);
final Button btn= (Button ) findViewById(R.id.button);
final Button btn2=(Button) findViewById(R.id.button2);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lv.setAdapter(null);
//String kk=textView.getText().toString().trim();
dd.execute();
if(textView.getText() != ""){
}else{
}
}
});
i did not use Transmitting Network Data Volley thats why im getting :)
I'm new to Java and Android and am trying to figure out how to write a ListView and load the ListView from where it is saved.
I have ListView and each item on the ListView has a string and bool that changes if a checkbox for the item is checked or unchecked. I have a working method to add items to the ListView and am now trying to figure out how to write the ListView to a textfile.
I got some code for saving the ListView by clicking a menu item and them I'm trying to load it when I re-run the program in my OnCreate, but nothing is loading. I'm not sure if its the write or load that is not working or both.
Here is a class I made that works with my ListView.
Item.java
public class Item {
String name;
boolean isChecked = false;
public Item(String name) {this.name = name;}
public Item(String name, boolean checked){
this.name = name;
this.isChecked = checked;
}
#Override
public String toString(){
return name;
}
}
Here is my MainActivity.java that includes my saveList() and readFile()
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getName();
ArrayList<Item> items = new ArrayList<>();
private ListView lv;
private static final String sFile = "Saved.txt";
protected ListView getListView() {
if (lv == null) {
lv = (ListView) findViewById(android.R.id.list);
}
return lv;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter) adapter).getWrappedAdapter();
} else {
return adapter;
}
}
private void deleteList()
{
if (!items.isEmpty())
{
items.clear();
}
lv.invalidateViews();
}
private void deleteCheckedItems()
{
SparseBooleanArray checked = lv.getCheckedItemPositions();
for(int i = 0; i < lv.getCount(); i++)
{
if (checked.get(i)==true)
{
items.remove(i);
}
lv.invalidateViews();
}
lv.clearChoices();
}
private void saveList(ArrayList<Item> itemlist) {
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(sFile, 0));
int iCnt = 0;
String allstring = "";
for (Item s : items)
{
if (s.isChecked)
{
iCnt++;
if (iCnt < items.size()) {
String thisstring;
thisstring = s.name + "\r\n";
out.write(thisstring);
allstring += thisstring;
} else {
String thisstring;
thisstring = s.name;
out.write(thisstring);
allstring += thisstring;
}
}
}
out.close();
//Toast.makeText(activity, allstring + " Written", duration).show();
}
catch (java.io.FileNotFoundException e)
{
}
catch (Exception ex)
{
// Toast.makeText(activity, "Write Exception : " + ex.getMessage(), duration).show();
}
}
public String readFile(ArrayList<Item> itemsList)
{
String sRet = "Nothing";
try
{
InputStream is = openFileInput(sFile);
if (is != null)
{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String sLine;
StringBuffer sb = new StringBuffer();
while ((sLine = br.readLine()) != null)
sb.append(sLine + "\r\n");
is.close();
sRet = sb.toString();
// Toast.makeText(Toast.LENGTH_LONG).show();
}
}
catch (java.io.FileNotFoundException e)
{
}
catch (Exception ex)
{
// Toast.makeText(activi"Read Exception" + ex.getMessage(), Toast.LENGTH_LONG).show();
}
return sRet;
}
private void addItemDialog()
{
LayoutInflater inflater = LayoutInflater.from(this);
final View addView = inflater.inflate(R.layout.add, null);
new AlertDialog.Builder(this)
.setTitle("Add Item")
.setView(addView)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EditText txtAdd = (EditText) addView.findViewById(R.id.etInput);
String sItem = (txtAdd).getText().toString();
items.add(new Item(sItem));
for (int i = 0; i < items.size(); i++)
{
lv.setItemChecked(i, items.get(i).isChecked);
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
}).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setListAdapter(new ArrayAdapter<Item>(this, android.R.layout.simple_list_item_multiple_choice, items));
lv = this.getListView();
for (int i = 0; i < items.size(); i++)
{
lv.setItemChecked(i, items.get(i).isChecked);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
readFile(items);
}
#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) {
switch(item.getItemId()){
case R.id.add_item:
addItemDialog();
return true;
case R.id.clear_all:
deleteList();
return true;
case R.id.clear_checked:
deleteCheckedItems();
return true;
case R.id.write:
saveList(items);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
put your oncreate method above after declaration that means after this line
private static final String sFile = "Saved.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.......
.......
//your code
}
//other method
Read Android activity lifecyle for better understanding
I want to show an alertdialog and get some input from user and after that, processing that inputs in an asynctask but the alertdialog become dismissed before get inputs and asynctask start to execute.
What should I do? Please help me. Here is my code;
private String[] newspapers,newspapersUrl,newspapersPath;
private String[] choosed,choosedUrl,choosedPath;
private boolean[] checked;
private int perNewspaper;
private boolean returned = false;
private AlertDialog.Builder builder;
private FetchingNewsByChoice fetchingNewsByChoice;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
returned = AlertDialogCreation();
if(returned)
{
fetchingNewsByChoice = new FetchingNewsByChoice((AppCompatActivity)MainActivity.this,choosed,choosedPath,perNewspaper);
fetchingNewsByChoice.execute();
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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);
}
//***** Alert Dialog *****//
public boolean AlertDialogCreation()
{
//***** File Control And Creating An Dialog Interface if this is first usage *****//
File file = getApplicationContext().getFileStreamPath("First.txt");
if(!file.exists())
{
writeToFile("First.txt", "0",true);
}
if(readFromFile("First.txt",false)[0].equals("0"))
{
newspapers = readFromFile("Choicable Newspaper.txt",true);
newspapersUrl = readFromFile("Choicable Url.txt",true);
newspapersPath = readFromFile("Choicable Path.txt",true);
checked = new boolean[newspapers.length];
builder = new AlertDialog.Builder(this,R.style.AppCompatAlertDialogStyle);
builder.setTitle("Lütfen Güncel Haberlerini Takip Etmek İstediğiniz Siteleri Seçiniz..");
builder.setItems(newspapers, null);
builder.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
int count = 0;
for (int a = 0; a < newspapers.length; a++) {
if (checked[a]) {
count++;
writeToFile("Choosed.txt", newspapers[a], false);
writeToFile("ChoosedUrl.txt", newspapersUrl[a], false);
writeToFile("ChoosedPath.txt", newspapersPath[a], false);
}
if (a == (newspapers.length - 1) && count == 0) {
Toast.makeText(getApplicationContext(), "En az bir gazete seçmek zorundasınız..", Toast.LENGTH_LONG).show();
builder.show();
}
}
}
});
builder.setMultiChoiceItems(newspapers, checked, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i, boolean isChecked) {
if (isChecked) {
checked[i] = true;
} else {
checked[i] = false;
}
}
});
try
{
builder.show();
}
catch (Exception ex)
{
ex.printStackTrace();
}
writeToFile("First.txt", "1", true);
choosed = readFromFile("Choosed.txt",false);
choosedUrl = readFromFile("ChoosedUrl.txt",false);
choosedPath = readFromFile("ChoosedPath.txt",false);
if(choosed != null)
{
perNewspaper = (int) Math.ceil(newspapers.length / choosed.length);
if(perNewspaper > 15)
{
perNewspaper = 14;
}
}
return true;
}
else if(readFromFile("First.txt",false)[0].equals("1"))
{
newspapers = readFromFile("Choicable Newspaper.txt",true);
newspapersUrl = readFromFile("Choicable Url.txt",true);
newspapersPath = readFromFile("Choicable Path.txt",true);
choosed = readFromFile("Choosed.txt",false);
choosedUrl = readFromFile("ChoosedUrl.txt",false);
choosedPath = readFromFile("ChoosedPath.txt",false);
perNewspaper = (int) Math.ceil(newspapers.length / choosed.length);
if(perNewspaper > 15)
{
perNewspaper = 14;
}
return true;
}
else
{
return false;
}
//***** File Control And Creating An Dialog Interface if this is first usage *****//
}
//*****Files*****//
private void writeToFile(String fileName,String data,boolean isPrivate)
{
try
{
OutputStreamWriter outputStreamWriter;
if(isPrivate)
{
outputStreamWriter = new OutputStreamWriter(getApplicationContext().openFileOutput(fileName, MODE_PRIVATE));
}
else
{
outputStreamWriter = new OutputStreamWriter(getApplicationContext().openFileOutput(fileName, MODE_APPEND));
}
outputStreamWriter.write(data+"\r\n");
outputStreamWriter.close();
}
catch (IOException e)
{
}
}
public String[] readFromFile(String fileName,boolean isAsset)
{
String[] ret=null;
try
{
InputStream inputStream;
if(isAsset)
{
inputStream = getApplicationContext().getAssets().open(fileName);
}
else
{
inputStream = getApplicationContext().openFileInput(fileName);
}
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).append(",");
}
inputStream.close();
ret = stringBuilder.toString().split(",");
inputStream.close();
}
}
catch (FileNotFoundException e)
{
}
catch (IOException e)
{
}
return ret;
}
I suppose you have a setpositivebutton click listener.
Start your asynktask in that listener with the desired input.
First Write your own function with parameters.
Call async task inside that function.
Now call that function by pass the form values as parameters to that function after you finish dimiss the dialog box.
I have problems with android programming in java, because it does not want to read from a text file. The problem is that the buttons do not add the text which I am trying to do in the async-class. Furthermore, the buttons which will show the text does not work, because when I press on a button the application stops working.
Short introduction of the program:
The application starts with a value sent to gameAction from a spinner, and from there it wil invoke a name on text-file which will be loaded into strings in an array-list, the class QuestionBox. Lastly it will questions will be made in GameAction class.
If something was unclear, please comment. And any help is appreciated! Excuse me for adding a lot of code, but I added it due to not knowing how to do.
public class QuestionBox extends AsyncTask<Object, Void, Object>{
private Context context;
private Callback callback;
private List<Question> mQuestions;
public QuestionBox(Context context,Callback callback)
{
mQuestions = new ArrayList<Question>();
this.callback=callback;
this.context= context;
}
public Callback getCallback(){
return callback;
}
#Override
protected Object doInBackground(Object... params) {
InputStream iS = null;
try {
iS = context.getAssets().open("hogskoleprovet.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println("Hit kom du");
BufferedReader reader = new BufferedReader(new InputStreamReader(iS));
String question, answer, answerOne, answerTwo, answerThree, answerFour;
try {
while (reader.readLine() != null) {
//reading some lines from resource file
question = reader.readLine();
answer = reader.readLine();
answerOne = reader.readLine();
answerTwo = reader.readLine();
answerThree = reader.readLine();
answerFour = reader.readLine();
Question q = new Question(question, answer, answerOne, answerTwo, answerThree, answerFour);
mQuestions.add(q);
break;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
reader.close();
System.out.println("Hit kom du3");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
public interface Callback{
public void notify_result(List<Question> question_list);
}
#Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
public int getQuestionsLeft() {
return mQuestions.size();
}
public Question getRandomQuestion() {
Random random = new Random();
int index = random.nextInt(mQuestions.size());
Question newQuestion = mQuestions.get(index);
mQuestions.remove(index);
return newQuestion;
}
}
Here is another method which the strings will be sent to:
public class gameAction extends ActionBarActivity implements QuestionBox.Callback{
private QuestionBox mQuestionBox;
private Question mCurrentQuestion;
private Context context;
private Callback callback;
#Override
public void notify_result(List<Question> question_list) {
}
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_action);
//Kod som kollar vad som skickades med när aktiviteten startades
Intent callingIntent = getIntent();
int index = callingIntent.getIntExtra("INDEX",0);
//Bestäm filnamn beroende på vad som skickades med
if(index==0){
mQuestionBox =new QuestionBox(getApplicationContext(), this);
mQuestionBox.execute("hogskoleprovet.txt");
}
else {
if (index == 1 ) {
mQuestionBox =new QuestionBox(getApplicationContext(), this);
mQuestionBox.execute("hogskoleprovet.txt");
} else if (index == 1) {
mQuestionBox =new QuestionBox(getApplicationContext(), this);
mQuestionBox.execute("hogskoleprovet.txt");
} else if (index == 2) {
mQuestionBox =new QuestionBox(getApplicationContext(), this);
mQuestionBox.execute("hogskoleprovet.txt");
}
}
}
public void setNewQuestion()
{
//Hämta en slumpmässig fråga från vår QuestionBox
//och lagra den i mCurrentQuestion
mCurrentQuestion = mQuestionBox.getRandomQuestion();
//Se till så att textfält och knappar visar den aktuella
//frågan
TextView questionTextView = (TextView) findViewById(R.id.questionTextView);
questionTextView.setText(mCurrentQuestion.getQuestion());
Button buttonOne = (Button) findViewById(R.id.buttonOne);
buttonOne.setText(mCurrentQuestion.getOptionOne());
Button buttonTwo = (Button) findViewById(R.id.buttonTwo);
buttonTwo.setText(mCurrentQuestion.getOptionTwo());
Button buttonThree = (Button) findViewById(R.id.buttonThree);
buttonThree.setText(mCurrentQuestion.getOptionThree());
Button buttonFour = (Button) findViewById(R.id.buttonFour);
buttonFour.setText(mCurrentQuestion.getOptionFour());
Button buttonNew = (Button) findViewById(R.id.buttonNew);
buttonOne.setEnabled(true);
buttonTwo.setEnabled(true);
buttonThree.setEnabled(true);
buttonFour.setEnabled(true);
buttonNew.setVisibility(View.INVISIBLE);
buttonOne.setText(mCurrentQuestion.getOptionOne());
buttonTwo.setText(mCurrentQuestion.getOptionTwo());
buttonThree.setText(mCurrentQuestion.getOptionThree());
buttonFour.setText(mCurrentQuestion.getOptionFour());
}
public void quitTheGame(View v){
Intent intent = new Intent (this, MainActivity.class);
Button butttonQuit = (Button) findViewById(R.id.buttonFive);
startActivity(intent);
}
public void answerClick(View V)
{
Button answerButton = (Button)V;
Button buttonOne = (Button) findViewById(R.id.buttonOne);
buttonOne.setText(mCurrentQuestion.getOptionOne());
Button buttonTwo = (Button) findViewById(R.id.buttonTwo);
buttonTwo.setText(mCurrentQuestion.getOptionTwo());
Button buttonThree = (Button) findViewById(R.id.buttonThree);
buttonThree.setText(mCurrentQuestion.getOptionThree());
Button buttonFour = (Button) findViewById(R.id.buttonFour);
buttonFour.setText(mCurrentQuestion.getOptionFour());
Button buttonNew = (Button) findViewById(R.id.buttonNew);
buttonOne.setEnabled(false);
buttonTwo.setEnabled(false);
buttonThree.setEnabled(false);
buttonFour.setEnabled(false);
buttonNew.setVisibility(View.VISIBLE);
}
public void newClick(View v){
if(mQuestionBox.getQuestionsLeft()>0){
setNewQuestion();
}
else
{
Context context = getApplicationContext();
String text = "Slut på frågor!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
#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);
}
}
Here is the class for putting answer to correct options:
package com.example.arnpet.ultimatehogskoleprovet;
public class Question {
private String question;//Lagrar frågan
private String optionOne; //Lagrar svarsalternativ
private String optionTwo;
private String optionThree;
private String optionFour;
private String correctAnswer; //Lagrar det korrekta svaret
//konstruktor
public Question (String question, String optionOne, String optionTwo,
String optionThree, String optionFour, String correctAnswer)
{
this.question = question;
this.optionOne = optionOne;
this.optionTwo = optionTwo;
this.optionThree = optionThree;
this.optionFour = optionFour;
}
public String getQuestion() {
return question;
}
public String getOptionOne() {
return optionOne;
}
public String getOptionTwo() {
return optionTwo;
}
public String getOptionThree() {
return optionThree;
}
public String getOptionFour() {
return optionFour;
}
}
while (reader.readLine() != null)
Here you are reading a line of the file and throwing it away. Not what you want, unless your file is strangely structured with ignorable junk lines every so often.
The usual loop looks like this:
while ((line = reader.readLine()) != null)
and then using line in the controlled block.
Secondly, this is the only place you check for null, yet you have several other readLine() calls, any one of which can return null. So you run some risk of NPEs later in your code.