如何将onPostExecute的结果值转换为mainactivity

时间:2018-01-07 06:38:46

标签: android android-asynctask

我正在尝试创建一个应用程序,我可以从剪贴板中翻译复制的字符串,翻译显示在logcat中,但应用程序在将翻译打印到Toast时崩溃 这是代码

enter code here
MainActivity.java
import android.app.*;
import android.content.*;
import android.os.*;
import android.util.*;
import com.sk.translater.TranslatorBackgroundTask;
import java.util.concurrent.*;

public class MainActivity extends Activity 
{

String def;
String textToBeTranslated;
Context context=this;

@Override
protected void onCreate(Bundle savedInstanceState)
{

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //Default variables for translation
    //String textToBeTranslated = "Compare";
    String languagePair = "en-mr"; 

    final ClipboardManager cb = (ClipboardManager)  getSystemService(CLIPBOARD_SERVICE);
    cb.addPrimaryClipChangedListener(new    ClipboardManager.OnPrimaryClipChangedListener(){

            @Override
            public void onPrimaryClipChanged()
            {
                // TODO: Implement this method
                ClipData clipdata = cb.getPrimaryClip();
                ClipData.Item item = clipdata.getItemAt(0);
                if (item.getText() != null)
                {
                    textToBeTranslated = item.getText().toString();


                }
            }
        });
    Translate(textToBeTranslated, languagePair);
}

//Function for calling executing the Translator Background Task
void Translate(String textToBeTranslated, String languagePair)
{
    TranslatorBackgroundTask translatorBackgroundTask= new  TranslatorBackgroundTask(context);

        //String translationResult = 
        translatorBackgroundTask.execute(textToBeTranslated, languagePair);// Returns the translated text as a String
        //Log.d("Translation Result",translationResult); // Logs the result in Android Monitor

}
  }

这是位于github上的TranslatorBackgroundTask.class

enter code here
TranslatorBackgroundTask.java
public class TranslatorBackgroundTask extends AsyncTask<String, Void, String>
{

//Declare Context
Context ctx;
//Set Context
TranslatorBackgroundTask(Context ctx)
{
    this.ctx = ctx;
}

@Override
public String doInBackground(String... params)
{
    //String variables
    String textToBeTranslated = params[0];
    String languagePair = params[1];

    String jsonString;

    try
    {
        //Set up the translation call URL
        String yandexKey = "[MY_KEY]";
        String yandexUrl = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + yandexKey
            + "&text=" + textToBeTranslated + "&lang=" + languagePair;
        URL yandexTranslateURL = new URL(yandexUrl);

        //Set Http Conncection, Input Stream, and Buffered Reader
        HttpURLConnection httpJsonConnection = (HttpURLConnection) yandexTranslateURL.openConnection();
        InputStream inputStream = httpJsonConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        //Set string builder and insert retrieved JSON result into it
        StringBuilder jsonStringBuilder = new StringBuilder();
        while ((jsonString = bufferedReader.readLine()) != null)
        {
            jsonStringBuilder.append(jsonString + "\n");
        }

        //Close and disconnect
        bufferedReader.close();
        inputStream.close();
        httpJsonConnection.disconnect();

        //Making result human readable
        String resultString = jsonStringBuilder.toString().trim();
        //Getting the characters between [ and ]
        resultString = resultString.substring(resultString.indexOf('[') + 1);
        resultString = resultString.substring(0, resultString.indexOf("]"));
        //Getting the characters between " and "
        resultString = resultString.substring(resultString.indexOf("\"") + 1);
        resultString = resultString.substring(0, resultString.indexOf("\""));

        Log.d("Translation Result:", resultString);
        Toast.makeText(ctx, "" + resultString, Toast.LENGTH_LONG).show();

        return jsonStringBuilder.toString().trim();
    }
    catch (MalformedURLException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    return null;
}

@Override
protected void onPreExecute()
{
    super.onPreExecute();
}

@Override
public void onPostExecute(String result)
{
    super.onPostExecute(result);    
}

@Override
protected void onProgressUpdate(Void... values)
{
    super.onProgressUpdate(values);
}    

我如何在另一个类中使用结果值?我试图搜索但没有解决我的问题。

2 个答案:

答案 0 :(得分:0)

由于您将活动的上下文传递给异步任务,因此可以在活动中创建公共方法并从postExecute方法调用它。

$post["title"] = 'Post title Goes Here';
$post["author"] = 'Post author Goes Here';

$post_title = implode(" - ", $post);
// Or to keep it grouped:
$post["post_title"] = implode(" - ", $post);

其中,yourMethodName是一个带有一个字符串参数的公共函数。

答案 1 :(得分:0)

以下是我所做的更改

#include "Student.h"

Student::Student(string student_name, char student_grade)
{
    setName(student_name);
    setGrade(student_grade);
}

string Student::getName()
{
    return _name;
}

char Student::getGrade()
{
    return _grade;
}

void Student::setName(string student_name)
{
    _name = student_name;
}

void Student::setGrade(char student_grade)
{
    _grade = student_grade;
}

TranslatorBackgroundTask.java

enter code here
MainActivity.java
public class MainActivity extends Activity 
{
String textToBeTranslated;
Context context=this;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final String languagePair = "en-mr"; 

    final ClipboardManager cb = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    cb.addPrimaryClipChangedListener(new ClipboardManager.OnPrimaryClipChangedListener(){

            @Override
            public void onPrimaryClipChanged()
            {
                // TODO: Implement this method
                ClipData clipdata = cb.getPrimaryClip();
                ClipData.Item item = clipdata.getItemAt(0);
                if (item.getText() != null)
                {
                    textToBeTranslated = item.getText().toString();
                    Log.d("clipboard value", "" + textToBeTranslated);
                    Translate(textToBeTranslated, languagePair);

                }
            }
        }); 
}

//Function for calling executing the Translator Background Task
void Translate(String textToBeTranslated, String languagePair)
{
    TranslatorBackgroundTask translatorBackgroundTask= new TranslatorBackgroundTask(context);

    //String translationResult = 
    translatorBackgroundTask.execute(textToBeTranslated, languagePair);// Returns the translated text as a String
    //Log.d("Translation Result",translationResult); // Logs the result in Android Monitor  
}

@Override
protected void onPause()
{
    // TODO: Implement this method
    super.onPause();
}
  }