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.
Related
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 am attempting to establish a connection with android and my server. My server sends HTML5 responses.
My main activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//atempting connection to sever
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
SimpleHTTPRequest connect=new SimpleHTTPRequest();
connect.attemptConnect();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
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);
}
}
My network class
public class SimpleHTTPRequest {
HttpURLConnection connection = null;
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;
public void attemptConnect() {
try {
URL serverAddress = new URL("myUrl");
//set up out communications stuff
connection = null;
//Set up the initial connection
connection = (HttpURLConnection) serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.connect();
//get the output stream writer and write the output to the server
//not needed in this example
//wr = new OutputStreamWriter(connection.getOutputStream());
//wr.write("");
//wr.flush();
//read the result from the server
rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line + '\n');
System.out.println(sb.toString());
//This will return the String Server Sent event from the server
//Need to parse the data as JSON Now
//attempt to parse string from sb=StringBuilder into a JSon object
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//close the connection, set all objects to null
connection.disconnect();
rd = null;
sb = null;
connection = null;
}
}
}
I did this in eclipse and it worked, so what am I doing wroung?
I am trying to write a notes management app, when I am adding few new notes, delete them and then try to add new note the app is crashing on setcontentview().
I added the log, it can be triggered easily by deleting the first editText and then adding a new one.
public class Mainpage extends AppCompatActivity {
private LinearLayout MyLayout;
private ScrollView sv;
private List<EditText> et = new ArrayList<EditText>();
private List<EditText> ct = new ArrayList<EditText>();
private List<TextView> tv = new ArrayList<TextView>();
private List<CheckBox> cb = new ArrayList<CheckBox>();
private Button btn;
final Context context = this;
private CountDownTimer timer;
boolean isWaiting;
int last_added;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainpage);
last_added = 0;
//btn = (Button) findViewById(R.id.btn);
//btn.setVisibility(View.INVISIBLE);
}
#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_mainpage, menu);
sv = new ScrollView(this);
MyLayout = new LinearLayout(this);
MyLayout.setOrientation(LinearLayout.VERTICAL);
sv.addView(MyLayout);
timer = new CountDownTimer(500,500) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
isWaiting = false;
}
};
btn = new Button(this);
btn.setText("Accept");
btn.setVisibility(View.INVISIBLE);
MyLayout.addView(btn);
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;
}
else if (id == R.id.action_add) {
et.add(new EditText(this)) ;
tv.add(new TextView(this));
ct.add(new EditText(this));
cb.add(new CheckBox(this));
cb.get(ct.size() -1).setVisibility(View.INVISIBLE);
ct.get(ct.size() -1).setVisibility(View.INVISIBLE);
Calendar cal = Calendar.getInstance();
String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
tv.get(tv.size() -1).setText("created on" + date);
et.get(et.size() - 1).setText("weeeeeeeeeee~!");
MyLayout.addView(et.get(et.size() - 1));
MyLayout.addView(ct.get(ct.size() -1));
MyLayout.addView(tv.get(tv.size() - 1));
MyLayout.addView(cb.get(cb.size() - 1));
this.setContentView(sv);
et.get(last_added).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i=0;i<et.size();i++)
{
if(et.get(i) == v)
{
last_added = i + 1;
break;
}
}
if(isWaiting) {
isWaiting = false;
timer.cancel();
// TODO: open a new EditText
if(ct.get(last_added -1).isShown())
{
ct.get(last_added -1).setVisibility(View.INVISIBLE);
}
else
{
ct.get(last_added -1).setVisibility(View.VISIBLE);
}
}
else {
isWaiting = true;
timer.start();
}
}
});
last_added++;
return true;
}
else if (id == R.id.action_delete) {
btn.setVisibility(View.VISIBLE);
for (int i = 0; i < cb.size(); i++) {
cb.get(i).setVisibility(View.VISIBLE);
}
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int j=0; j < cb.size();j++)
{
if(cb.get(j).isChecked())
{
et.get(j).setVisibility(View.GONE);
tv.get(j).setVisibility(View.GONE);
ct.get(j).setVisibility(View.GONE);
cb.get(j).setVisibility(View.GONE);
et.remove(j);
tv.remove(j);
ct.remove(j);
cb.remove(j);
}
}
btn.setVisibility(View.INVISIBLE);
for (int i = 0; i < cb.size(); i++) {
cb.get(i).setVisibility(View.INVISIBLE);
}
}
});
this.setContentView(sv);
return true;
}
else if (id == R.id.action_search) {
return true;
}
else if (id == R.id.action_send) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
log
10-16 11:10:34.203 13030-13030/com.example.user_pc.notes E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.user_pc.notes, PID: 13030
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.example.user_pc.notes.Mainpage.onOptionsItemSelected(Mainpage.java:125)
at android.app.Activity.onMenuItemSelected(Activity.java:2908)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:325)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:147)
at android.support.v7.internal.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
at android.support.v7.app.AppCompatDelegateImplV7.onMenuItemSelected(AppCompatDelegateImplV7.java:609)
at android.support.v7.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811)
at android.support.v7.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:153)
at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:948)
at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:619)
at android.support.v7.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:139)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
1) Your error
Error shows that in 125 you have IndexOutOfBoundsException exeption.
at com.example.user_pc.notes.Mainpage.onOptionsItemSelected(Mainpage.java:125)
You call get functions on one of your array. There are one item in list. There for maxumum index must be 0 but you call 1 it throws IndexOutOfBoundsException.
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
2)You don't need to create additonal arraylist as yours
private List<EditText> et = new ArrayList<EditText>();
LinearLayout has following methods. And you can get them from your layout.
getChildAt());
getChildCount();
3) You don't need to call following method on ScrollView. It has to automatically
this.setContentView(sv);
4) And finally your code very smashed. Try use standart way. Read android tutorial https://developer.android.com/guide/topics/ui/index.html
fixed it .
The last added was too high when I tried to add new EditText.
public class Mainpage extends AppCompatActivity {
private LinearLayout MyLayout;
private ScrollView sv;
private List<EditText> et = new ArrayList<EditText>();
private List<EditText> ct = new ArrayList<EditText>();
private List<TextView> tv = new ArrayList<TextView>();
private List<CheckBox> cb = new ArrayList<CheckBox>();
private Button btn;
final Context context = this;
private CountDownTimer timer;
boolean isWaiting;
int last_added;
int num_removed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainpage);
last_added = 0;
//btn = (Button) findViewById(R.id.btn);
//btn.setVisibility(View.INVISIBLE);
}
#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_mainpage, menu);
sv = new ScrollView(this);
MyLayout = new LinearLayout(this);
MyLayout.setOrientation(LinearLayout.VERTICAL);
sv.addView(MyLayout);
timer = new CountDownTimer(500,500) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
isWaiting = false;
}
};
btn = new Button(this);
btn.setText("Accept");
btn.setVisibility(View.INVISIBLE);
MyLayout.addView(btn);
///search shit
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;
}
else if (id == R.id.action_add) {
et.add(new EditText(this)) ;
tv.add(new TextView(this));
ct.add(new EditText(this));
cb.add(new CheckBox(this));
cb.get(ct.size() -1).setVisibility(View.INVISIBLE);
ct.get(ct.size() -1).setVisibility(View.INVISIBLE);
Calendar cal = Calendar.getInstance();
String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
tv.get(tv.size() -1).setText("created on" + date);
et.get(et.size() - 1).setText("weeeeeeeeeee~!");
MyLayout.addView(et.get(et.size() - 1));
MyLayout.addView(ct.get(ct.size() -1));
MyLayout.addView(tv.get(tv.size() - 1));
MyLayout.addView(cb.get(cb.size() - 1));
this.setContentView(sv);
et.get(last_added).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i=0;i<et.size();i++)
{
if(et.get(i) == v)
{
last_added = i + 1;
break;
}
}
if(isWaiting) {
isWaiting = false;
timer.cancel();
// TODO: open a new EditText
if(ct.get(last_added -1).isShown())
{
ct.get(last_added -1).setVisibility(View.INVISIBLE);
}
else
{
ct.get(last_added -1).setVisibility(View.VISIBLE);
}
}
else {
isWaiting = true;
timer.start();
}
}
});
last_added++;
return true;
}
else if (id == R.id.action_delete) {
num_removed = 0;
btn.setVisibility(View.VISIBLE);
for (int i = 0; i < cb.size(); i++) {
cb.get(i).setVisibility(View.VISIBLE);
}
btn.setOnClickListener(new View.OnClickListener() {
int checked =0;
#Override
public void onClick(View v) {
while(true)
{
for(int j=0;j< cb.size();j++)
{
if(cb.get(j).isChecked())
{
checked++;
}
}
if(checked == 0)
{
break;
}
for(int i=0;i<cb.size();i++)
{
if(cb.get(i).isChecked())
{
et.get(i).setVisibility(View.GONE);
tv.get(i).setVisibility(View.GONE);
ct.get(i).setVisibility(View.GONE);
cb.get(i).setVisibility(View.GONE);
et.remove(i);
tv.remove(i);
ct.remove(i);
cb.remove(i);
last_added--;
}
}
checked = 0;
}
btn.setVisibility(View.INVISIBLE);
for (int i = 0; i < cb.size(); i++) {
cb.get(i).setVisibility(View.INVISIBLE);
}
}
});
this.setContentView(sv);
return true;
}
else if (id == R.id.action_search) {
btn.setVisibility(View.VISIBLE);
for (int i = 0; i < cb.size(); i++) {
cb.get(i).setVisibility(View.VISIBLE);
}
return true;
}
else if (id == R.id.action_send)
{
btn.setVisibility(View.VISIBLE);
for (int i = 0; i < cb.size(); i++)
{
cb.get(i).setVisibility(View.VISIBLE);
cb.get(i).setChecked(false);
}
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String [] to = new String[]{};
for(int j=0; j < cb.size();j++)
{
if(cb.get(j).isChecked())
{
sendEmail(et.get(j).getText().toString(),ct.get(j).getText().toString());
}
}
btn.setVisibility(View.INVISIBLE);
for (int i = 0; i < cb.size(); i++)
{
cb.get(i).setVisibility(View.INVISIBLE);
}
}});
this.setContentView(sv);
return true;
}
return super.onOptionsItemSelected(item);
}
protected void sendEmail(String subject,String Context)
{
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_SUBJECT,subject);
emailIntent.putExtra(Intent.EXTRA_TEXT,Context);
emailIntent.setType("message/rfc822");
startActivity(Intent.createChooser(emailIntent,"Email"));
}
}
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!
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.